When validation fails, Pydantic raises a ValidationError with detailed information:
from pydantic import BaseModel, ValidationErrorclass User(BaseModel): id: int name: str age: inttry: user = User(id='not-a-number', name='John', age='25')except ValidationError as e: print(e) ''' 1 validation error for User id Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='not-a-number', input_type=str] '''
The error message tells you exactly which field failed (id), why it failed (unable to parse string as integer), and what the input was ('not-a-number').
from pydantic import BaseModel, Fieldclass Product(BaseModel): name: str = Field(min_length=1, max_length=100) description: str = Field(default='', max_length=500) price: float = Field(gt=0, le=1000000) # Greater than 0, less than or equal to 1M quantity: int = Field(ge=0) # Greater than or equal to 0product = Product( name='Widget', description='A useful widget', price=29.99, quantity=100)try: invalid_product = Product(name='', price=-10, quantity=50)except ValidationError as e: print(e) ''' 2 validation errors for Product name String should have at least 1 character [type=string_too_short, input_value='', input_type=str] price Input should be greater than 0 [type=greater_than, input_value=-10, input_type=int] '''
from pydantic import BaseModel, field_validatorclass Product(BaseModel): name: str sku: str @field_validator('name') @classmethod def name_must_contain_space(cls, v: str) -> str: if ' ' not in v: raise ValueError('Product name must contain a space') return v @field_validator('sku') @classmethod def sku_format(cls, v: str) -> str: if not v.startswith('SKU-'): raise ValueError('SKU must start with "SKU-"') return v.upper()product = Product(name='Super Widget', sku='sku-12345')print(product.sku)#> SKU-12345try: invalid = Product(name='Widget', sku='12345')except ValidationError as e: print(e) ''' 2 validation errors for Product name Value error, Product name must contain a space [type=value_error, input_value='Widget', input_type=str] sku Value error, SKU must start with "SKU-" [type=value_error, input_value='12345', input_type=str] '''
1
Define the validator
Use the @field_validator decorator on a classmethod
2
Receive the value
The validator receives the field value as its first argument
3
Validate and transform
Raise ValueError for invalid data, or return the (possibly modified) value
from pydantic import BaseModel, ValidationErrorclass Model(BaseModel): a: float b: inttry: Model(a='x', b='x')except ValidationError as e: # Get errors as list of dicts errors = e.errors() for error in errors: print(f"Field: {error['loc'][0]}") print(f"Error: {error['msg']}") print(f"Input: {error['input']}") print() # Get as JSON print(e.json())
Now that you understand the basics, explore more advanced features:
Models
Learn about model configuration, inheritance, and advanced features
Fields
Deep dive into field types, constraints, and customization
Validators
Master custom validation logic and transform data
Types
Explore built-in types for URLs, emails, dates, and more
Ready to use Pydantic in a real project? Check out the Examples section for common use cases like API validation, configuration management, and database models.