Ojasa Mirai

Ojasa Mirai

FastAPI

Loading...

Learning Level

🟢 Beginner🔵 Advanced
🚀 Error Basics📚 HTTP Exceptions📚 Custom Exceptions📚 Error Responses📚 Exception Handlers📚 Validation Errors📚 Error Logging📚 Error Best Practices
Fastapi/Error Handling/Error Responses

Error Responses

Learn the fundamentals of error responses in FastAPI.

🎯 Core Concept

Error responses communicate what went wrong to API clients in a structured, consistent format. Well-designed error responses include status codes, error messages, and contextual information that help clients debug and handle errors appropriately.

📖 What You'll Learn

In this section, you'll understand:

  • Structuring error responses consistently
  • How it applies to real-world API development
  • Using status codes effectively
  • Common patterns and best practices

💡 Basic Error Response Structure

from fastapi import FastAPI, HTTPException
from fastapi.responses import JSONResponse

app = FastAPI()

@app.get("/items/{item_id}")
async def get_item(item_id: int):
    if item_id < 1:
        raise HTTPException(
            status_code=400,
            detail="Item ID must be positive"
        )
    return {"item_id": item_id, "name": "Widget"}

Error response:

{
  "detail": "Item ID must be positive"
}

🔍 Consistent Error Format

Create a standardized error response model:

from pydantic import BaseModel
from datetime import datetime
from typing import Optional

class ErrorResponse(BaseModel):
    error: str
    detail: str
    status_code: int
    timestamp: datetime
    path: Optional[str] = None

@app.exception_handler(Exception)
async def global_error_handler(request, exc):
    return JSONResponse(
        status_code=500,
        content={
            "error": "InternalServerError",
            "detail": "An unexpected error occurred",
            "status_code": 500,
            "timestamp": datetime.utcnow().isoformat(),
            "path": str(request.url.path)
        }
    )

💼 Production-Grade Error Responses

class ValidationErrorResponse(BaseModel):
    error: str
    detail: str
    errors: list[dict]

@app.post("/users/")
async def create_user(user: UserCreate):
    validation_errors = []

    if not user.email:
        validation_errors.append({
            "field": "email",
            "message": "Email is required"
        })

    if len(user.password) < 8:
        validation_errors.append({
            "field": "password",
            "message": "Password must be at least 8 characters"
        })

    if validation_errors:
        raise HTTPException(
            status_code=422,
            detail={
                "error": "ValidationFailed",
                "validation_errors": validation_errors
            }
        )

    return {"id": 1, "email": user.email}

How it applies to real-world API development

Proper error responses are essential for:

  • **Mobile apps**: Users need clear messages about what failed
  • **Frontend apps**: JavaScript can parse and handle errors programmatically
  • **Third-party integrations**: API consumers need error details to implement retries
  • **Debugging**: Developers need enough information to fix issues

Example - E-commerce error handling:

class OrderError(BaseModel):
    error_code: str
    message: str
    order_id: Optional[int] = None
    suggestion: Optional[str] = None

@app.post("/orders/", response_model=OrderResponse)
async def create_order(order: OrderCreate):
    # Check inventory
    if not check_inventory(order.item_id, order.quantity):
        raise HTTPException(
            status_code=400,
            detail={
                "error_code": "OUT_OF_STOCK",
                "message": "Item is out of stock",
                "item_id": order.item_id,
                "suggestion": "Check back in 2 days"
            }
        )

    # Check payment
    if not process_payment(order.payment):
        raise HTTPException(
            status_code=402,
            detail={
                "error_code": "PAYMENT_FAILED",
                "message": "Payment could not be processed",
                "suggestion": "Verify your payment method and try again"
            }
        )

    return create_order_in_db(order)

Common patterns and best practices

  • ✅ Use consistent error response structure
  • ✅ Include error codes for programmatic handling
  • ✅ Provide actionable error messages
  • ✅ Include request IDs for support/debugging
  • ✅ Use appropriate HTTP status codes
  • ✅ Don't expose sensitive implementation details
  • ✅ Log errors for monitoring
  • ✅ Test error scenarios thoroughly

🔑 Key Takeaways

  • ✅ Understand the purpose of error responses
  • ✅ Know when to apply this pattern
  • ✅ Recognize its benefits in real-world scenarios
  • ✅ Be prepared to use it in your projects

Ready to explore more? Check out the advanced section for production patterns and edge cases.


Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep • Build Real • Verify Skills • Launch Forward

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn