@adan
To do a partial update in FastAPI, you can follow these steps:
Here's an example of how to do a partial update in FastAPI:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
from fastapi import FastAPI
from pydantic import BaseModel
from typing import Optional
app = FastAPI()
class Item(BaseModel):
name: Optional[str]
description: Optional[str]
# Mock data for demonstration purposes
items = {
1: {"name": "Item 1", "description": "Description 1"},
2: {"name": "Item 2", "description": "Description 2"}
}
@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
if item_id not in items:
return {"error": "Item not found"}
existing_item = items[item_id]
if item.name:
existing_item["name"] = item.name
if item.description:
existing_item["description"] = item.description
items[item_id] = existing_item
return items[item_id]
|
In this example, we create a PUT endpoint that accepts an Item object with optional name and description fields. We retrieve the existing item data based on the item_id provided in the URL path, then update the specified fields with the new values from the request body. Finally, we return the updated item data in the response.
You can test this by sending a PUT request to /items/{item_id} endpoint with the fields you want to update in the request body. The endpoint will update the specified fields in the item data and return the updated item.