![]() |
VOOZH | about |
The Pydantic library in Python is used for data validation and data parsing using Python type hints. It ensures that data structures like classes, dictionaries or API inputs contain valid and correctly typed data before being processed. Pydantic automatically converts and validates incoming data, helping developers write cleaner, more reliable code.
Before using Pydantic, install it using pip, including the optional settings module:
pip install pydantic pydantic-settings
Pydantic has some core concepts that make it easy to work with data models. Some of them are:
A Pydantic model is a Python class that defines the structure of your data using type hints. It automatically checks and converts input values to the correct types.
For example, let’s create a simple UserProfile model with three fields name, age and email. When we create an instance, Pydantic validates the data types automatically.
Output:
name='Liam Svensson' age=40 email='liam.svensson@example.com'
Once you create a model instance, you can easily access and update its attributes just like a normal Python object. Pydantic still keeps validation in place when you modify values.
Output:
Liam Svensson
41
Pydantic lets you set default values for fields and mark others as required. If a field has a default value, it’s automatically used when that field is missing in input data.
Output:
name='Sofia Moretti' age=43 email='sofia.moretti@example.com' is_active=True
Pydantic offers more advanced validation techniques through decorators and custom validators.
Field validators let you define custom validation rules for individual fields. They are useful when you need to enforce constraints beyond type checking.
Output:
ValidationError: 1 validation error for UserProfile
age
Value error, Age must be at least 18 [type=value_error, input_value=17, input_type=int]
For further information visit https://errors.pydantic.dev/2.11/v/value_error
Model validators let you define validation rules that involve multiple fields or the model as a whole.
Output:
ValidationError: 1 validation error for User
Value error, Passwords do not match [type=value_error, input_value={'password': 'a', 'confirm_password': 'b'}, input_type=dict]
For further information visit https://errors.pydantic.dev/2.11/v/value_error
Nested models allow Pydantic to handle hierarchical or complex data structures cleanly.
Output:
name='Emma Dubois' age=34 email='emma.dubois@example.fr' address=Address(street='10 Rue de la Paix', city='Paris')
Pydantic makes it easy to parse data from different formats and serialize it back to JSON or other formats.
Pydantic can parse JSON or other serialized data formats into Python objects automatically, validating types in the process.
Output:
name='Noah Kim' age=28 email='noah.kim@example.kr'
You can convert a Pydantic model back to JSON for storage, APIs or communication with other systems.
Output:
{"name":"Luca Rossi","age":29,"email":"luca.rossi@example.it"}
Pydantic allows optional fields using Python’s Optional type which default to None if not provided. This is useful for fields that may be missing.
Output:
name='Mia Johansson' age=None email='mia.johansson@example.se'
Pydantic provides BaseSettings to manage configuration via environment variables, .env files and other sources. This is useful for real-world apps where settings may change between environments.
Output:
TestApp
Pydantic supports constrained types and custom data classes to enforce stricter rules, reducing boilerplate validation.
Output:
name='Pen' price=10 tags=['stationery']
Pydantic allows you to set aliases, default values and metadata for fields. This is useful when your external data uses different field names or when you want to provide descriptive information for documentation.
Output:
{'full_name': 'Rita', 'age': 18}
By default, Pydantic coerces types (e.g., "1" -> 1). Strict types prevent this coercion, ensuring that the input type matches exactly.
Output:
ValidationError: 1 validation error for Account
id
Input should be a valid integer [type=int_type, input_value='5', input_type=str]
For further information visit https://errors.pydantic.dev/2.11/v/int_type
Pydantic allows you to handle validation errors and customize messages using validators. This is particularly useful in APIs where you want to provide structured and clear error feedback.
Output:
[{"type":"value_error","loc":["age"],"msg":"Value error, User must be 18 or older","input":16,"ctx":{"error":"User must be 18 or older"},"url":"https://errors.pydantic.dev/2.11/v/value_error"}]
The key strategies to optimize Pydantic for speed and efficiency are as follows:
Pydantic is widely used in Python projects for reliable and type-safe data handling. The main use cases are as follows: