Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I return 400 error instead of 422 error [duplicate]

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?

like image 873
Konstantinos Avatar asked Sep 02 '25 13:09

Konstantinos


1 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.

like image 149
Aksen P Avatar answered Sep 05 '25 02:09

Aksen P