In FastAPI, when validating a request, if a parameter is missing or invalid, FastAPI raises a RequestValidationError exception. By default, this exception returns a 422 Unprocessable Entity response. However, you may want to customize this response for specific routes. Here are several approaches to achieve this:
Override the default exception handler for RequestValidationError and provide a custom response for the desired routes.
from fastapi import FastAPI, Request, status, HTTPException from fastapi.responses import JSONResponse from fastapi.encoders import jsonable_encoder from fastapi.exceptions import RequestValidationError app = FastAPI() routes_with_custom_exception = ['/'] @app.exception_handler(RequestValidationError) async def validation_exception_handler(request: Request, exc: RequestValidationError): if request.url.path in routes_with_custom_exception: return JSONResponse(content={'401': 'Unauthorized'}, status_code=401)
Create a sub-application and mount it to the main app for the specific routes. Override the exception handler for RequestValidationError in the sub-application.
from fastapi import FastAPI, RequestValidationError, HTTPException from fastapi.responses import JSONResponse app = FastAPI() subapi = FastAPI() @subapi.exception_handler(RequestValidationError) async def validation_exception_handler(request: Request, exc: RequestValidationError): return JSONResponse(content={'401': 'Unauthorized'}, status_code=401) app.mount('/sub', subapi)
Create a custom APIRoute subclass and override the get_route_handler method. This allows you to intercept requests and handle RequestValidationError exceptions.
from fastapi import FastAPI from fastapi.routing import APIRoute from fastapi.responses import JSONResponse from fastapi.exceptions import RequestValidationError from fastapi.requests import Request class ValidationErrorHandlingRoute(APIRoute): def get_route_handler(self): original_route_handler = super().get_route_handler() async def custom_route_handler(request: Request): try: return await original_route_handler(request) except RequestValidationError as e: return JSONResponse(content={'401': 'Unauthorized'}, status_code=401) return custom_route_handler app = FastAPI() router = APIRouter(route_class=ValidationErrorHandlingRoute) @app.get('/') async def main(): return {'message': 'Hello from main API'} @router.get('/custom') async def custom_route(some_custom_header: str = Header(...)): return {'some-custom-header': some_custom_header} app.include_router(router)
The above is the detailed content of How to Customize FastAPI\'s Error Response for Specific Routes?. For more information, please follow other related articles on the PHP Chinese website!