In the last post, Header Parameters, we read values off the request headers. Back in Query Parameter Models, we bundled a pile of query params into one Pydantic model to tidy the signature. Cookies can do the exact same trick. If a request carries several related cookies, group them into a model instead of listing them one at a time. 🍪
Bundling cookies into a model
Put the cookies in a Pydantic model, then declare the parameter with Cookie().
from typing import Annotated, Optionalfrom fastapi import Cookie, FastAPIfrom pydantic import BaseModelapp = FastAPI()class Cookies(BaseModel): session_id: str tracker: Optional[str] = None theme: Optional[str] = None@app.get("/blog")async def read_blog(cookies: Annotated[Cookies, Cookie()]): return cookiesLet's review:
Cookiesholds all three cookies in one place, validations included if you add them.Annotated[Cookies, Cookie()]tells FastAPI to pull each field from the request cookies, not the query string.FastAPI hands you back a ready
Cookiesobject. One model, reusable on any endpoint that needs the same cookies.
Note this needs FastAPI 0.115.0 or newer, the same release that added query parameter models.
Forbidding extra cookies
By default FastAPI ignores cookies you did not declare. If you would rather reject anything unexpected, tell Pydantic to forbid extras.
class Cookies(BaseModel): model_config = {"extra": "forbid"} session_id: str tracker: Optional[str] = None theme: Optional[str] = NoneLet's review:
model_config = {"extra": "forbid"}flips on strict mode.Now a request carrying a stray cookie like
santa_trackergets a clean error instead of being quietly ignored.Handy when you want tight control over exactly what your endpoint accepts.
You guessed it, the same bundling idea applies to headers too. We will group several headers into one model and reuse it across endpoints. See you there.
