Can I return 400 error instead of 422 error

Question:

I validate data using Pydantic schema in my FastAPI project and if it is not ok it returns 422. Can I change it to 400?

Asked By: Konstantinos

||

Answers:

Yes, you can. For example, you can apply the next exception handler:

from fastapi import FastAPI, Request, status
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_400_BAD_REQUEST,
        content={"detail": exc.errors()},
    )

# your routes and endpoints here

In this case any validation errors raised by Pydantic will result in a 400 Bad Request status code being returned by your API. The exc.errors() contains the validation errors.

Answered By: Aksen P
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.