How to Customize FastAPI\'s Error Response for Specific Routes?

Mary-Kate Olsen
Release: 2024-11-20 00:35:02
Original
653 people have browsed it

How to Customize FastAPI's Error Response for Specific Routes?

Customize Error Response for Specific Route in FastAPI

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:

Option 1: Override Default Exception Handler

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)
Copy after login

Option 2: Use Sub-Application(s)

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)
Copy after login

Option 3: Use Custom APIRouter and APIRoute

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template