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