tiangolo/fastapi · error · HTTPException
X-Key header invalid
Error message
X-Key header invalid
What it means
Identical to error 27 but in tutorial012_py310.py (non-Annotated form). Global dependency verify_key enforces X-Key == 'fake-super-secret-key', raising HTTPException(400) on mismatch. Applies to every route.
Solutions
- Send X-Key: fake-super-secret-key alongside a valid X-Token.
- Confirm both headers are configured identically across server and client.
- Source both secrets from the same configuration store.
Example fix
// before
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")
// after
EXPECTED_KEY = os.environ["EXPECTED_X_KEY"]
async def verify_key(x_key: str = Header()):
if x_key != EXPECTED_KEY:
raise HTTPException(status_code=400, detail="X-Key header invalid") Defensive patterns
Strategy: validation
Validate before calling
headers = {'X-Key': os.environ['X_KEY']}
assert headers['X-Key'] == 'fake-super-secret-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(url, headers=headers)
if resp.status_code == 400:
print('X-Key invalid:', resp.json()['detail']) Prevention
- Send X-Key alongside X-Token every time.
- Keep both secrets in one config object.
- Add tests asserting both headers are present.
When it happens
Trigger: Any request with a valid X-Token but a missing or wrong X-Key header. Missing header -> 422; present-but-wrong -> 400.
Common situations: Forgetting the second of two required headers, or sending a stale key after rotation.
Related errors
AI-assisted analysis of tiangolo/fastapi@3e8d1526d8 (2026-08-11).
Data as JSON: /api/errors/80510d035c7125bb.
Report an issue: GitHub.
Appendix: source
Thrown at docs_src/dependencies/tutorial012_py310.py:11
from fastapi import Depends, FastAPI, Header, HTTPException
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 = 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)