There is some more spot a request can carry data: cookies. That is where things like a auth session token usually ride along. 🍪The nice part: reading a cookie looks exactly like reading a query or path value. Same pattern just a 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 understand the code:
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: 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.
