FastAPI Interactive Docs

Cookie Parameters

Last time, in Extra Data Types, we taught our Blog to handle UUIDs and dates. We have now pulled data from the path, the query, and the body. There is one more spot a request can carry data: cookies. That is where things like a session token usually ride along. 🍪

The nice part: reading a cookie looks exactly like reading a query or path value. Same pattern, new helper.

Reading a cookie

Import Cookie from fastapi and use it inside Annotated, just like Query and Path.

main.py
from typing import Annotated, Optionalfrom fastapi import Cookie, FastAPIapp = FastAPI()@app.get("/blog")async def read_blog(session_id: Annotated[Optional[str], Cookie()] = None):    return {"session_id": session_id}

Let's review:

  1. Cookie() tells FastAPI to look for session_id in the request cookies, not the query string.

  2. The type is Optional[str] with a default of None, so the cookie is optional. No cookie, no problem.

  3. Cookie takes the same extras as Query and Path, like min_length or a description, since they are all siblings.

Send a request with a cookie session_id=abc123 and you get back {"session_id": "abc123"}.

Next Ra: Header Parameters. Cookies have a close cousin, the request header, where things like User-Agent and auth tokens live. Reading headers uses the very same pattern, with one small naming quirk we will sort out. Okie dokie, bye.