Skip to main content

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-Agent header from the request.
  • Header(None) makes it optional.
  • If not provided, user_agent will be None.

Required Header Exampleโ€‹

@app.get("/secure-data/")
def get_secure_data(api_key: str = Header(...)):
return {"API-Key": api_key}
  • ... makes the api_key header 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-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 TypeSourceUse Case
PathURL pathResource identification
QueryURL query stringFiltering, pagination
BodyRequest body (JSON)Structured data
HeaderHTTP headersMetadata, auth, tracing

Would you like an example of using headers for JWT authentication or API key validation in FastAPI?