Customising Error Responses in FastAPI
When receiving requests with invalid or unexpected data, it's often desirable to return a customised error response rather than the default FastAPI response. This guide addresses how to handle and customise error responses in FastAPI.
Specifically, the issue described pertains to receiving extra data in a request body, which results in a 422 Unprocessable Entity error with default error details. The goal is to handle this error gracefully and return a customised response, such as:
<code class="json">{ "error": { "message": "Invalid JSON body" }, "status": 0 }</code>
To customise error responses, FastAPI allows overriding the exception handler for validation errors. The following steps outline how to achieve this:
Import necessary libraries:
from fastapi import FastAPI, Body, Request, status from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse
Define a custom exception handler:
@app.exception_handler(RequestValidationError) async def validation_exception_handler(request: Request, exc: RequestValidationError): return JSONResponse( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, content={ "detail": exc.errors(), # optionally include the errors "body": exc.body, "custom msg": "Your error message" } )
Register the custom handler with the FastAPI app:
app = FastAPI()
Alternative Handler:
Alternatively, a PlainTextResponse can be used to return a simple 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>
By following these steps, you can handle validation errors gracefully and customise the error responses returned by your FastAPI application.
The above is the detailed content of How to Customize Error Responses for Validation Errors in FastAPI?. For more information, please follow other related articles on the PHP Chinese website!