tiangolo/fastapi · error · HTTPException
Item not found
Error message
Item not found
What it means
Non-Annotated variant of error 2: GET /items/{item_id} raises HTTP 404 "Item not found" when item_id is absent from fake_db. Identical runtime behavior to error 2.
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 42a41db11f)
Solutions
- Request an existing id or create it first.
- Handle the 404 gracefully in the client.
- Verify id format and casing.
Example fix
# before
client.get("/items/ghost", headers=auth)
# after
client.get("/items/foo", headers=auth) Defensive patterns
Strategy: validation
Validate before calling
valid_ids = {"foo", "bar"}
if item_id in valid_ids:
client.get(f"/items/{item_id}", headers=auth) Type guard
def item_exists(item_id: str, known: set[str]) -> bool:
return item_id in known Try / catch
resp = client.get(f"/items/{item_id}", headers=auth)
if resp.status_code == 404:
... Prevention
- Verify the id is known before requesting.
- Strip/normalize the id string.
- Handle 404 without retrying blindly.
When it happens
Trigger: GET /items/{item_id} with valid token but an id not in {"foo","bar"}.
Common situations: Looking up a non-existent or deleted item; id typo.
Related errors
AI-assisted analysis of tiangolo/fastapi@42a41db11f (2026-08-04).
Data as JSON: /data/errors/2615281d899bd889.json.
Report an issue: GitHub.