← Back to FastAPI, page 1

fastapi-0012 · Easy fresher

How do you read headers and cookies in FastAPI, and how do you set them on the response?

Read headers with Header() and cookies with Cookie() parameters; FastAPI converts underscores in header parameter names to hyphens, so user_agent reads User-Agent. To set values, accept a Response parameter and call response.headers[...] = ... or response.set_cookie(...), or return a Response object with headers. Use httponly, secure and samesite flags for cookies that carry sessions.

Full answer

Reading headers:

python
def endpoint(user_agent: Annotated[str | None, Header()] = None,
             x_request_id: Annotated[str | None, Header()] = None): ...
  • Header names are case-insensitive. FastAPI converts x_request_id to x-request-id automatically. Disable with Header(convert_underscores=False) (rarely needed; some proxies drop headers with underscores).
  • Repeated headers: x_tag: Annotated[list[str] | None, Header()] = None.
  • Since FastAPI 0.115 a Pydantic model can group headers: headers: Annotated[CommonHeaders, Header()].

Reading cookies:

python
def endpoint(session_id: Annotated[str | None, Cookie()] = None): ...

Setting values on the response:

  • Add a response: Response parameter, then response.headers["X-Total-Count"] = "42" or response.set_cookie(...). FastAPI merges these into the final response, even when you return a dict or model.
  • Or return a JSONResponse and call methods on it.

Cookie flags matter for security:

  • httponly=True: JavaScript cannot read it, which limits damage from XSS.
  • secure=True: only sent over HTTPS.
  • samesite="lax" (or "strict"): reduces cross-site request forgery risk.
  • max_age or expires: lifetime; response.delete_cookie("session_id") to log out.

If a browser front end on another origin reads custom headers like X-Total-Count, list them in CORS expose_headers, or the browser hides them from JavaScript. For cookies sent cross-site, samesite="none" requires secure=True and CORS with allow_credentials=True.

python
from typing import Annotated

from fastapi import Cookie, FastAPI, Header, Response
from fastapi.testclient import TestClient

app = FastAPI()


@app.get("/whoami")
def whoami(
    user_agent: Annotated[str | None, Header()] = None,
    x_request_id: Annotated[str | None, Header()] = None,
    theme: Annotated[str, Cookie()] = "light",
):
    return {"user_agent": user_agent, "request_id": x_request_id, "theme": theme}


@app.post("/login")
def login(response: Response):
    response.set_cookie("session_id", "s-8f3a", httponly=True, secure=True, samesite="lax", max_age=3600)
    response.headers["X-Login-Count"] = "1"
    return {"ok": True}


c = TestClient(app, base_url="https://testserver")
print(c.get("/whoami", headers={"User-Agent": "CampusApp/2.1", "X-Request-ID": "abc-123"},
            cookies={"theme": "dark"}).json())
r = c.post("/login")
print(r.json(), r.headers["x-login-count"])
print(r.headers["set-cookie"])

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): {'user_agent': 'CampusApp/2.1', 'request_id': 'abc-123', 'theme': 'dark'} {'ok': True} 1 session_id=s-8f3a; HttpOnly; Max-Age=3600; Path=/; SameSite=lax; Secure

Key points

  • Header() and Cookie() read request values
  • Underscores convert to hyphens for header names
  • A Response parameter lets you set headers and cookies
  • Use httponly, secure and samesite on session cookies
  • Expose custom headers via CORS for browser clients

Common mistakes

  • Expecting header parameter names with underscores to match exactly without conversion
  • Setting session cookies without httponly and secure
  • Forgetting CORS expose_headers so the browser hides custom headers
  • Creating a new Response object and losing the headers you set on the injected one

Follow-ups

  • How would you implement logout with cookies?
  • Why do some proxies drop headers that contain underscores?
  • When should you choose cookies over bearer tokens for a web app?

Tips

  • Mention the underscore to hyphen conversion
  • Name all three cookie security flags and why
  • Bring up CORS expose_headers for browser clients