Header Parameters in FastAPI#
In FastAPI, a Header parameter is used to extract and validate values from the HTTP request headers. These are often used for things like:
Authentication tokens (e.g.,
Authorization)Custom headers (e.g.,
X-Request-ID)Content negotiation (e.g.,
Accept,User-Agent)
Basic Example#
from fastapi import FastAPI, Header
app = FastAPI()
@app.get("/items/")
def read_items(user_agent: str = Header(None)):
return {"User-Agent": user_agent}
This reads the
User-Agentheader from the request.Header(None)makes it optional.If not provided,
user_agentwill beNone.
Required Header Example#
@app.get("/secure-data/")
def get_secure_data(api_key: str = Header(...)):
return {"API-Key": api_key}
...makes theapi_keyheader requiredIf missing, FastAPI returns a 422 error
Header Name Conventions#
HTTP headers are case-insensitive and use hyphens (e.g.,
X-Token)FastAPI automatically converts underscore
_to hyphen-
@app.get("/check/")
def check_header(x_token: str = Header(...)):
return {"X-Token": x_token}
This will correctly read the X-Token header from the request.
Example with Multiple Headers#
@app.get("/info/")
def get_info(
x_token: str = Header(...),
x_request_id: str = Header(None)
):
return {"token": x_token, "request_id": x_request_id}
Summary: Parameter Types#
Parameter Type |
Source |
Use Case |
|---|---|---|
|
URL path |
Resource identification |
|
URL query string |
Filtering, pagination |
|
Request body (JSON) |
Structured data |
|
HTTP headers |
Metadata, auth, tracing |