什麼是 PATCH?
HTTP 的 PUT 方法代表「整筆取代」,每次都需傳入所有欄位,PATCH 方法則代表「部分更新」,只需傳入要修改的欄位。
PATCH 基礎語法
- 定義專用的更新模型(Update Schema),所有欄位皆設為選填(
型別 | None = None),讓客戶端只傳入要變更的欄位。 - 使用
model_dump(exclude_unset=True)取得只含「本次實際傳入欄位」的字典,未傳入的欄位不會出現在結果中。 - 使用
existing_item.model_copy(update=update_data)將部分更新套用到原始物件,產生更新後的完整物件。 - 路由裝飾器使用 @app.patch() 而非 @app.put(),語意上代表這是部分欄位的更新操作。
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: int
is_available: bool = True
class ItemUpdate(BaseModel):
name: str | None = None # 所有欄位皆為選填
price: int | None = None
is_available: bool | None = None
fake_db: dict[int, Item] = {
1: Item(name="筆記型電腦", price=35000, is_available=True)
}
@app.patch("/items/{item_id}", response_model=Item)
def update_item(item_id: int, item_update: ItemUpdate):
if item_id not in fake_db:
raise HTTPException(status_code=404, detail="找不到商品")
existing = fake_db[item_id]
# 只取得使用者實際傳入的欄位,忽略未傳入的欄位
update_data = item_update.model_dump(exclude_unset=True)
# 將部分更新套用到原始物件上
updated = existing.model_copy(update=update_data)
fake_db[item_id] = updated
return updated

















