tiangolo/fastapi · error · HTTPException

X-Key header invalid

Error message

X-Key header invalid

What it means

Non-Annotated variant of error 29: `verify_key` (`x_key: str = Header()`) raises HTTP 400 "X-Key header invalid" when X-Key differs from "fake-super-secret-key". Runs as the second global dependency after verify_token.

Source

Thrown at docs_src/dependencies/tutorial012_py310.py:11

from fastapi import Depends, FastAPI, Header, HTTPException


async def verify_token(x_token: str = Header()):
    if x_token != "fake-super-secret-token":
        raise HTTPException(status_code=400, detail="X-Token header invalid")


async def verify_key(x_key: str = Header()):
    if x_key != "fake-super-secret-key":
        raise HTTPException(status_code=400, detail="X-Key header invalid")
    return x_key


app = FastAPI(dependencies=[Depends(verify_token), Depends(verify_key)])


@app.get("/items/")
async def read_items():
    return [{"item": "Portal Gun"}, {"item": "Plumbus"}]


@app.get("/users/")
async def read_users():
    return [{"username": "Rick"}, {"username": "Morty"}]

View on GitHub (pinned to 42a41db11f)

Solutions

  1. Send `X-Key: fake-super-secret-key` alongside a valid X-Token.
  2. Store both keys in configuration.
  3. Return 401 for key failures.
  4. Centralize header injection in the client SDK.

Example fix

# before
if x_key != "fake-super-secret-key":
    raise HTTPException(status_code=400, detail="X-Key header invalid")

# after
if x_key != settings.expected_key:
    raise HTTPException(status_code=401, detail="Unauthorized")
Defensive patterns

Strategy: validation

Validate before calling

if headers.get("X-Key") != EXPECTED_KEY:
    raise PermissionError("missing/invalid X-Key")

Type guard

def key_ok(headers: dict) -> bool:
    return headers.get("X-Key") == EXPECTED_KEY

Try / catch

r = client.get("/users/", headers=headers)
if r.status_code == 400 and "X-Key header invalid" in r.json().get("detail", ""):
    ...

Prevention

When it happens

Trigger: Any request that passes verify_token but sends a missing/wrong X-Key header.

Common situations: Second key forgotten; key-pair mismatch; header stripping by proxies.

Related errors


AI-assisted analysis of tiangolo/fastapi@42a41db11f (2026-08-04). Data as JSON: /data/errors/80510d035c7125bb.json. Report an issue: GitHub.