tiangolo/fastapi · error · HTTPException

Item not found

Error message

Item not found

What it means

The canonical FastAPI HTTP 404 "Item not found", raised when `item_id` is not a key in the in-memory `items` dict ({"foo": ...}). It is the simplest usage of HTTPException to signal a missing resource and is rendered by FastAPI's default exception handler as JSON {"detail": "Item not found"}.

Source

Thrown at docs_src/handling_errors/tutorial001_py310.py:11

from fastapi import FastAPI, HTTPException

app = FastAPI()

items = {"foo": "The Foo Wrestlers"}


@app.get("/items/{item_id}")
async def read_item(item_id: str):
    if item_id not in items:
        raise HTTPException(status_code=404, detail="Item not found")
    return {"item": items[item_id]}

View on GitHub (pinned to 42a41db11f)

Solutions

  1. Request GET /items/foo for a successful response.
  2. If backing with a DB, keep the same 404 on lookup miss.
  3. Use a custom exception handler if you need a different body shape.
  4. Add a test for the 404 path.

Example fix

# before
if item_id not in items:
    raise HTTPException(status_code=404, detail="Item not found")

# after (resource from DB)
item = await db.get(Item, item_id)
if item is None:
    raise HTTPException(status_code=404, detail="Item not found")
Defensive patterns

Strategy: validation

Validate before calling

if item_id not in {"foo"}:
    raise KeyError("Item not found")

Type guard

def is_known(item_id: str) -> bool:
    return item_id in {"foo"}

Try / catch

r = client.get(f"/items/{item_id}")
if r.status_code == 404:
    # offer the valid set to the user
    ...

Prevention

When it happens

Trigger: GET /items/<anything-except-foo> (e.g. /items/bar).

Common situations: Client typos; deleted resources; cached client references; replacing the dict with a DB without preserving the not-found semantics.

Related errors


AI-assisted analysis of tiangolo/fastapi@42a41db11f (2026-08-04). Data as JSON: /data/errors/b5545b55cd7cb826.json. Report an issue: GitHub.