FastAPI Interactive Docs

Cookie Parameter Models

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 cookies

Let's review:

  1. Cookies holds all three cookies in one place, validations included if you add them.

  2. Annotated[Cookies, Cookie()] tells FastAPI to pull each field from the request cookies, not the query string.

  3. FastAPI hands you back a ready Cookies object. 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] = None

Let's review:

  1. model_config = {"extra": "forbid"} flips on strict mode.

  2. Now a request carrying a stray cookie like santa_tracker gets a clean error instead of being quietly ignored.

  3. 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.

Practice Lab: