Skip to content
tezvyn:
Menu

FastAPI: Reading Request Cookies

Source: fastapi.tiangolo.comEasyHow cards are made

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.

Interview question

What is the primary function of declaring a parameter with Cookie() in a FastAPI path operation?

  • a.To specify a default value for a cookie if it's not provided by the client.
  • b.To retrieve the value of a specific cookie sent by the client in the request.Correct
  • c.To validate the structure and type of all cookies present in the request.
  • d.To define a new cookie that FastAPI should include in the response to the client.
Why?

The card states that `Cookie()` is used to signal to FastAPI that a parameter's value should come from a request cookie, allowing it to extract the value. Option D is incorrect because the card explicitly warns against using `Cookie()` to send cookies back to the client.

Just read this? Test yourself on what you have been reading.

Read the original → fastapi.tiangolo.com

Put your scrolling time to good use

Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on python — each one lists the topics its interview covers.

See open roles