Skip to main content

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:
  1. Why Pydantic?
  2. Creating Data Models
  3. Type Validation
  4. Default Values
  5. Optional Fields
  6. Field Validation
  7. Using Annotated
  8. Nested Models
  9. Serialization
  10. Deserialization
  11. Type-safe Programming
  12. Integrating Pydantic with Applications
  13. Best Practices
Try Yourself: 💻 VS Code | 🚀 Colab | 📥 Download
Verify Solutions: 💻 VS Code | 🚀 Colab | 📥 Download
By 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.

Why Pydantic?

Suppose we want to represent a student. Using a dictionary,
Although 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
Instead of working with dictionaries, we work with models.

Installing Pydantic

Using uv
Using pip
Import the base model.
Every Pydantic model inherits from BaseModel.

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.
Pydantic reads these exact standard type annotations at runtime to parse and validate incoming data dynamically.

Creating Your First Model

A Pydantic model looks similar to a regular Python class.
Creating an object.
Output ?
Notice that we didn’t define an __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.
Output ?

Exercise 1

Create a Book model with the following fields:
  • title
  • author
  • price
Sample Input
Expected Output

Exercise 2

Create an Employee model with the following fields:
  • id
  • name
  • department
Sample Input
Expected Output

Type Validation

One of Pydantic’s biggest advantages is automatic type validation.
Output ?
Pydantic automatically converts compatible values whenever possible. If conversion is not possible, a validation error is raised.
Output ?

Exercise 1

Create a Product model with the following fields:
  • name
  • price
Pass the price as a string. Observe the result.

Exercise 2

Create a Student model with an integer field age. Pass "abc" as the value. Observe the validation error.

Default Values

Fields can have default values.
Output ?

Exercise 1

Create an Employee model with a default country of "India". Expected Output

Exercise 2

Create a Product model with a default quantity of 1.

Optional Fields

Some fields are optional. Modern Python uses the union operator (|) to indicate optional values.
Output ?
Providing the optional value.
Output ?

Exercise 1

Create a Book model with an optional ISBN field.

Exercise 2

Create an Employee model with an optional phone number.

Field Validation

Pydantic allows you to define validation rules for individual fields using the Field() function. Some commonly used validation constraints are:

Example

Output ?
Providing invalid data raises a validation error.
Output ?

Exercise 1

Create a Product model. Requirements:
  • Name should contain at least 3 characters.
  • Price should be greater than 0.
Sample Input
Expected Output

Exercise 2

Create an Employee model. Requirements:
  • Age between 18 and 60.
Pydantic v2 recommends using Annotated to separate type information from validation metadata. Instead of
the modern approach is
This keeps the type declaration clean and improves compatibility with IDEs and type checkers.

Example

Output ?

Why Prefer Annotated?

  • Keeps the type separate from validation rules.
  • Recommended in Pydantic v2.
  • Extensively used in FastAPI.
  • Improves readability.

Exercise 1

Create a Book model. Requirements:
  • Title should contain at least 3 characters.
  • Price should be greater than 0.
Sample Input
Expected Output

Exercise 2

Create a Student model. Requirements:
  • Age between 18 and 30.

Nested Models

Real-world data often contains other objects. Pydantic allows one model to contain another model.
Output ?
Notice that Pydantic automatically converts the dictionary into an Address object.

Exercise 1

Create a Company model and use it inside an Employee model. Sample Input

Exercise 2

Create a Course model inside a Student model.

Collections of Models

A field can also contain multiple nested models.
Output ?

Exercise 1

Create a Department model containing multiple employees.

Exercise 2

Create an Order model containing multiple products.

Serialization

Serialization is the process of converting a Python object into a format that can be stored or transmitted. Pydantic provides the model_dump() method to convert a model into a Python dictionary.

Example

Output ?

Converting to JSON

Use model_dump_json() to generate a JSON string.
Output ?

Exercise 1

Create an Employee model and convert it into a dictionary.

Exercise 2

Convert a Book model into JSON.

Deserialization

Deserialization is the process of creating a model from external data.

Creating a Model from a Dictionary

Use model_validate().
Output ?

Creating a Model from JSON

Use model_validate_json().
Output ?

Exercise 1

Create an Employee model from a dictionary.

Exercise 2

Create a Book model from a JSON string.

Type-safe Programming

Pydantic encourages type-safe programming by ensuring that data always conforms to the expected model. Instead of working with dictionaries,
we work with objects.
This provides several benefits:
  • Better code completion in IDEs.
  • Early error detection.
  • Improved readability.
  • Self-documenting code.
  • Easier refactoring.

Example

Output ?

Exercise 1

Create a Customer model and access its fields using dot notation.

Exercise 2

Create an Order model and display the product name.

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.
Output ?
Instead of manually validating every field, Pydantic performs the validation automatically. This makes applications simpler, safer, and easier to maintain.

Exercise 1

Create a LoginRequest model and validate a dictionary.

Exercise 2

Create a RegistrationRequest model and validate incoming data.

Best Practices

  • Prefer Annotated with Field() 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() and model_dump_json() for serialization.
  • Use model_validate() and model_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
Pydantic combines Python’s type annotations with automatic validation, making it easy to build reliable, maintainable, and type-safe applications. It has become a fundamental library in the modern Python ecosystem and is extensively used in frameworks such as FastAPI.