tiangolo/fastapi · error · HTTPException
Item not found
Error message
Item not found
What it means
Same as error 1 in the legacy-style file: GET /items/{item_id} returns 404 when item_id is not a key in fake_db ('foo' or 'bar'). The store is in-memory and resets on restart.
Solutions
- GET /items/foo or /items/bar.
- Create then read within the same process.
- Back fake_db with persistent storage.
Example fix
// before GET /items/missing // after GET /items/foo
Defensive patterns
Strategy: try-catch
Validate before calling
import httpx
KNOWN = {'foo', 'bar'}
item_id = 'foo'
if item_id in KNOWN:
resp = httpx.get(f'http://localhost:8000/items/{item_id}', headers={'X-Token': 'coneofsilence'}) Type guard
def is_known_item(item_id: object) -> bool:
return isinstance(item_id, str) and item_id in {'foo', 'bar'} Try / catch
try:
resp = httpx.get(url, headers=headers)
resp.raise_for_status()
except httpx.HTTPStatusError as e:
if e.response.status_code == 404:
... Prevention
- Do not rely on in-memory data after a restart.
- Whitelist known ids before requesting.
- Back the store with persistence for non-tutorial use.
When it happens
Trigger: GET /items/<anything-but-foo-or-bar> with a valid token, or GETting an item created in a previous server process.
Common situations: Post-restart 404s, typos in item_id, or assuming seeded data includes more than foo/bar.
Related errors
AI-assisted analysis of tiangolo/fastapi@3e8d1526d8 (2026-08-11).
Data as JSON: /api/errors/2615281d899bd889.
Report an issue: GitHub.
Appendix: source
Thrown at docs_src/app_testing/app_b_py310/main.py:25
"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 3e8d1526d8)