tiangolo/fastapi · error · HTTPException

X-Token header invalid

Error message

X-Token header invalid

What it means

Raised by the verify_token dependency (Annotated variant) when X-Token != "fake-super-secret-token", returning HTTP 400. The dependency is registered via dependencies=[Depends(verify_token), Depends(verify_key)] on GET /items/, so it is an access-control gate that runs before the route body executes.

Source

Thrown at docs_src/dependencies/tutorial006_an_py310.py:10

from typing import Annotated

from fastapi import Depends, FastAPI, Header, HTTPException

app = FastAPI()


async def verify_token(x_token: Annotated[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: Annotated[str, Header()]):
    if x_key != "fake-super-secret-key":
        raise HTTPException(status_code=400, detail="X-Key header invalid")
    return x_key


@app.get("/items/", dependencies=[Depends(verify_token), Depends(verify_key)])
async def read_items():
    return [{"item": "Foo"}, {"item": "Bar"}]

View on GitHub (pinned to 42a41db11f)

Solutions

  1. Send X-Token: fake-super-secret-token (and also X-Key, see error 15).
  2. Keep the secret in shared config.
  3. Confirm both header dependencies are satisfied.

Example fix

# before
client.get("/items/")
# after
client.get("/items/", headers={"X-Token":"fake-super-secret-token","X-Key":"fake-super-secret-key"})
Defensive patterns

Strategy: validation

Validate before calling

TOKEN = "fake-super-secret-token"
KEY = "fake-super-secret-key"
headers = {"X-Token": TOKEN, "X-Key": KEY}
client.get("/items/", headers=headers)

Type guard

def has_both_headers(h: dict) -> bool:
    return h.get("X-Token") == "fake-super-secret-token" and h.get("X-Key") == "fake-super-secret-key"

Prevention

When it happens

Trigger: GET /items/ without X-Token header equal to "fake-super-secret-token".

Common situations: Missing token header in the client; secret mismatch after rotation; forgetting the dependency also requires X-Key.

Related errors


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