In FastAPI, how do you implement a PATCH endpoint that changes only the product fields the client actually sent?
answer
- defaults overwrite stored data
- a separate all-optional model
- fields the client set
- copy with an update dict
basics
~10 sDeclare an update model whose fields all default to None, then merge only patch.model_dump(exclude_unset=True) into the stored product. Fields the client omitted never appear in that dict, so they keep their stored values.
solid answer
~30 sFastAPI gives `PATCH` no special meaning, so the handler does the work. Validating the body into the full `Product` model would fill omitted fields with defaults and overwrite stored data, or answer 422 for missing required fields. Instead declare a `ProductUpdate` model where every field defaults to `None`, call `patch.model_dump(exclude_unset=True)` to get only the keys the client sent, and build the result with `stored.model_copy(update=changes)`. `exclude_unset` keeps an explicit `null`, so a client can clear `description`; `exclude_none` would silently drop it. Because `model_copy` does not validate the update values, re-validate the merged data or forbid `null` for fields the stored model requires.
code
python · 32 linesfrom fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
class Product(BaseModel):
name: str
description: str | None = None
price: float
tags: list[str] = []
class ProductUpdate(BaseModel):
name: str | None = None
description: str | None = None
price: float | None = None
tags: list[str] | None = None
products = {"lamp": Product(name="Desk lamp", price=40.0, tags=["home"])}
@app.patch("/products/{product_id}")
async def update_product(product_id: str, patch: ProductUpdate) -> Product:
stored = products.get(product_id)
if stored is None:
raise HTTPException(status_code=404, detail="Product not found")
changes = patch.model_dump(exclude_unset=True) # only what the client sent
updated = stored.model_copy(update=changes)
products[product_id] = updated
return updatedgo deeper
Recall that a PATCH needs a separate model with every field optional, and that model_dump(exclude_unset=True) returns only the fields the client sent.
Walk through the merge: load, validate into the update model, dump with exclude_unset, model_copy with update, save. Explain why exclude_none would stop clients clearing a field.
Point out that model_copy skips validation, so nulls for required fields reach storage, and that nested lists are replaced rather than merged. Show how you would re-validate the merged product.
Decide whether a team standardises on PATCH with explicit null semantics or full PUT replacement, and how that choice is documented so clients know absent from null.
## The problem with updating through a full model A product in the catalog has a `name`, a `price`, an optional `description` and a list of `tags` that defaults to `[]`. If a `PUT` endpoint validates its body as that same `Product` model, every field the client leaves out is filled from the model's **defaults**. A client that sends only a new name and price overwrites the stored tags with `[]`, because the validated model really does contain an empty list. FastAPI's own tutorial calls this out: a replacing update takes default values for anything not sent, and saves them. FastAPI imposes no semantics on `PUT` or `PATCH`. Both are just decorators. A **partial update** is something you build in the handler, and the tool for it is knowing which fields the client actually sent. ## The update model The first step is an input model in which nothing is required: ```python class ProductUpdate(BaseModel): name: str | None = None description: str | None = None price: float | None = None tags: list[str] | None = None ``` - **Every field has a default**, so a body of `{"price": 35.5}` validates. Reusing `Product` would answer 422 because `name` is missing. - **The input is still validated.** A price of `"cheap"` is rejected exactly as it would be on creation. - **Create and update models stay separate.** The create model keeps its required fields; the update model relaxes them. FastAPI's tutorial points to separate models for creation and for updates. ## exclude_unset: what the client sent A Pydantic 2 model remembers which fields were set explicitly during validation. `model_dump(exclude_unset=True)` returns only those: | Request body | `model_dump()` | `model_dump(exclude_unset=True)` | |---|---|---| | `{"price": 35.5}` | all four keys, three of them `None` | `{"price": 35.5}` | | `{"description": null}` | all four keys | `{"description": None}` | | `{}` | all four keys, all `None` | `{}` | That dict is the patch. Fields absent from the request never appear in it, so they cannot overwrite stored data. ## Merging into the stored product The recipe from FastAPI's tutorial, applied to the product PATCH: 1. Load the stored product and answer 404 if it does not exist. 2. Validate the body into `ProductUpdate`. 3. Take `changes = patch.model_dump(exclude_unset=True)`. 4. Build the updated product with `stored.model_copy(update=changes)`. 5. Save it and return it. The same technique works for `PUT` if a team prefers that method; what matters is `exclude_unset`, not the verb. ## exclude_unset, exclude_none and exclude_defaults The three look interchangeable and are not: - **`exclude_unset=True`** keeps what the client sent, including an explicit `null`. That is how a client clears an optional field such as `description`. - **`exclude_none=True`** drops every `None`, so the explicit `null` disappears and the client can never clear a field. - **`exclude_defaults=True`** drops values equal to the field's default. In the update model the default is `None`, so an explicit `null` disappears here too. For a PATCH, `exclude_unset=True` alone is the one that distinguishes "absent" from "set to null". ## Traps in the merge - **`model_copy(update=...)` does not validate.** The update values are copied in as they are. A client that sends `{"name": null}` produces a `Product` whose required `name` is `None`. Either forbid `null` for fields the stored model requires, or validate the merged data again, for example with `Product.model_validate(stored.model_dump() | changes)`, and reject the request when that fails. - **Nested objects are replaced, not merged.** Sending `{"tags": ["sale"]}` replaces the whole list; there is no element-wise merge. - **Storage conversion is a separate step.** FastAPI's tutorial converts the result with `jsonable_encoder` before saving to a JSON store, so values such as `datetime` become strings. - **An empty body is a valid no-op.** `{}` validates against the update model and yields an empty update dict; decide whether the endpoint returns the unchanged product or rejects an update that changes nothing. - **Table models have their own helper.** When the stored object is an ORM table model rather than a plain Pydantic model, the update call differs; that belongs with the data-layer material. A middle-level answer names the update model and `exclude_unset=True`; a stronger one explains why `exclude_none` breaks clearing, and that `model_copy` skips validation.
- In a FastAPI PATCH handler, why is `exclude_unset=True` better than `exclude_none=True` for building the update dict?`exclude_none=True` drops every `None`, so a client sending `{"description": null}` to clear the description is ignored. `exclude_unset=True` keeps that explicit `null`, because the client set it, while still leaving out fields that were absent from the request.
- What can go wrong when a FastAPI PATCH handler merges changes with `stored.model_copy(update=changes)`?`model_copy` does not validate the update values. A client sending `{"name": null}` leaves a `Product` whose required `name` is `None`, which then reaches storage. Re-validate the merged data, for example `Product.model_validate(stored.model_dump() | changes)`, and reject the request when it fails, or disallow `null` for those fields in the update model.
- FastAPI applies partial-update semantics automatically to @app.patch endpoints
- Reusing the create model for PATCH works because missing fields are skipped
- exclude_none=True is the way to find which fields the client sent
- model_copy(update=...) validates the new values like the constructor does
- A PUT that validates the full model only changes the fields sent