Custom error response models help you send clear and consistent error messages from your API. This makes it easier for users and developers to understand what went wrong.
0
0
Custom error response models in FastAPI
Introduction
When you want to return specific error details in a structured way.
When you want to document your API errors clearly for users.
When you want to handle different error types with different messages.
When you want to keep your API responses consistent, even on errors.
Syntax
FastAPI
from fastapi import FastAPI, HTTPException, Request from fastapi.responses import JSONResponse from pydantic import BaseModel class ErrorResponse(BaseModel): detail: str app = FastAPI() @app.exception_handler(HTTPException) async def custom_http_exception_handler(request: Request, exc: HTTPException): return JSONResponse( status_code=exc.status_code, content=ErrorResponse(detail=exc.detail).dict() )
Define a Pydantic model to describe the error response structure.
Use FastAPI's exception handler decorator to customize error responses.
Examples
This model defines the error message format with a single 'detail' field.
FastAPI
class ErrorResponse(BaseModel): detail: str
This function catches HTTP exceptions and returns the error using the custom model.
FastAPI
@app.exception_handler(HTTPException) async def custom_http_exception_handler(request: Request, exc: HTTPException): return JSONResponse( status_code=exc.status_code, content=ErrorResponse(detail=exc.detail).dict() )
Example endpoint that raises an error if the item ID is invalid.
FastAPI
@app.get('/items/{item_id}') async def read_item(item_id: int): if item_id < 1: raise HTTPException(status_code=400, detail='Item ID must be positive') return {'item_id': item_id}
Sample Program
This FastAPI app defines a custom error response model. When you request an item with an invalid ID (less than 1), it returns a clear error message using the custom model.
FastAPI
from fastapi import FastAPI, HTTPException, Request from fastapi.responses import JSONResponse from pydantic import BaseModel class ErrorResponse(BaseModel): detail: str app = FastAPI() @app.exception_handler(HTTPException) async def custom_http_exception_handler(request: Request, exc: HTTPException): return JSONResponse( status_code=exc.status_code, content=ErrorResponse(detail=exc.detail).dict() ) @app.get('/items/{item_id}') async def read_item(item_id: int): if item_id < 1: raise HTTPException(status_code=400, detail='Item ID must be positive') return {'item_id': item_id}
OutputSuccess
Important Notes
Custom error models improve API clarity and help clients handle errors better.
Always keep error messages simple and informative.
Summary
Custom error response models let you control how errors look in your API.
Use Pydantic models to define error message structure.
Handle exceptions with FastAPI's exception handlers to return these models.