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.
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:
Cookie()tells FastAPI to look forsession_idin the request cookies, not the query string.The type is
Optional[str]with a default ofNone, so the cookie is optional. No cookie, no problem.Cookietakes the same extras asQueryandPath, likemin_lengthor adescription, 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.
