Introduction
- This article guides you through data validation with pydantic. Pydantic is a Python library built in Rust.
- Before we get start, make sure you have Python and Pydantic library installed on your environment. Check the pydantic instalation command below.
Creating a model
- First, we will need to import and make our class inherit from
pydantic.BaseModelto start validating. In our example we will create a class namedPersonand it will have name, age and an e-mail.
- With this class, when we instatiate it, pydantic will validate if the parameters
nameandemailare strings andageis integer.
Using the model
- Now we have it created, we will instantiate the class. We will create a dict containing the data and unpack it to our class.
- The above example will not raise any error since all parameters are on correct type. Now we will make a wrong data to confirm if our validation work.
- In the above example it will raise the error
ValidationErrorbecauseageneeds to be an integer and cannot be provided as a string.
Creating dataclass
- You can also create dataclasses with pydantic which will be similar to standard Python dataclasses but will have validations like BaseModel.
- If we send a
stringtoage, it will convert toint.
Pydantic supports recursive validation, meaning that when validating nested models, it also validates the internal
models.If some class has a list of
Person, people: list[Person], it will check each item on the list and converts it into a Person.Extras
- Pydantic has some extras like e-mail validations and a fallback timezone package. To install them, you need to run the following commands:
- You can install both together by running the following command.
- Pydantic[email] brings a class to handle emails, normalizing it and validanting the format
user@domain.tld. For this, pydantic brings the classEmailStrto do this validation.
Did you like this article?
- We created this content with great care to offer the best help possible. If this article helped you in any way, support our work! Leave your review! it helps us understand what matters most to you.

