DEV Community

Fiyinfoluwa Ojo
Fiyinfoluwa Ojo

Posted on

Global Error Handling: Consistent API Error Responses with FastAPI

Why Error Handling Matters

Without proper error handling, your API either crashes
or returns confusing responses. Frontend developers
need consistent, predictable error shapes to build against.

The Standard Error Shape

Every error in this API follows this exact structure:

{
  "error": {
    "message": "Reason for the error",
    "status": 400
  }
}
Enter fullscreen mode Exit fullscreen mode

Consistent. Predictable. Professional.

3 Global Error Handlers

1. 404 Not Found

@app.exception_handler(404)
async def not_found_handler(request: Request, exc: HTTPException):
    return JSONResponse(
        status_code=404,
        content={
            "error": {
                "message": "Resource not found",
                "status": 404,
                "path": str(request.url)
            }
        }
    )
Enter fullscreen mode Exit fullscreen mode

2. 400 Validation Error

@app.exception_handler(RequestValidationError)
async def validation_error_handler(request: Request, exc: RequestValidationError):
    return JSONResponse(
        status_code=400,
        content={
            "error": {
                "message": "Invalid input data",
                "status": 400,
                "details": str(exc.errors())
            }
        }
    )
Enter fullscreen mode Exit fullscreen mode

3. 500 Internal Server Error

@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    return JSONResponse(
        status_code=500,
        content={
            "error": {
                "message": "Internal server error",
                "status": 500
            }
        }
    )
Enter fullscreen mode Exit fullscreen mode

Postman Tests

404 - Item not found

404 item

400 - Invalid input

400 invalid

404 - Invalid route with path

404 - invalid route

Lessons Learned

Global error handlers are not optional in production.
Every unhandled exception is a potential server crash
or a confusing response to the client. Define your
error shape once, apply it everywhere.

Day 12 done. 18 more to go.

GDGoCBowen30dayChallenge

Top comments (0)