
FastAPI
Learn the fundamentals of error responses in FastAPI.
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.
In this section, you'll understand:
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"
}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)
}
)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}Proper error responses are essential for:
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)Ready to explore more? Check out the advanced section for production patterns and edge cases.
Resources
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