pydantic-core) is written in Rust. The examples use pydantic v2. You need Python and the pydantic library:
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 a name, an age and an e-mail.
- With this class, when we instantiate it, pydantic will validate that
nameandemailare strings andageis 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
ageis the string"19", it becomes the integer19. Now we will send wrong data to confirm that our validation works.
- The above example raises a
ValidationErrorbecauseageneeds 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. Itserrors()method lists each invalid field:
Strict mode
- If you want to reject strings like
"19"too, enable strict mode in the model. Thenageonly accepts a realint, andPerson(name="John", age="19", email="john@example.com")raisesValidationError.
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"toage, it will convert to theint19.
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 theEmailStrtype, which validates theuser@domain.tldformat 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_tokenreadsDISCORD_TOKEN.
settings.py
- If
DISCORD_TOKENisn’t set,Settings()raises aValidationErrorfordiscord_tokenwith the messageField required. A value likePORT=abcfails the same way, becauseportmust be an integer. SecretStrhides the token when you print or log the settings. Read the real value withsettings.discord_token.get_secret_value().
Run it on Square Cloud
List pydantic and its extras in yourrequirements.txt, so Square Cloud installs them during the deploy:
requirements.txt
squarecloud.app file at the root of your project. For a bot whose main file is main.py and imports settings from settings.py:
squarecloud.app
.py files, requirements.txt and squarecloud.app, without the token. Set DISCORD_TOKEN and the other variables in the dashboard or with squarecloud app env set: see Environment variables. If a required variable is missing, the ValidationError shows up in the application’s logs as soon as it starts.
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.

