Home > Backend Development > Python Tutorial > How to Customise Error Responses in FastAPI?

How to Customise Error Responses in FastAPI?

DDD
Release: 2024-10-21 06:32:29
Original
953 people have browsed it

How to Customise Error Responses in FastAPI?

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

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template