Using TypeDicts in FastAPI for PATCH endpoints
This article goes through a quick example of how to use TypedDict
in FastAPI for the body of a PATCH
endpoint.
Consider a FastAPI application with the following endpoints
GET /movies
: Get all moviesGET /movies/{movie_id}
: Get a movie by ID
Here's what the output of the latter endpoint might look like
{
"comment": null,
"id": 1,
"rating": null,
"title": "Pulp Fiction",
"year": 1994
}
and let's say we want to add the following endpoint:
PATCH /movies/{movie_id}
: Update a movie's rating or comment
The HTTP verb PATCH
makes the most sense for this operation, as it's used to apply partial modifications to a resource. The request body should contain only the fields that need to be updated.
Let's look at different implementations and point out the issues with each.
Almost there: Pydantic model with extra="forbid"
The first solution that might come to mind is adding a Pydantic model with the fields that can be updated, and setting extra="forbid"
to prevent any other fields from being passed.
from pydantic import BaseModel, ConfigDict
class MovieUpdate(BaseModel):
model_config = ConfigDict(extra="forbid")
rating: Rating
comment: Comment
@app.patch("/movies/{movie_id}")
def update_movie(movie_id: int, update: schemas.MovieUpdate) -> schemas.MovieRead:
if movie := db.get(doc_id=movie_id):
movie.update(update.model_dump())
db.update(movie, doc_ids=[movie_id])
return schemas.MovieRead.model_validate({"id": movie.doc_id, **movie})
raise HTTPException(
status_code=http.HTTPStatus.NOT_FOUND,
detail="Movie not found",
)
This approach will correctly disallow updating fields that are not in the MovieUpdate
model, such as title
and year
, but fields are required so we cannot omit them from the request body.
We could make the fields optional by setting None
as the default value:
class MovieUpdate(BaseModel):
model_config = ConfigDict(extra="forbid")
rating: Rating | None = None
comment: Comment | None = None
This is not ideal because it allows None
as a valid value for the fields, which is not what we want.
The solution: TypedDict
The TypedDict
class was introduced in Python 3.8. Pydantic has support for it, and it's perfect for this use case.
from typing import TypedDict
from pydantic import ConfigDict, with_config
@with_config(ConfigDict(extra="forbid")) # (1)
class MovieUpdate(TypedDict, total=False): # (2)
rating: Rating
comment: Comment
@app.patch("/movies/{movie_id}")
def update_movie(movie_id: int, update: schemas.MovieUpdate) -> schemas.MovieRead:
if movie := db.get(doc_id=movie_id):
movie.update(update)
db.update(movie, doc_ids=[movie_id]) # (3)
return schemas.MovieRead.model_validate({"id": movie.doc_id, **movie})
raise HTTPException(
status_code=http.HTTPStatus.NOT_FOUND,
detail="Movie not found",
)
- Use Pydantic's
@with_config
decorator to disallow extra fields. - Use
total=False
to make all fields optional. - Since
movie
is a dictionary, we can use it directly to update the fields.
This gives us all the desired behavior:
-
Fields are optional
-
Extra fields are not allowed
-
Fields are not nullable
Appendix: Full code
pyproject.toml | |
---|---|