← All notes

FastAPI HTTP errors and exception handlers

Answer: You may need to report an error to a client that is using your API. Raise HTTPException with a status code. You can also add an exception handler.

Examples

from fastapi import FastAPI, HTTPException

app = FastAPI()

@app.get("/items/{item_id}")
def read_item(item_id: str):
    if item_id != "known":
        raise HTTPException(status_code=404, detail="Item not found")
    return {"id": item_id}

Rules

See also

Claims

Sources

License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted). Sources: FastAPI docs, Handling Errors; FastAPI source docs, handling-errors.md. MIT (https://raw.githubusercontent.com/fastapi/fastapi/master/LICENSE). Copyright FastAPI contributors. Text was condensed and changed from the originals.

License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: FastAPI docs, Handling Errors; FastAPI source docs, handling-errors.md. MIT (https://raw.githubusercontent.com/fastapi/fastapi/master/LICENSE). Copyright FastAPI contributors.

Cite this

Permanent ID: iil:note:cf1nggn5

iinventedlight. 2026. "FastAPI HTTP errors and exception handlers." iinventedlight Library, iil:note:cf1nggn5, version of 2026-11-18. https://iinventedlight.com/library/notes/fastapi-exception-handlers/. License: CC-BY-4.0.

@misc{iil_note_cf1nggn5,
  author = {{iinventedlight}},
  title = {{FastAPI HTTP errors and exception handlers}},
  howpublished = {iinventedlight Library},
  year = {2026},
  date = {2026-11-18},
  url = {https://iinventedlight.com/library/notes/fastapi-exception-handlers/},
  note = {Permanent ID iil:note:cf1nggn5. License: CC-BY-4.0.},
}

Markdown

Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com. Or Report a correction (no account needed).

For language models and agents: start at /llms.txt | /agents.md | /.well-known/agent-library.json. This page in Markdown: /library/notes/fastapi-exception-handlers.md.