tiangolo/fastapi · error · HTTPException

Item not found

Error message

Item not found

What it means

Standard HTTPException with status_code 404 raised in the path operation when item_id is not a key in the in-memory `data` dict. It is FastAPI's canonical way to signal a missing resource. The library converts it into a JSON response of shape {detail: 'Item not found'} with a 404 status.

Solutions

  1. Verify the item_id against the known keys ('plumbus', 'portal-gun') before requesting.
  2. Check the data source the app reads from — if it was reset or seeded differently, missing keys now return 404.
  3. Return a more descriptive detail or use a typed response model so clients can distinguish 'not found' from 'forbidden'.

Example fix

// before
if item_id not in data:
    raise HTTPException(status_code=404, detail="Item not found")
// after (richer detail)
if item_id not in data:
    raise HTTPException(status_code=404, detail=f"Item '{item_id}' not found; available: {list(data)}")
Defensive patterns

Strategy: validation

Validate before calling

known_ids = {'plumbus', 'portal-gun'}
item_id = 'foo'
assert item_id in known_ids, f'{item_id} not in {known_ids}'

Type guard

def item_exists(item_id: str, data: dict) -> bool:
    return item_id in data

Try / catch

import requests
resp = requests.get(f'http://localhost:8000/items/{item_id}')
if resp.status_code == 404:
    print('not found, pick from', data.keys())
else:
    resp.raise_for_status()

Prevention

When it happens

Trigger: GET /items/{item_id} where item_id is neither 'plumbus' nor 'portal-gun' (the only keys in `data`). Any other path segment, e.g. GET /items/foo, triggers it.

Common situations: Lookup-by-ID endpoints backed by a dict/database where the client passes an unknown or deleted identifier. Common after data resets, with stale client-cached IDs, or when the URL casing/encoding does not match the stored key.

Related errors


AI-assisted analysis of tiangolo/fastapi@3e8d1526d8 (2026-08-11). Data as JSON: /api/errors/cf00267b1766221c. Report an issue: GitHub.

Appendix: source

Thrown at docs_src/dependencies/tutorial008b_py310.py:26

    "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: 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 3e8d1526d8)