FastAPI: Implementing Patch and Delete Endpoints

Posted by

Creating patch and delete endpoints with FastAPI

Creating patch and delete endpoints with FastAPI

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. It is designed to be easy to use and provides automatic interactive API documentation. In this article, we will look at how to create patch and delete endpoints using FastAPI.

Creating patch endpoints

To create patch endpoints in FastAPI, we can use the @app.patch() decorator. For example:

        
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None

items = {
    "item1": {"name": "item1", "description": "Description for item1", "price": 10.5, "tax": 0.5}
}

@app.patch("/items/{item_id}")
async def update_item(item_id: str, item: Item):
    items[item_id] = item
    return {"item_id": item_id, "item": item}
    
    

In this example, the update_item function is decorated with @app.patch(), and it takes in the item_id and item as parameters. It then updates the item in the items dictionary and returns the updated item along with the item_id.

Creating delete endpoints

To create delete endpoints in FastAPI, we can use the @app.delete() decorator. For example:

        
@app.delete("/items/{item_id}")
async def delete_item(item_id: str):
    if item_id in items:
        del items[item_id]
        return {"message": "Item deleted"}
    return {"message": "Item not found"}
    
    

In this example, the delete_item function is decorated with @app.delete() and it takes in the item_id as a parameter. It then checks if the item_id exists in the items dictionary and deletes it if it does, returning a message indicating whether the item was deleted or not.

Conclusion

FastAPI makes it easy to create patch and delete endpoints for your API. By using the @app.patch() and @app.delete() decorators, you can quickly define handlers for updating and deleting resources. Combined with its intuitive syntax and built-in documentation, FastAPI is a powerful tool for building modern web APIs with Python.