How to Use Header in FastAPI: Simple Guide with Examples
In FastAPI, you use the
Header function from fastapi to declare HTTP headers as parameters in your path operation functions. This lets you access header values directly by naming them as function arguments with Header type hints.Syntax
Use Header from fastapi to declare a header parameter in your endpoint function. The header name is inferred from the parameter name but can be customized. You can also set default values or make headers optional.
- Parameter name: The Python function argument name.
- Header(...): Marks the parameter as coming from HTTP headers.
- default value: Optional, sets a default if header is missing.
- alias: Use to specify a different header name if it contains dashes or case differences.
python
from fastapi import FastAPI, Header from typing import Optional app = FastAPI() @app.get("/items/") async def read_items(user_agent: Optional[str] = Header(None)): return {"User-Agent": user_agent}
Example
This example shows how to read the User-Agent header from a request. The header value is returned in the JSON response. If the header is missing, it returns null.
python
from fastapi import FastAPI, Header from typing import Optional app = FastAPI() @app.get("/headers/") async def get_headers(user_agent: Optional[str] = Header(None), x_token: Optional[str] = Header(None, alias="X-Token")): return {"User-Agent": user_agent, "X-Token": x_token}
Output
{"User-Agent": "Mozilla/5.0", "X-Token": "abc123"}
Common Pitfalls
- Header names are case-insensitive but Python variables are case-sensitive: Use
aliasto match header names with dashes or different casing. - Missing headers: If a header is required but missing, FastAPI returns a 422 error unless you provide a default or make it optional.
- Do not use underscores in parameter names expecting dashes in headers: Use
aliasto map them correctly.
python
from fastapi import FastAPI, Header from typing import Optional app = FastAPI() # Wrong: header with dash not matched correctly @app.get("/wrong/") async def wrong_header(x_token: Optional[str] = Header(None)): return {"X-Token": x_token} # Right: use alias to match header name @app.get("/right/") async def right_header(x_token: Optional[str] = Header(None, alias="X-Token")): return {"X-Token": x_token}
Quick Reference
Remember these tips when using Header in FastAPI:
- Use
Headerto declare header parameters. - Use
aliasto handle headers with dashes or different casing. - Set default values or use
Optionalto avoid errors if headers are missing. - Headers are strings; convert if needed inside your function.
Key Takeaways
Use the Header function from fastapi to read HTTP headers as function parameters.
Use alias to match header names with dashes or different casing.
Make headers optional or provide defaults to avoid validation errors.
Header parameters are strings; convert them if you need other types.
FastAPI automatically extracts headers when you declare them with Header.