skip to content

In FastAPI, how does a Header() parameter named user_agent find the User-Agent header, and why must headers and cookies be declared explicitly?

level: middleimportance: should knowfreq 35%

answer

  1. never inferred from the name
  2. underscore becomes hyphen
  3. case does not matter
  4. convert_underscores and proxies

basics

~20 s

Header() converts underscores in the parameter name to hyphens and matches case-insensitively, so user_agent reads User-Agent. Without Header() or Cookie(), FastAPI treats the same parameter as a query parameter, because sources other than path, query and body are never inferred.

solid answer

~40 s

FastAPI only infers path, query and body, so a header or cookie needs `Header()` or `Cookie()`, usually inside `Annotated`; otherwise `user_agent: str | None = None` is just a query parameter. `Header()` has `convert_underscores=True` by default: `user_agent` is looked up as `user-agent`, and since header names are case-insensitive it matches `User-Agent`. Since FastAPI 0.136.3 the underscore spelling `user_agent` sent by a client is not accepted while conversion is on. `convert_underscores=False` reads the literal underscore name, but some proxies and servers drop such headers. Declaring `list[str]` collects a repeated header, and a required header that is missing gets a 422 with `loc` `["header", "x-api-version"]`.

code

python · 16 lines
python
from typing import Annotated

from fastapi import Cookie, FastAPI, Header

app = FastAPI()


@app.get("/catalogue")
async def catalogue(
    x_api_version: Annotated[int, Header(ge=1)],
    user_agent: Annotated[str | None, Header()] = None,
    x_token: Annotated[list[str] | None, Header()] = None,
    session_id: Annotated[str | None, Cookie()] = None,
):
    return {"version": x_api_version, "ua": user_agent,
            "tokens": x_token, "session": session_id}

go deeper

for a junior

Recall that headers need Header() and cookies need Cookie(), and that user_agent maps to User-Agent automatically.

for a middle

Explain convert_underscores, case-insensitive lookup, list types for repeated headers, and the 422 loc for a missing required header.

for a senior

Flag that FastAPI 0.143 ignores the underscore spelling, that proxies may drop underscore headers, and that client-set headers are never identity without a trusted component in front.

for a principal

Decide which request metadata the app may read from headers at all, and route identity through the security classes or a trusted gateway rather than ad hoc Header() reads.

## Headers and cookies are opt-in sources FastAPI's inference covers three sources: a name in the path template is a **path** parameter, a scalar is a **query** parameter, a model is the **body**. Headers and cookies are **never inferred**, however a parameter is named. To read them you declare the marker: ```python user_agent: Annotated[str | None, Header()] = None session_id: Annotated[str | None, Cookie()] = None ``` Leave the marker out and both become query parameters named `user_agent` and `session_id`, which is a common reason for "the header is always None". ## How Header() maps a Python name to a header name Header names such as `User-Agent` or `X-API-Version` contain hyphens, which Python identifiers cannot. `Header()` therefore has a parameter `convert_underscores`, **`True` by default**: 1. The parameter name `x_api_version` becomes the alias `x-api-version`. 2. Header lookup is **case-insensitive**, so `X-API-Version`, `x-api-version` and `X-Api-Version` all match. 3. The schema at `/docs` documents the hyphenated name. Since **FastAPI 0.136.3**, with conversion on, a client sending the underscore spelling `x_api_version` no longer fills the parameter; only the hyphenated header does. Code or clients that relied on the underscore fallback in older releases stop receiving the value. ## Options and edge cases | Need | Declaration | Behaviour | |---|---|---| | A header with underscores in its real name | `Header(convert_underscores=False)` | reads `strange_header` literally | | An arbitrary header name | `Header(alias="X-Trace")` | an explicit alias is used as given | | A header sent more than once | `Annotated[list[str] \| None, Header()]` | every value, as a list | | A typed, validated header | `Annotated[int, Header(ge=1)]` | 422 on a non-integer or out-of-range value | Points to keep in mind: - FastAPI's docs warn that **some HTTP proxies and servers disallow headers with underscores**, so a header that works in local tests can vanish in production when `convert_underscores=False` is used. - A **required** header that is missing produces `{"type": "missing", "loc": ["header", "x-api-version"]}`, again a 422. - `Cookie()` reads a cookie by its parameter name or `alias`. The interactive docs page **cannot send cookies** you type in, because it sends requests from page JavaScript, which browsers do not let set a `Cookie` header; trying a cookie parameter from `/docs` reports it as missing. ## What the function receives - A `str` annotation receives the header's value as text; an `int` or other type is converted and validated exactly like a query parameter, with 422 on failure. - A `list[str]` annotation receives every value of a repeated header, one element per header line. - A missing optional header leaves the default, usually `None`. - A group of related headers or cookies can also be declared as one Pydantic model marked with `Header()` or `Cookie()`, with the same underscore conversion applied to the model's field names. ## Reading headers defensively Headers and cookies are **client-controlled input**, exactly like the query string: - Validate them with types and constraints instead of trusting free-form strings. - Never treat a header such as `X-User-Id` read through `Header()` as proof of identity; the client can set it to anything unless a component in front overwrites it, and trusting forwarded headers is a deployment decision covered with reverse proxy setup. - Credentials sent in headers or cookies belong to FastAPI's security classes, which add the right docs and 401 behaviour, rather than to a bare `Header()`. ## Checklist - Declare every header and cookie with its marker. - Prefer the default conversion and hyphenated header names. - Use `list[...]` when a header can repeat. - Test the endpoint through the same proxy chain it runs behind if you depend on unusual header names.

  • In FastAPI, when would you set `convert_underscores=False` on a Header(), and what is the risk?
    Only when a client really sends a header whose name contains underscores and you cannot change it. With conversion off, FastAPI reads the literal name. The risk, which FastAPI's docs call out, is that some proxies and servers drop or reject headers with underscores, so the value may never reach the app in production.
  • In FastAPI, how does a required header's absence differ from a required query parameter's absence?
    It does not differ in mechanism: both are validated the same way and produce a 422 of type `missing`. Only the `loc` changes, to `["header", "x-api-version"]`, using the hyphenated alias rather than the Python name, which helps when you read client error reports.

  • A parameter named user_agent is read from the User-Agent header without Header().
  • Header() needs the exact capitalisation, so it must be declared as User_Agent.
  • Clients may send x_token or x-token interchangeably to a FastAPI Header() parameter.
  • A repeated header can only be read through the raw Request object.
  • A header value read with Header() can be trusted as the caller's identity.

Assumes FastAPI 0.143; since 0.136.3 the underscore spelling of a header is not accepted while convert_underscores is True, the default.