FastAPI by Example: Header Parameter Extraction
Sometimes you need to read custom headers, such as API keys or user-agent strings. This sample code shows how to define and validate header parameters using the `Header` class.
Code
from fastapi import FastAPI, Header, HTTPException
from typing import Annotated, Union
app = FastAPI()
@app.get("/items/")
async def read_items(
# 1. Simple header
user_agent: Annotated[Union[str, None], Header()] = None,
# 2. Required header with alias
# Clients send 'X-Token', but variable is 'x_token'
x_token: Annotated[str, Header()] = None
):
if x_token != "secret-token":
raise HTTPException(status_code=400, detail="Invalid X-Token header")
return {
"User-Agent": user_agent,
"X-Token": x_token
}
@app.get("/strange-header/")
async def read_strange_header(
# 3. Disable underscore conversion
strange_header: Annotated[Union[str, None], Header(convert_underscores=False)] = None
):
return {"strange_header": strange_header}Explanation
FastAPI allows developers to declare HTTP headers as function parameters using the Header class. By default, FastAPI automatically converts the parameter name from snake_case to hyphenated-case (e.g., user_agent becomes User-Agent) and treats the header name as case-insensitive. This behavior aligns with standard HTTP conventions, making it intuitive to work with common headers without worrying about exact casing or manual string manipulation.
While the automatic conversion covers most use cases, there are scenarios where you might need to accept non-standard headers that strictly contain underscores. In such cases, you can disable the automatic conversion by setting the convert_underscores parameter to False. This gives you full control over the expected header name, ensuring compatibility with legacy systems or specific client requirements that deviate from standard HTTP practices.
Header parameters leverage the same powerful validation system as query and path parameters. You can use standard Python type hints to define whether a header is required or optional, and FastAPI will automatically validate the incoming request. If a required header is missing, the API will respond with a standard 422 Validation Error, providing clear feedback to the client without requiring any custom validation code within your route handler.
Code Breakdown
Header() tells FastAPI to look for the value in the HTTP headers, not the query string.user_agent is automatically mapped to the User-Agent header.x_token maps to X-Token. If the client sends x-token (lowercase), it still works.convert_underscores=False forces FastAPI to look for strange_header exactly as written, with the underscore.
