tiangolo/fastapi · error · HTTPException

X-Token header invalid

Error message

X-Token header invalid

What it means

Raised (400) by the verify_token dependency attached to GET /items/ via dependencies=[Depends(verify_token), Depends(verify_key)]. The X-Token header must equal 'fake-super-secret-token'. This is the Annotated-style dependencies tutorial; the dependency does not return a value (it is a pure guard).

Solutions

  1. Send X-Token: fake-super-secret-token on GET /items/.
  2. Remember both X-Token and X-Key are required on this route.
  3. Centralize the expected secrets in configuration.

Example fix

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

Strategy: validation

Validate before calling

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

Type guard

def is_valid_token_and_key(token: object, key: object) -> bool:
    return token == 'fake-super-secret-token' and key == 'fake-super-secret-key'

Prevention

When it happens

Trigger: GET /items/ without X-Token: fake-super-secret-token. verify_token runs before verify_key, so a bad token short-circuits before the key check.

Common situations: Token drift between client and the hardcoded literal; header stripped by proxy; sending the X-Key correctly but forgetting X-Token.

Related errors


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

Appendix: 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 3e8d1526d8)