1. Installation
To start using Pydantic, you first need to install it. You can do this easily with pip:
pip install pydantic
Once installed, you’re ready to create your first Pydantic model! A model in Pydantic defines the structure of your data, including its types and any validation rules you need. Let’s look at a simple example to illustrate this.
Suppose you’re building an app that manages user profiles, and each profile needs to include a username, age, and a list of hobbies. Here’s how you could create a model for this data with Pydantic
2. Creating Your First Pydantic Model
Imagine you’re building an app that manages information about cars. Each car record should include details like the car's make, model, year, and whether it's electric.
Here's how you could create a Pydantic model for this data:
from pydantic import BaseModel
class Car(BaseModel):
make: str
model: str
year: int
is_electric: bool
In this example:
- We define a
Car class that inherits from BaseModel.
- Each field has a type:
make and model are str, year is an int, and is_electric is a bool.
- These types allow Pydantic to validate that any input data matches the expected structure.
Creating a Car Instance
With this model, creating a new Car instance is straightforward:
my_car = Car(
make="Tesla",
model="Model S",
year=2022,
is_electric=True
)
If we try to pass incorrect data types, like using a string for year or passing is_electric as a non-boolean value, Pydantic will raise an error to help catch the mistake early:
# This will raise an error because 'year' should be an integer
invalid_car = Car(
make="Toyota",
model="Camry",
year="twenty-twenty", # Incorrect type
is_electric="yes" # Incorrect type
)
This Car model allows you to easily manage and validate car data, ensuring it’s consistent and well-structured.