← Back to FastAPI map
FastAPI · HTTP layer

Headers & cookies

Read the headers and cookies the caller sent, and set your own on the reply.

http

Overview

Headers carry request metadata - auth tokens, content negotiation, tracing ids - and cookies carry browser state such as sessions. FastAPI reads them with Header() and Cookie() just like query parameters, including type conversion. To send them back, add a Response parameter and set values on it while returning your data as usual.

Key concepts

Name conversion
Header() converts underscores to hyphens, so a user_agent parameter reads the User-Agent header. Header names are case-insensitive.
Repeated headers
Type the parameter as a list to receive every value of a header that appears more than once.
Response parameter
A temporary response FastAPI merges into the final one, so you can set headers and cookies without building the response yourself.
Cookie flags
httponly hides the cookie from JavaScript, secure sends it only over HTTPS, and samesite limits sending it on cross-site requests.

Best practices

  • Set httponly, secure, and samesite on every session or auth cookie.
  • Use a request-id header for tracing and echo it back in the response.
  • Never keep secrets in cookies readable by JavaScript - any script on the page can read them.

Headers and cookies

Reading headers

Headers
from fastapi import Header, Response from typing import Optional, List # FastAPI auto-converts hyphen -> underscore # HTTP "user-agent" -> param "user_agent" @app.get("/info") async def info( user_agent: Optional[str] = Header(None), x_request_id: Optional[str] = Header(None), accept_language: Optional[str] = Header(None) ): return {"agent": user_agent, "lang": accept_language} # Duplicate headers -> List @app.get("/tokens") async def tokens(x_token: Optional[List[str]] = Header(None)): return {"tokens": x_token} # Set response headers @app.get("/with-header") async def with_header(response: Response): response.headers["X-Custom"] = "my-value" response.headers["Cache-Control"] = "max-age=3600" return {"msg": "headers set"}

Reading and setting cookies

Cookies
from fastapi import Cookie, Response from typing import Optional # Read request cookies @app.get("/profile") async def profile( session_id: Optional[str] = Cookie(None) ): return {"session": session_id} # Set cookies on response @app.post("/login") async def login(response: Response): response.set_cookie( key="session_id", value="abc123", httponly=True, # JS can't access secure=True, # HTTPS only samesite="lax", # CSRF protection max_age=3600 # 1 hour TTL ) return {"status": "logged in"} # Delete on logout @app.post("/logout") async def logout(response: Response): response.delete_cookie("session_id") return {"status": "logged out"}

Comments

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

Loading comments...