
FastAPI
Learn the fundamentals of validation errors in FastAPI.
FastAPI automatically validates request data using Pydantic models. When data doesn't match the expected format, FastAPI returns a 422 Unprocessable Entity response with detailed validation errors. Understanding these errors helps clients debug API usage issues.
In this section, you'll understand:
When you define a Pydantic model, FastAPI automatically validates incoming data:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
quantity: int
@app.post("/items/")
async def create_item(item: Item):
return itemInvalid request (price is string instead of float):
{
"name": "Widget",
"price": "not-a-number",
"quantity": 5
}FastAPI response (automatic validation error):
{
"detail": [
{
"loc": ["body", "price"],
"msg": "value is not a valid float",
"type": "value_error.float"
}
]
}# Invalid: Missing required field
{
"detail": [
{
"loc": ["body", "price"],
"msg": "field required",
"type": "value_error.missing"
}
]
}
# Invalid: Type mismatch
{
"detail": [
{
"loc": ["body", "quantity"],
"msg": "value is not a valid integer",
"type": "value_error.integer"
}
]
}
# Invalid: Multiple errors
{
"detail": [
{"loc": ["body", "name"], "msg": "field required", "type": "value_error.missing"},
{"loc": ["body", "price"], "msg": "value is not a valid float", "type": "value_error.float"}
]
}from pydantic import BaseModel, field_validator
class Product(BaseModel):
name: str
price: float
discount: float = 0
@field_validator('price')
def price_must_be_positive(cls, v):
if v <= 0:
raise ValueError('Price must be greater than 0')
return v
@field_validator('discount')
def discount_must_be_valid(cls, v, values):
if v > values.get('price', 0):
raise ValueError('Discount cannot exceed price')
return vValidation errors are critical for:
Example - User registration with custom validation:
from pydantic import BaseModel, EmailStr, field_validator
class UserCreate(BaseModel):
username: str
email: EmailStr
password: str
age: int
@field_validator('username')
def username_alphanumeric(cls, v):
if not v.isalnum():
raise ValueError('Username must be alphanumeric')
if len(v) < 3:
raise ValueError('Username must be at least 3 characters')
return v
@field_validator('password')
def password_strong(cls, v):
if len(v) < 8:
raise ValueError('Password must be at least 8 characters')
if not any(c.isupper() for c in v):
raise ValueError('Password must contain uppercase letters')
return v
@field_validator('age')
def age_valid(cls, v):
if v < 18:
raise ValueError('Must be at least 18 years old')
return v
@app.post("/register")
async def register(user: UserCreate):
return {"id": 1, "username": user.username}Ready to explore more? Check out the advanced section for production patterns and edge cases.
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward