Data Modeling with Pydantic
Applications constantly exchange and process data. Whether the data comes from user input, configuration files, APIs, or databases, ensuring that it is valid and correctly typed is essential. Pydantic is a modern Python library that simplifies data modeling and validation using Python’s type annotations. It automatically validates data, converts compatible types, and produces meaningful validation errors.Topics Covered
In this module, you’ll learn:- Why Pydantic?
- Creating Data Models
- Type Validation
- Default Values
- Optional Fields
- Field Validation
- Using
Annotated - Nested Models
- Serialization
- Deserialization
- Type-safe Programming
- Integrating Pydantic with Applications
- Best Practices
Try Yourself: 💻 VS Code | 🚀 Colab | 📥 DownloadBy the end of this module, you’ll be able to create robust, type-safe data models, validate incoming data, serialize and deserialize models, and integrate Pydantic into modern Python applications.
Verify Solutions: 💻 VS Code | 🚀 Colab | 📥 Download
Why Pydantic?
Suppose we want to represent a student. Using a dictionary,age should be an integer, Python accepts it as a string.
As applications grow, manually validating every field becomes repetitive and error-prone.
Pydantic solves this problem by automatically:
- Validating input data
- Converting compatible data types
- Producing informative validation errors
- Creating easy-to-use data models
Installing Pydantic
Using uvBaseModel.
Python Type Hinting & Generics
Before creating Pydantic models, you must understand how Python conveys data types. Python uses Type Hints (Type Annotations) to declare the expected data types of variables, function arguments, and return values.Basic Type Hinting Syntax
To annotate a variable or class attribute, use the colon (:) syntax:
Type Hinting Generics (Collections)
Modern Python (Python 3.9+) supports generic type hinting for collections directly using built-in classes:- Lists (
list[type]): Represents a list where all items match a specific type. - Dictionaries (
dict[key_type, value_type]): Represents a dictionary with specific key and value types. - Tuples (
tuple[type1, type2, ...]): Represents a tuple with fixed positions and types. - Sets (
set[type]): Represents a unique collection of items of a specific type.
Creating Your First Model
A Pydantic model looks similar to a regular Python class.Show Output
Show Output
__init__() method.
Pydantic automatically creates the constructor based on the declared fields.
Accessing Fields
Fields are accessed just like attributes of a regular Python object.Show Output
Show Output
Exercise 1
Create aBook model with the following fields:
titleauthorprice
Solution
Solution
Exercise 2
Create anEmployee model with the following fields:
idnamedepartment
Solution
Solution
Type Validation
One of Pydantic’s biggest advantages is automatic type validation.Show Output
Show Output
Show Output
Show Output
Exercise 1
Create aProduct model with the following fields:
nameprice
Solution
Solution
Exercise 2
Create aStudent model with an integer field age.
Pass "abc" as the value.
Observe the validation error.
Solution
Solution
Default Values
Fields can have default values.Show Output
Show Output
Exercise 1
Create anEmployee model with a default country of "India".
Expected Output
Solution
Solution
Exercise 2
Create aProduct model with a default quantity of 1.
Solution
Solution
Optional Fields
Some fields are optional. Modern Python uses the union operator (|) to indicate optional values.
Show Output
Show Output
Show Output
Show Output
Exercise 1
Create aBook model with an optional ISBN field.
Solution
Solution
Exercise 2
Create anEmployee model with an optional phone number.
Solution
Solution
Field Validation
Pydantic allows you to define validation rules for individual fields using theField() function.
Some commonly used validation constraints are:
Example
Show Output
Show Output
Show Output
Show Output
Exercise 1
Create aProduct model.
Requirements:
- Name should contain at least 3 characters.
- Price should be greater than 0.
Solution
Solution
Exercise 2
Create anEmployee model.
Requirements:
- Age between 18 and 60.
Solution
Solution
Using Annotated (Recommended)
Pydantic v2 recommends using Annotated to separate type information from validation metadata.
Instead of
Example
Show Output
Show Output
Why Prefer Annotated?
- Keeps the type separate from validation rules.
- Recommended in Pydantic v2.
- Extensively used in FastAPI.
- Improves readability.
Exercise 1
Create aBook model.
Requirements:
- Title should contain at least 3 characters.
- Price should be greater than 0.
Solution
Solution
Exercise 2
Create aStudent model.
Requirements:
- Age between 18 and 30.
Solution
Solution
Nested Models
Real-world data often contains other objects. Pydantic allows one model to contain another model.Show Output
Show Output
Address object.
Exercise 1
Create aCompany model and use it inside an Employee model.
Sample Input
Solution
Solution
Exercise 2
Create aCourse model inside a Student model.
Solution
Solution
Collections of Models
A field can also contain multiple nested models.Show Output
Show Output
Exercise 1
Create aDepartment model containing multiple employees.
Solution
Solution
Exercise 2
Create anOrder model containing multiple products.
Solution
Solution
Serialization
Serialization is the process of converting a Python object into a format that can be stored or transmitted. Pydantic provides themodel_dump() method to convert a model into a Python dictionary.
Example
Show Output
Show Output
Converting to JSON
Usemodel_dump_json() to generate a JSON string.
Show Output
Show Output
Exercise 1
Create anEmployee model and convert it into a dictionary.
Solution
Solution
Exercise 2
Convert aBook model into JSON.
Solution
Solution
Deserialization
Deserialization is the process of creating a model from external data.Creating a Model from a Dictionary
Usemodel_validate().
Show Output
Show Output
Creating a Model from JSON
Usemodel_validate_json().
Show Output
Show Output
Exercise 1
Create anEmployee model from a dictionary.
Solution
Solution
Exercise 2
Create aBook model from a JSON string.
Solution
Solution
Type-safe Programming
Pydantic encourages type-safe programming by ensuring that data always conforms to the expected model. Instead of working with dictionaries,- Better code completion in IDEs.
- Early error detection.
- Improved readability.
- Self-documenting code.
- Easier refactoring.
Example
Show Output
Show Output
Exercise 1
Create aCustomer model and access its fields using dot notation.
Solution
Solution
Exercise 2
Create anOrder model and display the product name.
Solution
Solution
Integrating Pydantic with Applications
Pydantic models are widely used in modern Python applications. Common use cases include:- Validating user input.
- Reading configuration.
- Working with APIs.
- Processing JSON data.
- Request and response models in FastAPI.
Example
Suppose an application receives user information.Show Output
Show Output
Exercise 1
Create aLoginRequest model and validate a dictionary.
Solution
Solution
Exercise 2
Create aRegistrationRequest model and validate incoming data.
Solution
Solution
Best Practices
- Prefer
AnnotatedwithField()for validation. - Use meaningful model names.
- Group related fields into nested models.
- Reuse models whenever possible.
- Keep validation rules close to the fields.
- Prefer Pydantic models over plain dictionaries for structured data.
- Use
model_dump()andmodel_dump_json()for serialization. - Use
model_validate()andmodel_validate_json()for deserialization. - Design models that accurately represent your application’s data.
Practice
To reinforce what you’ve learned in this section, practice with the interactive follow-along notebook:Follow-Along Practice
Practice creating BaseModel schemas, field validations with Field(), separating types with Annotated, nested models, and model serialization.💻 VS Code | 🚀 Colab | 📥 Download
Summary
In this module, you learned how Pydantic simplifies data modeling and validation in modern Python applications.Key Concepts Covered
- Why Pydantic?
- Creating Data Models
- Type Validation
- Default Values
- Optional Fields
- Field Validation
- Using
Annotated - Nested Models
- Collections of Models
- Serialization
- Deserialization
- Type-safe Programming
- Integrating Pydantic with Applications
- Best Practices