How to Customize Error Responses for Validation Errors in FastAPI?

Mary-Kate Olsen
Release: 2024-10-21 06:23:30
Original
695 people have browsed it

How to Customize Error Responses for Validation Errors in FastAPI?

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

To customise error responses, FastAPI allows overriding the exception handler for validation errors. The following steps outline how to achieve this:

  1. Import necessary libraries:

    from fastapi import FastAPI, Body, Request, status
    from fastapi.exceptions import RequestValidationError
    from fastapi.responses import JSONResponse
    Copy after login
  2. 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"
            }
        )
    Copy after login
  3. Register the custom handler with the FastAPI app:

    app = FastAPI()
    Copy after login
  4. Test the custom error handler:
    Send a request with invalid data (e.g., extra data in the request body) to trigger the exception handler.

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

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!

source:php
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!