ValidationError in FastAPI
FastAPI raises RequestValidationError when request data doesn't match your Pydantic models. This is the framework's primary defense against bad input.
Why You See It
- Client sends wrong types (string instead of int)
- Required fields missing from request body
- Nested model validation failing
How to Handle It
Customize the error response for better client experience:
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
app = FastAPI()
@app.exception_handler(RequestValidationError)
async def validation_handler(request: Request, exc: RequestValidationError):
errors = []
for error in exc.errors():
errors.append({
"field": " -> ".join(str(l) for l in error["loc"][1:]),
"message": error["msg"],
"type": error["type"],
})
return JSONResponse(status_code=422, content={"errors": errors})
class Item(BaseModel):
name: str = Field(min_length=1, max_length=100)
price: float = Field(gt=0)
quantity: int = Field(ge=1, le=10000)Return user-friendly error messages that map to form fields, making it easy for frontend developers to display inline errors.
Prevention Tips
To avoid this issue recurring, add automated checks to your CI/CD pipeline. Write integration tests that exercise the failure path — not just the happy path. Use linting rules to enforce best practices across your team. Consider adding health checks that detect this class of error early in staging before it reaches production.
Bugsly for FastAPI
Bugsly aggregates validation errors by endpoint and field, showing you which parts of your API receive the most invalid data — so you can improve docs or client-side validation.
Try Bugsly Free
AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.
Get Started FreeRelated Articles
Fix Iterator Protocol Error in Node.js
Resolve 'is not iterable' and iterator protocol errors in Node.js by implementing Symbol.iterator correctly on custom objects.
Read moreHow to Fix Query Error in Svelte
Learn how to diagnose and fix the query error in Svelte. Includes code examples and prevention tips.
Read moreHow to Fix CORS Policy Blocked Error in Node.js
Learn how to fix the CORS Policy Blocked Error in Node.js. Step-by-step guide with code examples.
Read moreHow to Fix Geolocation Permission Denied in Angular
Learn how to fix the Geolocation Permission Denied in Angular. Step-by-step guide with code examples.
Read more