FastAPI uses status code 422 Unprocessable Entity by default for validation errors. This means the server understood the request but the data did not pass validation.
from fastapi import FastAPI, Request from fastapi.responses import JSONResponse from fastapi.exceptions import RequestValidationError app = FastAPI() @app.exception_handler(RequestValidationError) async def validation_exception_handler(request: Request, exc: RequestValidationError): return JSONResponse( status_code=400, content={"detail": exc.errors(), "body": exc.body}, )
FastAPI allows customizing validation error responses by defining an exception handler for RequestValidationError using @app.exception_handler.
from fastapi import FastAPI from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse app = FastAPI() @app.exception_handler(Exception) async def generic_exception_handler(request, exc): if isinstance(exc, RequestValidationError): return JSONResponse(status_code=400, content={"error": "Validation failed"}) return JSONResponse(status_code=500, content={"error": "Server error"})
FastAPI uses the most specific exception handler first. Since there is no handler for RequestValidationError, it uses the default one before the generic Exception handler. So this generic handler never catches validation errors.
The default validation error response includes a key "detail" which is a list of error objects. Each error object has keys like "loc" (location), "msg" (message), and "type" (error type).
FastAPI does not provide a built-in way to change the validation error status code globally without a custom handler. Using middleware to catch responses with status 422 and change them to 400 is a practical approach without overriding handlers.