How to Use field_validator in Pydantic v2 with FastAPI
@field_validator decorator inside your model class to validate fields. In FastAPI, define your model with @field_validator methods to customize validation logic for request data easily.Syntax
The @field_validator decorator is used inside a Pydantic model class to add validation logic for one or more fields. You decorate a method with @field_validator('field_name'), and this method receives the field value to validate or transform it.
The method should return the validated or modified value. You can also validate multiple fields by listing them in the decorator.
from pydantic import BaseModel, field_validator class User(BaseModel): name: str age: int @field_validator('age') def check_age(cls, value): if value < 18: raise ValueError('Age must be at least 18') return value
Example
This example shows a FastAPI app using a Pydantic v2 model with @field_validator to ensure the user's age is at least 18. If validation fails, FastAPI returns a clear error response.
from fastapi import FastAPI from pydantic import BaseModel, field_validator app = FastAPI() class User(BaseModel): name: str age: int @field_validator('age') def age_must_be_adult(cls, value): if value < 18: raise ValueError('User must be at least 18 years old') return value @app.post('/users/') async def create_user(user: User): return {'message': f'User {user.name} is valid and {user.age} years old'}
Common Pitfalls
- Not using
clsas the first argument in the validator method causes errors. - Returning
Noneor not returning the value from the validator method breaks validation. - Using the old
@validatordecorator from Pydantic v1 will not work in v2. - For multiple fields, forgetting to list all field names in
@field_validatorcauses the validator not to run.
from pydantic import BaseModel, field_validator class User(BaseModel): age: int # Wrong: missing cls argument @field_validator('age') def check_age(value): if value < 18: raise ValueError('Too young') return value # Correct: @field_validator('age') def check_age(cls, value): if value < 18: raise ValueError('Too young') return value
Quick Reference
Use @field_validator('field_name') on a class method with cls and value parameters. Return the validated or transformed value. Raise ValueError to reject invalid data.
In FastAPI, use these models as request bodies to get automatic validation.
| Feature | Description |
|---|---|
| @field_validator('field') | Decorator to validate a specific field |
| Method signature | Must accept (cls, value) and return value |
| Raise error | Raise ValueError to reject invalid input |
| Multiple fields | List multiple field names in decorator |
| FastAPI usage | Use validated models as request bodies |