tiangolo/fastapi · error · HTTPException

X-Token header invalid

Error message

X-Token header invalid

What it means

Legacy-style variant of error 14: verify_token on GET /items/ raises 400 when X-Token != 'fake-super-secret-token'. Header injection uses x_token: str = Header() instead of Annotated. Behavior is identical.

Solutions

  1. Send X-Token: fake-super-secret-token.
  2. Send X-Key: fake-super-secret-key as well (both are required).
  3. Migrate to the Annotated variant for consistency with current docs.

Example fix

// before
GET /items/   X-Token: wrong
// after
GET /items/   X-Token: fake-super-secret-token
Defensive patterns

Strategy: validation

Validate before calling

import httpx
resp = httpx.get('http://localhost:8000/items/', headers={'X-Token': 'fake-super-secret-token', 'X-Key': 'fake-super-secret-key'})

Type guard

def is_valid_x_token(value: object) -> bool:
    return isinstance(value, str) and value == 'fake-super-secret-token'

Prevention

When it happens

Trigger: GET /items/ with a wrong/missing X-Token header.

Common situations: Stale client token; header stripped in transit; mismatch with another tutorial's token literal.

Related errors


AI-assisted analysis of tiangolo/fastapi@3e8d1526d8 (2026-08-11). Data as JSON: /api/errors/28c1c9769f86cfce. Report an issue: GitHub.

Appendix: source

Thrown at docs_src/dependencies/tutorial006_py310.py:8

from fastapi import Depends, FastAPI, Header, HTTPException

app = FastAPI()


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.get("/items/", dependencies=[Depends(verify_token), Depends(verify_key)])
async def read_items():
    return [{"item": "Foo"}, {"item": "Bar"}]

View on GitHub (pinned to 3e8d1526d8)