tiangolo/fastapi · error · HTTPException
X-Key header invalid
Error message
X-Key header invalid
What it means
HTTPException (400) from the global dependency verify_key, the second app-level dependency. It validates the X-Key header against 'fake-super-secret-key' and returns the key on success. Every route on the app requires both X-Token and X-Key; X-Key failing produces this 400.
Solutions
- Send header X-Key: fake-super-secret-key on every request (in addition to a valid X-Token).
- Confirm both headers are present and correctly named; FastAPI parameter x_key maps to header 'X-Key'.
- Centralize secret retrieval so X-Token and X-Key are configured together and cannot drift.
Example fix
// before curl -H 'X-Token: fake-super-secret-token' http://localhost:8000/items/ // after curl -H 'X-Token: fake-super-secret-token' -H 'X-Key: fake-super-secret-key' http://localhost:8000/items/
Defensive patterns
Strategy: validation
Validate before calling
headers = {'X-Token': 'fake-super-secret-token', 'X-Key': os.environ.get('X_KEY', 'fake-super-secret-key')}
assert headers['X-Key'] Type guard
def has_valid_x_key(headers: dict) -> bool:
return headers.get('X-Key') == 'fake-super-secret-key' Try / catch
resp = requests.get('http://localhost:8000/items/', headers=headers)
if resp.status_code == 400 and 'X-Key' in resp.text:
print('bad/missing X-Key') Prevention
- Always send both required headers together.
- Rotate both secrets in lockstep.
- Add a client interceptor to inject auth headers on every call.
When it happens
Trigger: Any request to a route on this app where X-Token is valid but X-Key is missing or != 'fake-super-secret-key'. Note: because both dependencies are declared, a missing X-Key yields a 422 first; a present-but-wrong X-Key yields this 400.
Common situations: Multi-header API-gateway checks. Developers pass X-Token correctly but forget X-Key, or send a stale key after rotation.
Related errors
AI-assisted analysis of tiangolo/fastapi@3e8d1526d8 (2026-08-11).
Data as JSON: /api/errors/081f977b85d7c8fa.
Report an issue: GitHub.
Appendix: source
Thrown at docs_src/dependencies/tutorial012_an_py310.py:13
from typing import Annotated
from fastapi import Depends, FastAPI, Header, HTTPException
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 = 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 3e8d1526d8)