Customising Error Responses in FastAPI
When receiving invalid JSON requests, FastAPI typically returns a 422 Unprocessable Entity error with detailed information about the issue. However, it is possible to customise this error response with your own message and structure.
One way to handle this is to override the default request validation exception handler. This can be done by implementing a custom exception handler decorator. Here's an example that modifies the error response to include a custom message:
<code class="python">from fastapi import FastAPI, Body, Request, status from fastapi.encoders import jsonable_encoder from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse app = FastAPI() @app.exception_handler(RequestValidationError) async def validation_exception_handler(request: Request, exc: RequestValidationError): return JSONResponse( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, content=jsonable_encoder({ "detail": exc.errors(), # optionally include the errors "body": exc.body, "custom msg": {"Your error message"} }), ) class Demo(BaseModel): content: str = None @app.post("/demo") async def demo_func(d: Demo): return d.content</code>
This exception handler will return a JSON response with a custom message, along with the original validation errors and body of the request.
Alternatively, you can customise the error response as a plain text message:
<code class="python">from fastapi.responses import PlainTextResponse @app.exception_handler(RequestValidationError) async def validation_exception_handler(request, exc): return PlainTextResponse(str(exc), status_code=422) </code>
This handler will output a simple plain text string representing the error message. Both these methods allow you to customise the error response to provide a more user-friendly or context-specific message to your API users.
The above is the detailed content of How to Customise Error Responses in FastAPI?. For more information, please follow other related articles on the PHP Chinese website!