Data Validation with Pydantic
Pydantic turns ordinary type hints into a powerful runtime validation engine. Define a model once and Pydantic parses, validates, and coerces messy external data into clean, typed Python objects — or tells you exactly what went wrong.
Learn Data Validation with Pydantic in our free Python course — an interactive lesson with runnable examples, a practice exercise and a quick reference.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
What You'll Learn in This Lesson
- • How to define models with BaseModel and type-annotated fields
- • How Pydantic validates and coerces incoming data automatically
- • Adding constraints with Field() and custom rules with @field_validator
- • Handling errors cleanly with ValidationError
- • Nested models, serialization with .model_dump() , and parsing with .model_validate()
- • Settings management and how Pydantic differs from dataclasses
🛡️ 1. Why Pydantic Exists
Real data is messy: missing keys, strings where numbers belong, extra fields. Pydantic validates it at runtime so the rest of your code can trust it.
You describe the shape of your data with normal Python type hints, and Pydantic enforces it.
📦 2. Your First Model
Notice that "42" became the integer 42 — Pydantic coerces compatible types by default.
🚨 3. Validation Errors
When data does not fit, Pydantic raises ValidationError :
The error object lists every failing field, the bad value, and why it failed.
🎚️ 4. Constraints with Field()
Use Field() to add bounds, defaults, and metadata:
Constraint
Meaning
gt / ge
Greater than / greater-or-equal
lt / le
Less than / less-or-equal
min_length / max_length
String / collection length bounds
✍️ 5. Custom Validators
For rules that constraints cannot express, use @field_validator (Pydantic v2):
Validators can also transform values (here we lowercased the username).
🪆 6. Nested Models
Models can contain other models, validated recursively:
The inner dict was validated and turned into a real Address instance.
🔁 7. Serialize and Parse
⚙️ 8. Settings Management
Pydantic's settings classes load configuration from environment variables, with validation:
⚖️ 9. Pydantic vs Dataclasses
Feature
dataclass
Pydantic BaseModel
Runtime validation
No
Yes
Type coercion
JSON serialization
Manual
Built in
Standard library
Third-party
Use a dataclass for simple in-memory records; use Pydantic when data crosses a boundary and must be validated.
🎉 Conclusion
✔ Validate external data with plain type hints
✔ Coerce and clean messy inputs automatically
Define the shape once, and trust your data everywhere after.
📋 Quick Reference — Pydantic
Syntax
What it does
class M(BaseModel)
Define a validated model
Field(gt=0, max_length=5)
Add field constraints
@field_validator(name)
Custom validation logic
m.model_dump()
Serialize model to a dict
M.model_validate(data)
Parse and validate input data
You can now model and validate real-world data with confidence using Pydantic.
Up next: NumPy — fast numerical computing with arrays and vectorized operations.
Practice quiz
What base class do you inherit from to define a Pydantic model?
- BaseModel
- DataModel
- Schema
- Validator
Answer: BaseModel. Pydantic models subclass pydantic.BaseModel, which drives validation, parsing, and serialization.
How does Pydantic decide what to validate on each field?
- From a separate schema file
- From method names
- From the field's type annotation
- From docstrings
Answer: From the field's type annotation. Pydantic reads the standard type annotations (name: str, age: int) and validates incoming data against them.
If you pass the string '42' to an int field in a Pydantic v2 model, what happens by default?
- It raises ValidationError immediately
- It is coerced to the integer 42
- It stays as the string '42'
- The field is set to None
Answer: It is coerced to the integer 42. By default Pydantic coerces compatible types, so '42' becomes the int 42. Use strict mode to forbid this.
Which exception does Pydantic raise when input data fails validation?
- AssertionError
- TypeError
- ValueError
- ValidationError
Answer: ValidationError. Pydantic raises pydantic.ValidationError, which collects every field error in one structured report.
Which helper adds constraints like a minimum value or max length to a field?
- Field()
- Constraint()
- Validate()
- Rule()
Answer: Field(). Field() lets you set constraints such as gt, ge, lt, le, min_length, max_length, and a default value.
In Pydantic v2, which decorator defines a custom validator for one or more fields?
- @constraint
- @field_validator
- @validator
- @check
Answer: @field_validator. Pydantic v2 uses @field_validator (the v1 @validator is deprecated) to run custom validation logic on fields.
What does the Pydantic v2 method model_dump() return?
- A new model instance
- The model's schema
- A JSON string
- A dict of the model's data
Answer: A dict of the model's data. model_dump() serializes the model into a plain dict; model_dump_json() produces a JSON string.
Which classmethod validates a dict (or object) into a model instance in Pydantic v2?
- model_load()
- model_build()
- model_validate()
- model_parse()
Answer: model_validate(). model_validate() takes external data and returns a validated model instance, replacing v1's parse_obj().
How do you model a field that itself contains another structured object?
- Use a dict type only
- Annotate the field with another BaseModel subclass
- Use a tuple
- It is not supported
Answer: Annotate the field with another BaseModel subclass. Nested models are just fields annotated with another BaseModel subclass; Pydantic validates them recursively.
Compared with a plain dataclass, what does Pydantic add automatically?
- Runtime data validation and type coercion
- Faster attribute access
- Nothing, they are identical
- Only a __repr__
Answer: Runtime data validation and type coercion. Dataclasses just store fields; Pydantic validates and coerces incoming data at runtime against the annotations.
Continue this course
- Previous: Final Project Ideas
- Next: NumPy for Numerical Computing