tiangolo/fastapi · error · HTTPException
Item not found
Error message
Item not found
What it means
HTTPException(404) variant that adds custom response headers. Same trigger as the basic not-found case, but the response includes an X-Error header. Demonstrates that HTTPException accepts a `headers` dict that FastAPI merges into the error response.
Solutions
- Request GET /items-header/foo to succeed.
- If you rely on the X-Error header client-side, parse response headers, not just the body.
- Use the headers pattern to attach request/correlation ids for tracing.
Example fix
// before
raise HTTPException(status_code=404, detail="Item not found", headers={"X-Error": "There goes my error"})
// after (correlation id)
raise HTTPException(status_code=404, detail="Item not found", headers={"X-Request-Id": request_id}) Defensive patterns
Strategy: validation
Validate before calling
items = {'foo': 'The Foo Wrestlers'}
assert item_id in items Type guard
def item_exists(item_id: str, items: dict) -> bool:
return item_id in items Try / catch
resp = requests.get(f'http://localhost:8000/items-header/{item_id}')
if resp.status_code == 404:
print('404, X-Error header:', resp.headers.get('X-Error')) Prevention
- Parse response headers when you expect X-Error metadata.
- Use headers for correlation ids rather than body pollution.
- Validate ids client-side before sending.
When it happens
Trigger: GET /items-header/{item_id} where item_id != 'foo'. Response carries header X-Error: 'There goes my error'.
Common situations: Returning machine-readable error metadata in headers (correlation ids, error codes) without polluting the body. Developers hit the 404 the same way as the plain variant.
Related errors
AI-assisted analysis of tiangolo/fastapi@3e8d1526d8 (2026-08-11).
Data as JSON: /api/errors/eaed84acd326fa03.
Report an issue: GitHub.
Appendix: source
Thrown at docs_src/handling_errors/tutorial002_py310.py:11
from fastapi import FastAPI, HTTPException
app = FastAPI()
items = {"foo": "The Foo Wrestlers"}
@app.get("/items-header/{item_id}")
async def read_item_header(item_id: str):
if item_id not in items:
raise HTTPException(
status_code=404,
detail="Item not found",
headers={"X-Error": "There goes my error"},
)
return {"item": items[item_id]}
View on GitHub (pinned to 3e8d1526d8)