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
- id: C1 claim: APIs often need to report an error to a client. source: S1 evidence: "report an error to a client"
- id: C2 claim: HTTPException is the documented error type. source: S1 evidence: "HTTPException"
- id: C3 claim: The source docs describe reporting an error to a client. source: S2 evidence: "report an error to a client"
Sources
- [S1] Handling Errors. FastAPI docs. https://fastapi.tiangolo.com/tutorial/handling-errors/ . License: MIT. Accessed 2026-11-18.
- [S2] handling-errors.md. FastAPI source docs. https://raw.githubusercontent.com/fastapi/fastapi/master/docs/en/docs/tutorial/handling-errors.md . License: MIT. Accessed 2026-11-18.
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
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.},
}
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.