0
0
FastapiHow-ToBeginner · 4 min read

How to Use field_validator in Pydantic v2 with FastAPI

In Pydantic v2, use the @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.

python
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.

python
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'}
Output
POST /users/ with JSON {"name": "Alice", "age": 20} returns {"message": "User Alice is valid and 20 years old"} POST /users/ with JSON {"name": "Bob", "age": 16} returns 422 Unprocessable Entity with validation error "User must be at least 18 years old"
⚠️

Common Pitfalls

  • Not using cls as the first argument in the validator method causes errors.
  • Returning None or not returning the value from the validator method breaks validation.
  • Using the old @validator decorator from Pydantic v1 will not work in v2.
  • For multiple fields, forgetting to list all field names in @field_validator causes the validator not to run.
python
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.

FeatureDescription
@field_validator('field')Decorator to validate a specific field
Method signatureMust accept (cls, value) and return value
Raise errorRaise ValueError to reject invalid input
Multiple fieldsList multiple field names in decorator
FastAPI usageUse validated models as request bodies

Key Takeaways

Use @field_validator inside Pydantic v2 models to validate or transform fields.
Always define validator methods with cls and value parameters and return the value.
Raise ValueError inside validators to reject invalid data with clear errors.
In FastAPI, validated Pydantic models automatically enforce these rules on request data.
Avoid using old @validator decorator from Pydantic v1 as it is incompatible with v2.