skip to content

In FastAPI, how do APIKeyHeader, APIKeyQuery and APIKeyCookie differ, and what does each one hand your endpoint?

level: juniorimportance: should knowfreq 40%

answer

  1. three places a key can travel
  2. name= picks the header, parameter or cookie
  3. returns the raw string, unchecked
  4. missing or empty: 401 with a challenge
  5. query strings land in access logs

basics

~20 s

All three read one named value from the request (a header, a query parameter or a cookie) and return it as a string. A missing or empty value gets 401, but none of them checks that the key is valid.

solid answer

~40 s

`APIKeyHeader(name="X-API-Key")`, `APIKeyQuery(name="api_key")` and `APIKeyCookie(name="api_key")` are callable dependencies: used with `Depends`, each reads `request.headers`, `request.query_params` or `request.cookies` by that name and returns the raw string. If the value is missing or empty and `auto_error` keeps its default `True`, they raise 401 (since FastAPI 0.122; earlier releases sent 403) with `detail` `"Not authenticated"` and `WWW-Authenticate: APIKey`; with `auto_error=False` they return `None`. They also register an `apiKey` security scheme, so `/docs` gets an Authorize button. They never compare the key with anything; that is your own dependency's job. For a partner integration prefer the header: a key in the query string is written into access logs, proxy logs and browser history, and a cookie is sent automatically by browsers, which brings CSRF into play.

code

python · 31 lines
python
from typing import Annotated

from fastapi import Depends, FastAPI
from fastapi.security import APIKeyCookie, APIKeyHeader, APIKeyQuery
from fastapi.testclient import TestClient

app = FastAPI()

header_key = APIKeyHeader(name="X-API-Key")
query_key = APIKeyQuery(name="api_key")
cookie_key = APIKeyCookie(name="api_key")


@app.get("/from-header")
def from_header(key: Annotated[str, Depends(header_key)]) -> dict[str, str]:
    return {"key": key}


@app.get("/from-query")
def from_query(key: Annotated[str, Depends(query_key)]) -> dict[str, str]:
    return {"key": key}


client = TestClient(app)
missing = client.get("/from-header")
print(missing.status_code, missing.json(), missing.headers["www-authenticate"])
# 401 {'detail': 'Not authenticated'} APIKey
print(client.get("/from-header", headers={"x-api-key": "anything"}).json())
# {'key': 'anything'}  -- any non-empty value is returned unchecked
print(client.get("/from-query", params={"api_key": "abc123"}).json())
# {'key': 'abc123'}

go deeper

for a junior

Recall the three classes, what name= means for each, and that the dependency hands you the raw key string or a 401 when it is missing.

for a middle

Explain that the classes extract and document but never validate, what auto_error changes, and why a header beats a query parameter for partner keys.

for a senior

Show where keys leak in production: URLs in access and proxy logs, browser history, your own logging middleware, and cookies sent cross-site.

for a principal

Set the team convention: one header name, one verifying dependency every router reuses, and a rule that a key seen in a URL is treated as exposed.

## What the three classes are FastAPI ships three **API key security classes** in `fastapi.security`: `APIKeyHeader`, `APIKeyQuery` and `APIKeyCookie`. Each is a class whose **instances are callable dependencies**. You create one instance with the name of the value to read, then use it with `Depends` like any other dependency: ```python from typing import Annotated from fastapi import Depends, FastAPI from fastapi.security import APIKeyHeader app = FastAPI() api_key_header = APIKeyHeader(name="X-API-Key") @app.get("/partner/orders") def list_orders(key: Annotated[str, Depends(api_key_header)]): ... ``` All three share one base class, `APIKeyBase`, and one constructor shape: a required keyword `name`, plus optional `scheme_name`, `description` and `auto_error` (default `True`). ## Where each one reads from | Class | Reads | Example of what the client sends | |---|---|---| | `APIKeyHeader(name="X-API-Key")` | `request.headers` | `X-API-Key: abc123` | | `APIKeyQuery(name="api_key")` | `request.query_params` | `GET /orders?api_key=abc123` | | `APIKeyCookie(name="api_key")` | `request.cookies` | `Cookie: api_key=abc123` | A few details follow from that: - The **dependency result is a plain `str`**: the value as Starlette parsed it from the request, with no further processing such as prefix stripping. - Header lookup goes through Starlette's request headers, which are **case-insensitive**, so `x-api-key` matches `APIKeyHeader(name="X-API-Key")`. - `APIKeyCookie` only **reads** a cookie. Its docstring says plainly that it does not define how to set that cookie; your login or provisioning flow does that. ## What happens when the key is absent The base class treats any **falsy value** as absent: a missing header, a missing query parameter, a missing cookie, or one sent with an empty value. Then: 1. With `auto_error=True` (the default), the class raises an `HTTPException` with status **401 Unauthorized**, `detail` `"Not authenticated"` and the header `WWW-Authenticate: APIKey`. The handler never runs. 2. With `auto_error=False`, the dependency returns `None` instead, which is how optional authentication is built. The `WWW-Authenticate: APIKey` value is a custom challenge: a comment in the source notes that the header is not standardized for API keys, but HTTP requires a 401 to include one, so FastAPI sends `APIKey`. This is the behaviour since FastAPI 0.122 and so in 0.143; earlier releases answered a missing key with 403. ## What they do not do This is the part candidates most often get wrong: - **None of the classes validates the key.** `APIKeyHeader` returns `"abc123"` or `"anything-at-all"` the same way. Comparing it with a configured or stored key is the job of a dependency you write on top of it. - They do not look the key up, rate-limit it, or know which partner it belongs to. - They do not hash, issue or rotate keys; that is key management, covered in the lesson on machine API keys. What they *do* add besides extraction is **documentation**: each instance a route uses registers an `apiKey` security scheme in the generated OpenAPI document, so `/docs` shows an **Authorize** button where a tester can paste the key once and have Swagger UI send it on every call. ## Choosing a location For a partner integration, the header is the usual choice, and the reasons are about **where the value ends up**: - **Query string (`APIKeyQuery`)**: the key is part of the URL. Uvicorn's access log writes the path with its query string, and so do most reverse proxies and monitoring tools; browsers keep it in history and may send it in a `Referer`. Anyone who can read those logs can reuse the key. - **Header (`APIKeyHeader`)**: not part of the URL, so default access logs do not record it. It still must never be logged by your own middleware. - **Cookie (`APIKeyCookie`)**: browsers attach cookies automatically to matching requests, which suits a browser session but brings cross-site request forgery into play; for a server-to-server partner, a cookie adds nothing over a header. `APIKeyQuery` still has legitimate uses, such as a link that cannot carry headers, but treat a key that has travelled in a URL as exposed. ## Documenting and testing them The constructor's other arguments are about the generated documentation rather than behaviour: - `scheme_name` names the scheme in OpenAPI; it defaults to the class name, so two different `APIKeyHeader` instances need distinct names to appear separately. - `description` adds text to the scheme in the generated OpenAPI document, visible at `/docs`, a good place to say where partners obtain a key. In tests, `fastapi.testclient.TestClient` sends each location directly: `headers={"X-API-Key": "..."}`, `params={"api_key": "..."}`, or a cookie set on the client. A useful habit is to test the missing case too and assert both the 401 and the `WWW-Authenticate: APIKey` header, so a future change of FastAPI's behaviour is caught by the suite instead of by a partner.

  • Is the header name given to APIKeyHeader matched case-sensitively?
    No. `APIKeyHeader` reads through Starlette's request headers, which are case-insensitive, so a client sending `x-api-key` matches `APIKeyHeader(name="X-API-Key")`. The spelling you pass still matters for the generated OpenAPI scheme, which shows it in `/docs`.
  • What does a request with an empty X-API-Key header produce?
    The same as a missing one. The shared base class treats any falsy value as absent, so `X-API-Key:` with no value raises 401 `Not authenticated` with `WWW-Authenticate: APIKey` when `auto_error` is true, and yields `None` when it is false.
  • Can APIKeyCookie set the cookie for the client?
    No. It only reads `request.cookies` by name; its docstring says it does not define how to set that cookie. Setting it, with its `HttpOnly`, `Secure` and `SameSite` flags, happens in whichever endpoint issues the credential, usually through a response's `set_cookie`.

  • APIKeyHeader rejects a request whose key does not match a configured value
  • A missing key gets 403 Forbidden from APIKeyHeader in current FastAPI
  • The client must send the header name in exactly the casing given to APIKeyHeader
  • A key in the query string is as private as a header because the connection uses TLS
  • APIKeyCookie sets the cookie on the client once the key is accepted

Assumes FastAPI 0.143; since 0.122 a missing key gets 401 with WWW-Authenticate: APIKey, where earlier releases sent 403.