How to Handle Errors in FastAPI: Simple Guide with Examples
In
FastAPI, handle errors by raising HTTPException with appropriate status codes and messages. For custom error handling, use @app.exception_handler() to catch exceptions and return friendly responses.Why This Happens
Errors happen when your API receives bad input or something unexpected occurs. If you don't handle these errors, FastAPI returns a default error response that might be unclear or not user-friendly.
python
from fastapi import FastAPI app = FastAPI() @app.get("/items/{item_id}") def read_item(item_id: int): if item_id == 0: return {"item_id": item_id} # No error handling here return {"item_id": item_id, "name": "Item Name"} @app.get("/cause_error") def cause_error(): # This will cause a ZeroDivisionError result = 1 / 0 return {"result": result}
Output
Internal Server Error (500) with default FastAPI error response for ZeroDivisionError
The Fix
Use HTTPException to return clear error messages with status codes. For unexpected errors, create custom exception handlers with @app.exception_handler() to control the response.
python
from fastapi import FastAPI, HTTPException, Request from fastapi.responses import JSONResponse app = FastAPI() @app.get("/items/{item_id}") def read_item(item_id: int): if item_id == 0: raise HTTPException(status_code=400, detail="Invalid item ID: 0 is not allowed") return {"item_id": item_id, "name": "Item Name"} class ZeroDivisionErrorHandled(Exception): pass @app.get("/cause_error") def cause_error(): try: result = 1 / 0 except ZeroDivisionError: raise ZeroDivisionErrorHandled() return {"result": result} @app.exception_handler(ZeroDivisionErrorHandled) async def zero_division_exception_handler(request: Request, exc: ZeroDivisionErrorHandled): return JSONResponse( status_code=400, content={"message": "Cannot divide by zero, please check your input."} )
Output
GET /items/0 returns 400 with JSON {"detail": "Invalid item ID: 0 is not allowed"}
GET /cause_error returns 400 with JSON {"message": "Cannot divide by zero, please check your input."}
Prevention
Always validate inputs and raise HTTPException for client errors. Use custom exception handlers for unexpected errors to keep API responses consistent and user-friendly. Employ Pydantic models for automatic validation and use try-except blocks wisely.
Related Errors
Common related errors include:
- ValidationError: Happens when input data doesn't match expected types or formats. Use Pydantic models to catch these early.
- RequestValidationError: Raised by FastAPI automatically for bad request data.
- Starlette HTTPException: Base for HTTP errors; use it to customize error responses.
Key Takeaways
Use HTTPException to return clear error messages with proper HTTP status codes.
Create custom exception handlers with @app.exception_handler() for unexpected errors.
Validate inputs early using Pydantic models to prevent many errors.
Keep API error responses consistent and user-friendly for better client experience.
Catch and handle exceptions explicitly to avoid server crashes and unclear errors.