Skip to main content

Introduction

  • This article guides you through data validation with pydantic, a Python library whose validation core (pydantic-core) is written in Rust. The examples use pydantic v2.
  • Before we get started, make sure you have Python and the pydantic library installed in your environment. Check the pydantic installation command below.

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 a name, an age and an e-mail.
  • With this class, when we instantiate it, pydantic will validate that name and email are strings and age is an integer.

Using the model

  • Now that we have it created, we will instantiate the class. We will create a dict containing the data and unpack it into our class.
  • The above example will not raise any error since all fields have the correct type. By default, pydantic also converts compatible values: if age is the string "19", it becomes the integer 19. Now we will send wrong data to confirm that our validation works.
  • The above example raises a ValidationError because age needs to be an integer and "nineteen" cannot be converted to one:
  • To handle the error instead of letting it stop your program, catch it with try/except. Its errors() method lists each invalid field:

Strict mode

  • If you want to reject strings like "19" too, enable strict mode in the model. Then age only accepts a real int, and Person(name="John", age="19", email="john@example.com") raises ValidationError.

Creating a dataclass

  • You can also create dataclasses with pydantic. They are similar to standard Python dataclasses, but validate their fields like BaseModel.
  • If we send the string "19" to age, it will convert to the int 19.
Pydantic supports recursive validation, meaning that when validating nested models, it also validates the internal models.If a class has a list of Person, people: list[Person], pydantic checks each item of the list and converts it into a Person.

Extras

  • Pydantic has some extras, like e-mail validation and a fallback timezone package. To install them, run the following commands:
  • You can install both together by running the following command.
  • pydantic[email] adds the EmailStr type, which validates the user@domain.tld format and normalizes the address.

Validating environment variables at boot

  • Bots and APIs read tokens and settings from environment variables. With pydantic-settings, a missing or invalid variable stops the application at startup with a clear error, instead of failing later in the middle of a request.
  • Declare the variables your application needs in a class that inherits from BaseSettings. Each field reads the environment variable with the same name, ignoring case: discord_token reads DISCORD_TOKEN.
settings.py
  • If DISCORD_TOKEN isn’t set, Settings() raises a ValidationError for discord_token with the message Field required. A value like PORT=abc fails the same way, because port must be an integer.
  • SecretStr hides the token when you print or log the settings. Read the real value with settings.discord_token.get_secret_value().
  • On Square Cloud, set the variables in the dashboard or with squarecloud app env set, and list pydantic-settings in your requirements.txt. See Environment variables.

Next steps

Environment variables

Set the variables your settings class reads.

FastAPI

Deploy an API that validates its requests with pydantic.

Discord bot

Host a bot that reads its token from the environment.

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! Developers have already rated Square Cloud 4.9/5 across 402 reviews on Google and Trustpilot: leave yours too! It helps us understand what matters most to you.

Google Reviews

Leave your review in Google Reviews.

Trustpilot

Leave your review in Trustpilot.