tiangolo/fastapi · error · HTTPException

Invalid X-Token header

Error message

Invalid X-Token header

What it means

Identical guard to error 0 but in the non-Annotated (default-value) variant of the app-testing example: GET /items/{item_id} raises HTTP 400 when the X-Token header != "coneofsilence". Only the parameter declaration style (x_token: str = Header() vs Annotated[str, Header()]) differs; behavior is identical.

Source

Thrown at docs_src/app_testing/app_b_py310/main.py:23

fake_db = {
    "foo": {"id": "foo", "title": "Foo", "description": "There goes my hero"},
    "bar": {"id": "bar", "title": "Bar", "description": "The bartenders"},
}

app = FastAPI()


class Item(BaseModel):
    id: str
    title: str
    description: str | None = None


@app.get("/items/{item_id}", response_model=Item)
async def read_main(item_id: str, x_token: str = Header()):
    if x_token != fake_secret_token:
        raise HTTPException(status_code=400, detail="Invalid X-Token header")
    if item_id not in fake_db:
        raise HTTPException(status_code=404, detail="Item not found")
    return fake_db[item_id]


@app.post("/items/")
async def create_item(item: Item, x_token: str = Header()) -> Item:
    if x_token != fake_secret_token:
        raise HTTPException(status_code=400, detail="Invalid X-Token header")
    if item.id in fake_db:
        raise HTTPException(status_code=409, detail="Item already exists")
    fake_db[item.id] = item.model_dump()
    return item

View on GitHub (pinned to 42a41db11f)

Solutions

  1. Send X-Token: coneofsilence on the GET request.
  2. Prefer the Annotated style for new code; ensure the header value matches.
  3. Centralize the token in config.

Example fix

# before
client.get("/items/foo")
# after
client.get("/items/foo", headers={"X-Token": "coneofsilence"})
Defensive patterns

Strategy: validation

Validate before calling

EXPECTED_TOKEN = "coneofsilence"
headers = {"X-Token": EXPECTED_TOKEN}
client.get("/items/foo", headers=headers)

Type guard

def has_valid_token(token: str | None) -> bool:
    return token == "coneofsilence"

Prevention

When it happens

Trigger: GET /items/{item_id} without a correct X-Token header against the app_b_py310 variant of the app.

Common situations: Same as error 0: missing/mismatched header in test clients or frontends.

Related errors


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