← Back to FastAPI
Lesson 3.4 · Responses & Errors

Headers and Cookies

Read request headers with Header() and cookies with Cookie(), send your own headers, and set and delete cookies with the right options. Built around a "remember my language" cookie, tested with TestClient, curl and a real browser - including a cookie that silently disappeared.

Intermediate30 min

What you will be able to do

  • Read request headers with Header(), with types and lists
  • Understand how FastAPI changes header names (underscore to dash)
  • Send your own response headers
  • Read cookies with Cookie()
  • Set cookies with max_age, httponly, secure and samesite - and delete them
  • Avoid the cookie that is set but never sent

The idea, in plain English

Every HTTP request and response carries headers: short "name: value" lines next to the body. They hold information about the message - which browser, which language, which format, who is logged in. Cookies are a special header: the server says "remember this" (Set-Cookie), and the browser sends it back with every later request (Cookie).

In FastAPI you read them like query parameters: a function argument with Header() or Cookie(). You write them through the Response object. FastAPI checks their types too - a wrong header type is a normal 422.

Our example remembers a visitor’s language in a cookie. We test it with TestClient, with curl, and in a real browser, and try the traps. FastAPI 0.143.0.

Worked example: A greeting API that remembers your language in a cookie - and falls back to the browser’s Accept-Language header when there is no cookie.

workflowA cookie’s lifestep 1 / 3

1 - No cookie yet

GET /greet has no cookie, so the API uses the Accept-Language header the browser sends.

Accept-Language
te-IN,te;q=0.9,en;q=0.8
answer
Namaskaram
Content-Language
te

The server sets the cookie once; the browser sends it back every time. Real results from our language API.

Words you will see in this lesson

A few words about headers and cookies.

Small dictionary
HeaderA "name: value" line sent with a request or response, like User-Agent: curl/8.7.1.
CookieA small named value the browser stores and sends back to the same site.
Set-CookieThe response header that asks the browser to store a cookie.
HttpOnlyA cookie option: page JavaScript cannot read the cookie.
SecureA cookie option: the browser sends it only over HTTPS.
SameSiteA cookie option: whether the cookie is sent when another site starts the request.

An everyday example: a coffee shop loyalty card

  • Every time you visit, you tell the barista a few things - "for here, large, paying by card". Those are headers: facts about this one order.
  • On your first visit the shop gives you a loyalty card: "Ravi - oat milk". That is Set-Cookie.
  • Next time you show the card, and they remember your order. That is the Cookie header coming back.
  • The card has rules: valid for one year (max_age), only for this shop (the domain), and not for others to read (HttpOnly).

Example 1 - remember my language

Four routes:

  • whoami - reads two headers. The argument user_agent reads the User-Agent header and x_request_id reads X-Request-Id: FastAPI changes "_" to "-" and ignores upper and lower case.
  • greet - reads the lang cookie with Cookie(). No cookie? It uses the first two letters of Accept-Language. Unknown? "en". It also sends a Content-Language header back through response: Response.
  • set_language - response.set_cookie(...) with max_age (one year, in seconds), httponly=True and samesite="lax".
  • forget_language - response.delete_cookie("lang").
Example 1 - lang.py
from typing import Annotated from fastapi import Cookie, FastAPI, Header, HTTPException, Response app = FastAPI() GREETINGS = {"en": "Hello", "hi": "Namaste", "te": "Namaskaram", "fr": "Bonjour"} @app.get("/whoami") def whoami( user_agent: Annotated[str | None, Header()] = None, # reads the "User-Agent" header x_request_id: Annotated[str | None, Header()] = None, # reads "X-Request-Id" ): return {"user_agent": user_agent, "request_id": x_request_id} @app.get("/greet") def greet( response: Response, lang: Annotated[str | None, Cookie()] = None, # reads the "lang" cookie accept_language: Annotated[str | None, Header()] = None, ): if lang is None and accept_language: # no cookie: use the browser's language lang = accept_language[:2].lower() if lang not in GREETINGS: lang = "en" response.headers["Content-Language"] = lang # a header we send back return {"message": GREETINGS[lang], "lang": lang} @app.post("/language/{code}") def set_language(code: str, response: Response): if code not in GREETINGS: raise HTTPException(status_code=404, detail="Unknown language") response.set_cookie("lang", code, max_age=60 * 60 * 24 * 365, # remember for one year httponly=True, samesite="lax") return {"saved": code} @app.delete("/language") def forget_language(response: Response): response.delete_cookie("lang") return {"forgotten": True}
try_lang.py
from fastapi.testclient import TestClient from lang import app c = TestClient(app) def show(label, r): extra = "" if "set-cookie" in r.headers: extra = "\n Set-Cookie: " + r.headers["set-cookie"] if "content-language" in r.headers: extra += " Content-Language=" + r.headers["content-language"] print(f"{label:<22} -> {r.status_code} {r.text}{extra}") show("whoami", c.get("/whoami", headers={"X-Request-Id": "abc-123"})) show("greet (nothing)", c.get("/greet")) show("greet (browser: te)", c.get("/greet", headers={"Accept-Language": "te-IN,te;q=0.9,en;q=0.8"})) show("save hi", c.post("/language/hi")) print(" client cookies now:", dict(c.cookies)) show("greet (cookie: hi)", c.get("/greet", headers={"Accept-Language": "te-IN"})) show("save xx", c.post("/language/xx")) show("forget", c.delete("/language")) print(" client cookies now:", dict(c.cookies)) show("greet (no cookie)", c.get("/greet"))

Reading the output

  • whoami - TestClient sends User-Agent: testclient, and our X-Request-Id arrived.
  • With no cookie, Accept-Language "te-IN,..." gave Namaskaram.
  • save hi - the response carried Set-Cookie: lang=hi; HttpOnly; Max-Age=31536000; Path=/; SameSite=lax. TestClient stored it, like a browser.
  • Next request: the cookie said hi and the header said te - the cookie won: Namaste.
  • forget - delete_cookie sends the same cookie with an empty value, Max-Age=0 and an expiry time now. The client removed it.
Output
whoami -> 200 {"user_agent":"testclient","request_id":"abc-123"} greet (nothing) -> 200 {"message":"Hello","lang":"en"} Content-Language=en greet (browser: te) -> 200 {"message":"Namaskaram","lang":"te"} Content-Language=te save hi -> 200 {"saved":"hi"} Set-Cookie: lang=hi; HttpOnly; Max-Age=31536000; Path=/; SameSite=lax client cookies now: {'lang': 'hi'} greet (cookie: hi) -> 200 {"message":"Namaste","lang":"hi"} Content-Language=hi save xx -> 404 {"detail":"Unknown language"} forget -> 200 {"forgotten":true} Set-Cookie: lang=""; expires=Mon, 12 Oct 2026 16:36:08 GMT; Max-Age=0; Path=/; SameSite=lax client cookies now: {} greet (no cookie) -> 200 {"message":"Hello","lang":"en"} Content-Language=en

The same with curl

With uvicorn running, curl shows two more things:

  • A header written with underscores, X_Request_Id, was NOT read - request_id was null. Header names use dashes; underscores in your Python name become dashes.
  • curl -c jar.txt saves cookies to a file and -b jar.txt sends them back. The jar line starts with #HttpOnly_.
Output - curl
$ curl -s http://127.0.0.1:8332/whoami -H "X-Request-Id: abc-123" {"user_agent":"curl/8.7.1","request_id":"abc-123"} $ curl -s http://127.0.0.1:8332/whoami -H "X_Request_Id: abc-123" {"user_agent":"curl/8.7.1","request_id":null} $ curl -s -c jar.txt -X POST http://127.0.0.1:8332/language/fr {"saved":"fr"} $ curl -s -b jar.txt http://127.0.0.1:8332/greet {"message":"Bonjour","lang":"fr"} $ grep lang jar.txt #HttpOnly_127.0.0.1 FALSE / FALSE 1823358992 lang fr

Headers with types, lists and exact names

Header() works like Query():

  • x_page: int reads X-Page and converts it. x-page in small letters worked too - header names ignore case.
  • "two" gave a normal 422, with loc ["header", "x-page"].
  • list[str] collects a header sent twice: ["new", "sale"]. But one header with a comma, "new, sale", stayed one value.
  • Header(convert_underscores=False) reads the name exactly: it found x_token and ignored X-Token. Rarely needed - and some proxies drop headers with underscores.
htraps.py - the header routes
@app.get("/page") def page(x_page: Annotated[int, Header()] = 1): # a typed header return {"page": x_page} @app.get("/tags") def tags(x_tag: Annotated[list[str] | None, Header()] = None): # the same header many times return {"tags": x_tag} @app.get("/raw") def raw(x_token: Annotated[str | None, Header(convert_underscores=False)] = None): return {"x_token": x_token}
Output
X-Page: 3 -> 200 {"page":3} x-page: 3 -> 200 {"page":3} X-Page: two -> 422 {"detail":[{"type":"int_parsing","loc":["header","x-page"],"msg":"Input should be a valid integer, unable to parse string as an integer","input":"two"}]} X-Tag twice -> 200 {"tags":["new","sale"]} X-Tag: new, sale -> 200 {"tags":["new, sale"]} raw X-Token -> 200 {"x_token":null} raw x_token -> 200 {"x_token":"t1"}

Cookie options: what each one does

set_cookie takes options. Choose them on purpose:

  • max_age - seconds until the browser forgets it. Without it, the cookie lives until the browser closes.
  • httponly=True - page JavaScript cannot read it. In a real browser (Playwright), document.cookie showed only theme=dark; the HttpOnly lang=hi was stored but hidden. Use it for anything about login.
  • secure=True - sent only over HTTPS. Over http://testserver the client stored nothing it would send back (session: null); over https:// it came back.
  • samesite="lax" (the default here) - not sent when another site posts a form to yours. "strict" is tighter; "none" needs secure=True.
Output - a real browser (Playwright)
document.cookie in the page: "theme=dark" cookies the browser stored: lang=hi (httpOnly: true), theme=dark (httpOnly: false)

Tip: You test on http://localhost, but production runs on HTTPS. If a cookie with secure=True "does not work" on your machine, this is why.

The cookie that disappeared

A real trap: login_lost set a cookie on the injected response, then returned a NEW JSONResponse.

  • The new response was sent, the injected one was thrown away - no Set-Cookie at all, and no error.
  • login_kept sets the cookie on the response it returns: it works.
  • Rule: use response: Response and return a dict - or build your own Response and set everything on it. Do not mix the two.
  • Also: a value with a comma or space is quoted and encoded ("Ravi Kumar\054 Hyderabad"). Cookie() decoded it back correctly, but other clients may not - keep cookie values simple, like an id.
htraps.py - the cookie routes
@app.post("/login-lost") def login_lost(response: Response): response.set_cookie("session", "s-42") # set on the injected response... return JSONResponse({"ok": True}) # ...but we return a NEW response @app.post("/login-kept") def login_kept(): reply = JSONResponse({"ok": True}) reply.set_cookie("session", "s-42") # set on the response we return return reply
Output
/login-lost Set-Cookie: None then /session -> {"session":null} /login-kept Set-Cookie: session=s-42; Path=/; SameSite=lax then /session -> {"session":"s-42"} secure Set-Cookie: session=s-42; HttpOnly; Path=/; SameSite=lax; Secure over http: /session -> {"session":null} over https: /session -> {"session":"s-42"} name Set-Cookie: name="Ravi Kumar\054 Hyderabad"; Path=/; SameSite=lax read back -> {"name":"Ravi Kumar, Hyderabad"}

What belongs in a cookie?

A cookie is stored by the client - and the client can change it.

  • Good: small settings (language, theme) and a random session id that points to data on the server.
  • Bad: a user id or a role ("admin=true") that you trust as it is. Anyone can edit their cookies.
  • Logins use signed tokens or server sessions (Module 6).
  • Always treat cookies and headers like any other input: check them. Our greet() turned an unknown lang into "en".

Headers and cookies at a glance

Read a header

_ becomes -, any case.

x_request_id: Annotated[str | None, Header()] = None
Repeated header

Each copy is one item.

x_tag: Annotated[list[str] | None, Header()] = None
Send a header

Through the injected response.

response.headers["Content-Language"] = "hi"
Read a cookie

None when missing.

lang: Annotated[str | None, Cookie()] = None
Set a cookie

Choose the options.

response.set_cookie("lang", "hi", max_age=31536000,
  httponly=True, secure=True, samesite="lax")
Delete a cookie

Max-Age=0.

response.delete_cookie("lang")

Try it yourself

The code does not change. Swap the content string and the program does something else entirely.

Your browser’s language

“Run fastapi dev lang.py and open /greet in your browser. Which Accept-Language did it send? Look in the Network tab.”

See the cookie

“Call POST /language/fr from /docs, then open the browser tools (Application -> Cookies). Which options do you see?”

Session cookie

“Remove max_age, set the cookie again, and close the browser. Is it still there?”

A header in /docs

“Look at /whoami in /docs. How are the header parameters shown?”

What usually goes wrong

Setting a cookie and returning a new Response

The injected response is thrown away, with its cookie.

✗ response.set_cookie("s", "1")
return JSONResponse({...})
✓ response.set_cookie("s", "1")
return {...}
Sending headers with underscores

x_request_id in Python reads X-Request-Id. A header called X_Request_Id is not read.

secure=True and testing on http

The client will not send the cookie back over plain http.

Trusting a cookie value

Clients can change cookies. Never store "is_admin=true" and believe it.

Practice

Write these yourself before opening anything. Getting them wrong first is most of how this sticks.

1.

Add a "theme" setting: POST /theme/{name} (only "light" or "dark", else 422) sets a theme cookie for 30 days, and GET /greet also returns the theme ("light" when there is no cookie). Then add an X-Response-Time header to /greet with the time the function took, in milliseconds.

Show hint

Use a Literal or an Enum for the path parameter. time.perf_counter() before and after.

Key points

  • Header() and Cookie() read request data like Query() - with types and 422s.
  • In Python names, _ becomes - for headers; header names ignore case.
  • A header sent twice becomes a list with list[str]; a comma does not split it.
  • Set headers and cookies on the injected response: Response, then return data.
  • httponly hides a cookie from JavaScript; secure sends it only over HTTPS; max_age sets its life.
  • delete_cookie sends the cookie again with Max-Age=0.
  • Cookies come from the client - check them like any input.

Quick check before you move on

Which header does the argument x_request_id read?
X-Request-Id (in any case).
What does Max-Age=31536000 mean?
Keep the cookie for 31,536,000 seconds - one year.
What did document.cookie show in the browser?
Only theme=dark - the HttpOnly cookie lang=hi was hidden.
What did "X-Page: two" give?
422 int_parsing with loc ["header", "x-page"].

Interview questions

Which cookie attributes would you set for a session cookie, and why?

HttpOnly (no JS access, limits XSS theft), Secure (HTTPS only), SameSite=Lax or Strict (CSRF protection), a sensible Max-Age, and Path=/ - plus a random, server-validated value rather than user data.

Cookies or an Authorization header for an API?

Browsers send cookies automatically, which suits same-site web apps but needs CSRF care. Authorization: Bearer headers suit mobile apps, other services and cross-site clients, and are not sent automatically.

Why might a header with underscores never reach your app?

Many proxies and servers (for example nginx by default) drop headers with underscores, and FastAPI maps _ to - when reading. Use dashes in header names.

Quiz

  1. 1.

    Why did /login-lost send no Set-Cookie?

  2. 2.

    Why did the secure cookie not come back over http://testserver?

  3. 3.

    In greet(), which wins: the cookie or Accept-Language?

  4. 4.

    How does delete_cookie remove a cookie?

Comments

Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.

Loading comments...