HTTPException & Custom Handlers in Python

From the FastAPI cheat sheet · Error Handling · verified Jul 2026

HTTPException & Custom Handlers

Return proper error responses and handle exceptions globally.

python
from fastapi import HTTPException

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    if item_id not in items:
        raise HTTPException(status_code=404, detail="Item not found")
    return items[item_id]
💡 HTTPException is the standard way to return error responses in FastAPI
⚡ Use @app.exception_handler() to catch custom exceptions globally
📌 Override RequestValidationError handler to customize 422 validation responses
🟢 You can add custom headers to HTTPException for debugging or auth flows
errorsexceptionshttp
Back to the full FastAPI cheat sheet