tiangolo/fastapi · error · HTTPException

Item not found

Error message

Item not found

What it means

The canonical FastAPI HTTPException(404) example from the handling-errors tutorial. The endpoint GET /items/{item_id} raises 'Item not found' when item_id is not a key in the in-memory `items` dict (which only contains 'foo'). FastAPI serializes it as a JSON body {detail: 'Item not found'} with status 404.

Solutions

  1. Request GET /items/foo to succeed.
  2. Replace the in-memory dict with a real data source if ids should be dynamic.
  3. Add a custom exception handler or response_model if you need a different error shape.

Example fix

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

Strategy: validation

Validate before calling

items = {'foo': 'The Foo Wrestlers'}
assert item_id in items, f'{item_id} not found'

Type guard

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

Try / catch

resp = requests.get(f'http://localhost:8000/items/{item_id}')
if resp.status_code == 404:
    print('Item not found')

Prevention

When it happens

Trigger: GET /items/{item_id} where item_id != 'foo'. Any other path segment returns 404.

Common situations: First-contact example for FastAPI error handling. Developers see this when testing unknown ids or after the in-memory store is reset.

Related errors


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

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