Header-Parameters
Header 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 required- If 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-Tokenheader 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 Type | Source | Use Case |
|---|---|---|
Path | URL path | Resource identification |
Query | URL query string | Filtering, pagination |
Body | Request body (JSON) | Structured data |
Header | HTTP headers | Metadata, auth, tracing |
Would you like an example of using headers for JWT authentication or API key validation in FastAPI?