Trung BìnhFastAPI iconFastAPI

Partial update/PATCH trong FastAPI nên thiết kế thế nào?

PATCH nên dùng model riêng với fields optional, sau đó chỉ apply field nào client gửi. Với Pydantic v2, model_dump(exclude_unset=True) giúp phân biệt field không gửi với field gửi giá trị null.

Ví dụ:

python
class UserPatch(BaseModel):
    name: str | None = None
    bio: str | None = None

changes = payload.model_dump(exclude_unset=True)

Không nên reuse model create cho PATCH vì create thường required fields, còn PATCH phải biểu diễn partial mutation.

Xem toàn bộ FastAPI cùng filter theo level & chủ đề con.

Mở danh sách FastAPI