How to Get Headers in FastAPI: Simple Guide
In FastAPI, you get headers by declaring a function parameter with
Header from fastapi. This lets you access specific headers by name inside your path operation function.Syntax
Use the Header function from fastapi to declare a parameter that extracts a header value. The parameter name should match the header name in lowercase with underscores instead of dashes.
from fastapi import Header: Import the Header helper.header_name: str = Header(None): Declare a parameter to get the header value, defaulting to None if missing.
python
from fastapi import FastAPI, Header app = FastAPI() @app.get("/items/") async def read_items(user_agent: str | None = Header(None)): return {"User-Agent": user_agent}
Example
This example shows how to get the User-Agent header from an incoming request and return it in the response JSON.
python
from fastapi import FastAPI, Header app = FastAPI() @app.get("/headers") async def get_headers(user_agent: str | None = Header(None)): return {"User-Agent": user_agent}
Output
{"User-Agent": "Mozilla/5.0 (example)"}
Common Pitfalls
1. Header names are case-insensitive but must be converted to lowercase with underscores in parameter names. For example, X-Token becomes x_token.
2. Forgetting to import Header causes errors.
3. Using the wrong default value can cause FastAPI to require the header when you want it optional. Use Header(None) for optional headers.
python
from fastapi import FastAPI app = FastAPI() # Wrong: missing Header import and wrong param name @app.get("/wrong") async def wrong(x_token: str): # This will not extract header return {"x_token": x_token} # Correct way from fastapi import Header @app.get("/correct") async def correct(x_token: str | None = Header(None)): return {"x_token": x_token}
Quick Reference
| Concept | Usage |
|---|---|
| Import Header | from fastapi import Header |
| Declare header param | param_name: str | None = Header(None) |
| Header name format | Use lowercase with underscores (e.g., X-Token → x_token) |
| Optional header | Set default to None in Header() |
| Required header | Omit default or set default to ... |
Key Takeaways
Use the Header function from fastapi to access HTTP headers in your endpoint parameters.
Convert header names to lowercase with underscores for parameter names (e.g., X-Token → x_token).
Set Header(None) to make headers optional and avoid errors if missing.
Always import Header from fastapi to avoid runtime errors.
You can access any header by declaring it as a parameter with Header in your path operation.