How to Use Validator in Pydantic in FastAPI
In FastAPI, use Pydantic's
@validator decorator inside your model class to add custom validation logic for fields. Define a method with @validator('field_name') that receives the field value and returns the validated or transformed value. This method runs automatically when the model is created.Syntax
Use the @validator decorator inside a Pydantic model class to create custom validation for one or more fields.
@validator('field_name'): Decorator specifying which field to validate.- Method receives
clsandvalueparameters. - Return the validated or transformed
value. - Raise
ValueErrorto reject invalid data.
python
from pydantic import BaseModel, validator class User(BaseModel): username: str age: int @validator('age') def age_must_be_adult(cls, value): if value < 18: raise ValueError('Age must be at least 18') return value
Example
This example shows a FastAPI app with a Pydantic model that uses a validator to ensure the user's age is 18 or older. If the validation fails, FastAPI returns a clear error response.
python
from fastapi import FastAPI from pydantic import BaseModel, validator app = FastAPI() class User(BaseModel): username: str age: int @validator('age') def age_must_be_adult(cls, value): if value < 18: raise ValueError('Age must be at least 18') return value @app.post('/users/') async def create_user(user: User): return {'message': f'User {user.username} is valid and created.'}
Output
POST /users/ with JSON {"username": "alice", "age": 17} returns 422 Unprocessable Entity with error about age
POST /users/ with JSON {"username": "alice", "age": 20} returns 200 OK with message 'User alice is valid and created.'
Common Pitfalls
Common mistakes when using @validator include:
- Not returning the value from the validator method, which breaks validation.
- Raising generic exceptions instead of
ValueErrororTypeError, which Pydantic expects. - Using
@validatoron a non-existent field name. - Forgetting that validators run on model creation, so side effects inside validators can cause unexpected behavior.
python
from pydantic import BaseModel, validator class Product(BaseModel): price: float # Wrong: missing return @validator('price') def price_must_be_positive(cls, value): if value <= 0: raise ValueError('Price must be positive') # Missing return here causes error # Correct: @validator('price') def price_must_be_positive_correct(cls, value): if value <= 0: raise ValueError('Price must be positive') return value
Quick Reference
Tips for using @validator in Pydantic with FastAPI:
- Use
@validator('field_name')for single field validation. - Use
@validator('field1', 'field2')to validate multiple fields with one method. - Always return the value after validation.
- Raise
ValueErrorto signal invalid data. - Validators run automatically when the model is created or parsed.
Key Takeaways
Use Pydantic's @validator decorator inside your model to add custom validation logic.
Always return the validated value and raise ValueError to reject invalid input.
Validators run automatically when FastAPI parses request data into models.
Common errors include forgetting to return the value or using wrong exception types.
You can validate one or multiple fields with a single validator method.