tezvyn:

FastAPI: Reading Request Cookies

AI-drafted, machine-checkedSource: fastapi.tiangolo.combeginner

FastAPI treats request cookies like any other parameter. Declare them directly in your endpoint's function signature using `Cookie()`, and the framework will extract the value for you. Use this for reading session IDs or user preferences.

WHY IT EXISTS HTTP is stateless, so cookies are used to store data on a client to maintain state across requests. FastAPI provides a clean, declarative way to access this data from incoming requests without manually parsing raw HTTP headers.

THE MENTAL MODEL Think of cookies as pre-sorted function arguments. Instead of receiving a raw HTTP request and digging through headers for a cookie string, you tell FastAPI what you need—ads_id: Annotated[str, Cookie()]—and it delivers the value directly to your function, already validated and type-cast.

HOW IT WORKS First, you import Cookie from fastapi. In your path operation function, you define an argument whose name matches the cookie you want to read. You mark this argument using Cookie() (or the modern Annotated[..., Cookie()] syntax) to signal to FastAPI that its value should come from a request cookie. When a request arrives, FastAPI finds the cookie with the matching name, extracts its value, and passes it to your function.

WHEN TO USE IT Use this pattern to access data stored on the client, such as a session_token for authentication, an ads_id for ad campaign tracking, or a theme preference for UI customization. It's for any data the client sends back to you in a cookie header.

WHEN NOT TO USE IT Do not use the Cookie() parameter declaration to send a cookie back to the client. Setting or modifying cookies is done on the Response object, not as an input parameter. Also, avoid this for receiving large amounts of data, as cookies have size limits and add overhead to every request.

ONE CANONICAL EXAMPLE To read an optional cookie named ads_id, you define your endpoint like this: from fastapi import FastAPI, Cookie and from typing import Annotated. Then, inside your app: @app.get("/items/") async def read_items(ads_id: Annotated[str | None, Cookie()] = None): return {"ads_id": ads_id}. If a request to /items/ includes a cookie ads_id=some_value, the function receives "some_value". If not, it receives None.

Read the original → fastapi.tiangolo.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.