How to customise error response in FastAPI?

You are passing an invalid JSON, and hence, the server correctly responds with the 422 Unprocessable Entity error. Your test client shouldn’t be able to run at all, without throwing an invalid syntax error. So, I’m guessing you posted the request through the interactive autodocs provided by Swagger UI at /docs, and received the relevant 422 error.

If what you actually want is to handle the error, in order to customise the error or something, you can override the request validation exception handler, as described in the documentation (have a look at this discussion, as well as this answer and this answer that demonstrates how to customise the RequestValidationError for specific routes only).

Working Example:

from fastapi import FastAPI, Body, Request, status
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel

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 some_func(d: Demo):
    return d.content

Or, you could also return a PlainTextResponse with a custom message:

from fastapi.responses import PlainTextResponse

@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
    return PlainTextResponse(str(exc), status_code=422) 

Leave a Comment