How to Use RequestValidationError in FastAPI for Custom Error Handling
In FastAPI,
RequestValidationError is raised automatically when request data fails validation. You can catch it by creating an exception handler with @app.exception_handler(RequestValidationError) to customize the error response sent back to the client.Syntax
The RequestValidationError is an exception class from fastapi.exceptions used to handle validation errors in request data. You use it by defining an exception handler function decorated with @app.exception_handler(RequestValidationError). This function receives the request and the error instance, allowing you to customize the response.
@app.exception_handler(RequestValidationError): Decorator to register the handler.def handler(request, exc):Function to process the error.exc.errors(): Method to get detailed validation errors.JSONResponse: Used to send a custom JSON response.
python
from fastapi import FastAPI, Request 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=422, content={"detail": exc.errors(), "body": exc.body}, )
Example
This example shows how to catch RequestValidationError to return a custom JSON response when the request body does not match the expected model.
python
from fastapi import FastAPI, Request from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str price: float @app.exception_handler(RequestValidationError) async def validation_exception_handler(request: Request, exc: RequestValidationError): return JSONResponse( status_code=422, content={ "message": "Oops! Validation failed.", "errors": exc.errors(), "received": exc.body }, ) @app.post("/items/") async def create_item(item: Item): return {"item_name": item.name, "item_price": item.price}
Output
When POSTing to /items/ with invalid data (e.g., missing 'price'):
{
"message": "Oops! Validation failed.",
"errors": [
{
"loc": ["body", "price"],
"msg": "field required",
"type": "value_error.missing"
}
],
"received": {"name": "apple"}
}
Common Pitfalls
Common mistakes when using RequestValidationError include:
- Not registering the exception handler, so FastAPI returns the default error response.
- Trying to catch
RequestValidationErrorinside route functions instead of using the global exception handler. - Not awaiting the handler function if it is async.
- Returning non-JSON responses or incorrect status codes.
Always use @app.exception_handler(RequestValidationError) to handle these errors globally.
python
from fastapi import FastAPI from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse app = FastAPI() # Wrong: Trying to catch inside route (won't work) @app.post("/wrong/") async def wrong_handler(item: dict): try: # validation error won't be caught here return item except RequestValidationError: return JSONResponse({"error": "Validation failed"}) # Right: Use global exception handler @app.exception_handler(RequestValidationError) async def correct_handler(request, exc): return JSONResponse({"error": "Validation failed"}, status_code=422)
Quick Reference
Summary tips for using RequestValidationError in FastAPI:
- Import from
fastapi.exceptions. - Use
@app.exception_handler(RequestValidationError)to catch validation errors globally. - Access detailed errors with
exc.errors(). - Return a
JSONResponsewith status code 422 for validation errors. - Do not try to catch validation errors inside route functions.
Key Takeaways
Use @app.exception_handler(RequestValidationError) to catch validation errors globally in FastAPI.
Access detailed validation error info with exc.errors() inside the handler.
Return a JSONResponse with status code 422 to inform clients about validation issues.
Do not try to catch RequestValidationError inside route functions; use the global handler instead.
Customizing RequestValidationError responses improves API usability and client feedback.