Skip to main content

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.
pip install pydantic

Creating a model

  • First, we will need to import and make our class inherit from pydantic.BaseModel to start validating. In our example we will create a class named Person and it will have name, age and an e-mail.
from pydantic import BaseModel

class Person(BaseModel):
    name: str
    age: int
    email: str
  • With this class, when we instatiate it, pydantic will validate if the parameters name and email are strings and age is 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.
data = {
    "name": "John",
    "age": 19,
    "email": "john@gmail.com"
}
person = Person(**data)
  • 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.
data = {
    "name": "John",
    "age": "19",
    "email": "john@gmail.com"
}
person = Person(**data)
  • In the above example it will raise the error ValidationError because age needs 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.
from pydantic import dataclass

@dataclass
class Person:
    name: str
    age: int
    email: str
  • If we send a string to age, it will convert to int.
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:
pip install pydantic[email]
pip install pydantic[timezone]
  • You can install both together by running the following command.
pip install pydantic[email,timezone]
  • Pydantic[email] brings a class to handle emails, normalizing it and validanting the format user@domain.tld. For this, pydantic brings the class EmailStr to do this validation.
from pydantic import dataclass, EmailStr

@dataclass
class Person:
    name: str
    age: int
    email: EmailStr

Did you like this article?

  • This article was written with great care to help people like you. If it helped you in any way, please leave a review! Your feedback means a lot to us.