tiangolo/fastapi · error · HTTPException

Item not found

Error message

Item not found

What it means

Raised by GET /items/{item_id} in the tutorial008b example when item_id is not a key in the data dict (only "plumbus" and "portal-gun" exist), returning HTTP 404. This check precedes the owner check, so unknown ids never reach the OwnerError path.

Source

Thrown at docs_src/dependencies/tutorial008b_an_py310.py:28

    "portal-gun": {"description": "Gun to create portals", "owner": "Rick"},
}


class OwnerError(Exception):
    pass


def get_username():
    try:
        yield "Rick"
    except OwnerError as e:
        raise HTTPException(status_code=400, detail=f"Owner error: {e}")


@app.get("/items/{item_id}")
def get_item(item_id: str, username: Annotated[str, Depends(get_username)]):
    if item_id not in data:
        raise HTTPException(status_code=404, detail="Item not found")
    item = data[item_id]
    if item["owner"] != username:
        raise OwnerError(username)
    return item

View on GitHub (pinned to 42a41db11f)

Solutions

  1. Use a known id ("plumbus" or "portal-gun").
  2. Handle the 404 in the client.
  3. Confirm the id against the data source.

Example fix

# before
client.get("/items/unknown")
# after
client.get("/items/portal-gun")
Defensive patterns

Strategy: validation

Validate before calling

valid_ids = {"plumbus", "portal-gun"}
if item_id in valid_ids:
    client.get(f"/items/{item_id}")

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}")
if resp.status_code == 404:
    ...

Prevention

When it happens

Trigger: GET /items/{item_id} with an id not in {"plumbus","portal-gun"}, e.g. /items/unknown.

Common situations: Requesting an unseeded/deleted item; id typo; wrong environment data.

Related errors


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