Header Parameters
HTTP headers carry metadata: authentication tokens, content negotiation, custom flags. FastAPI reads selected headers as validated parameters with the Header dependency, using the same validation machinery as everything else.
Reading Headers
from fastapi import FastAPI, Header
app = FastAPI()
@app.get("/items/")
def read_items(x_token: str | None = Header(default=None)):
return {"x_token": x_token}
GET /items/ with header X-Token: abc123 returns {"x_token": "abc123"}.
Underscore to Dash Conversion
HTTP headers conventionally use dashes, but Python identifiers cannot. FastAPI converts underscores to dashes automatically: the parameter x_token matches the header X-Token. To match a literal underscore or disable conversion, use the alias parameter:
from fastapi import Header
from typing import Annotated
@app.get("/")
def root(
proxy: Annotated[str, Header(alias="Proxy-Client-IP")] = "unknown",
):
return {"proxy": proxy}
Common Headers
@app.get("/items/")
def read_items(
user_agent: str | None = Header(default=None, alias="User-Agent"),
accept: str | None = Header(default=None),
authorization: str | None = Header(default=None),
):
return {"ua": user_agent, "accept": accept, "auth": authorization is not None}
Authentication Header Pattern
A typical bearer-token check reads the Authorization header and validates the scheme:
from fastapi import Header, HTTPException, status
@app.get("/me/")
def me(authorization: str | None = Header(default=None)):
if not authorization or not authorization.startswith("Bearer "):
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED)
token = authorization.removeprefix("Bearer ")
return {"token_seen": token[:4] + "..."}
Summary
Read headers with Header(default=...) parameters; FastAPI maps underscores to dashes by default and supports alias for exact names. Use this for custom flags and auth tokens, and raise HTTPException 401 when an expected header is missing or malformed.