What Is Pydantic?
Pydantic can be used with any Python-based framework and it supports native JSON encoding and decoding as well. Here, learn how simple it is to adopt Pydantic.
Join the DZone community and get the full member experience.
Join For FreePydantic is a Python library for data modeling/parsing that has efficient error handling and a custom validation mechanism. As of today, Pydantic is used mostly in the FastAPI framework for parsing requests and responses because Pydantic has built-in support for JSON encoding and decoding.
This article covers the following topics:
- Understanding
BaseModelclass Optionalin Pydantic- Validation in Pydantic
- Custom validation
- Email validation using Pydantic optional
email-validatormodule
BaseModel
For data modeling in Pydantic, we need to define a class that inherits from the BaseModel class and fields. Custom validation logic sits in the same model class. Let’s understand by the simple example of JSON parsing. Consider a JSON representing user data.
Input
data = {"id":20, "name":"John", "age":42, "dept":"IT"}
For parsing, first, we need to import BaseModel and declare a class User, which inherits from the BaseModel.
from pydantic import BaseModel
from pprint import print
data = {"id":20, "name":"John", "age":42, "dept":"IT"}
class User(BaseModel):
id: int
name: str
age: int
dept: str
Next, need to instantiate an object from the User class:
user = User(**data)
pprint(user)
Output
User(id=20, name='John', age=42, dept='IT')
Optional in Pydantic
Attributes in the User class can be declared of type Optional. If we are not sure whether any JSON field will be present or not, we can declare that specific type as Optional and if the field is missing, by default, Optional returns None if the attribute is not initialized with a default value. In the example, let’s remove the dept field completely:
from pydantic import BaseModel
from typing import Optional
from pprint import pprint
data = {"id":20, "name":"John", "age":42}
class User(BaseModel):
id: int
name: str
age: int
dept: Optional[str]
user = User(**data)
pprint(user)
Output
The dept field value is None, as it’s missing in the input data.
User(id=20, name='John', age=42, dept=None)
Validation in Pydantic
In Pydantic, to get finer error details, developers need to use try/except block. The error will be of type pydantic.error_wrappers.ValidationError.
In our JSON data, modify the id field to string, and import ValidationError.
Input Data
data = {"id":"default", "name":"John", "age":42}
Program
from pydantic import BaseModel, ValidationError
from typing import Optional
from pprint import pprint
data = {"id":"default", "name":"John", "age":42}
class User(BaseModel):
id: int
name: str
age: int
dept: Optional[str]
try:
user = User(**data)
pprint(user)
except ValidationError as error:
pprint(error)
Error
ValidationError(model='User', errors=[{'loc': ('id',), 'msg': 'value is not a valid integer', 'type': 'type_error.integer'}])
The error can be represented as JSON for better readability:
try:
user = User(**data)
pprint(user)
except ValidationError as error:
print(error.json())
This returns JSON:
[
{
"loc": [
"id"
],
"msg": "value is not a valid integer",
"type": "type_error.integer"
}
]
Custom Validation
Pydantic has useful decorators for custom validation of attributes. Developers need to import the Pydantic validator decorator and write our custom validation logic; for example, raise an error if the length of the name field is less than 3 characters.
Input Data
data = {"id":10, "name":"ab", "age":42}
Program
from pydantic import BaseModel, ValidationError, validator
from typing import Optional
from pprint import pprint
data = {"id":10, "name":"ab", "age":42}
class User(BaseModel):
id: int
name: str
age: int
dept: Optional[str]
@validator('name')
def validate_name(cls, name):
print('Length of Name:', len(name))
if len (name) < 3:
raise ValueError('Name length must be > 3')
return name
try:
user = User(**data)
print(user)
except ValidationError as e:
print(e.json())
Error
[
{
"loc": [
"name"
],
"msg": "Name length must be > 3",
"type": "value_error"
}
]
Email Validation
The reason for covering email validation is that one can utilize the Pydantic custom optional email-validator library. You will need to import validate_email from the email_validator module. Using the @validator decorator, all we need to do is invoke validate_email with the data.
Input Data
data = {"id":20, "name":"Sameer", "age":42, "email":"sameer@abc.com"}
Program
from pydantic import BaseModel, ValidationError, validator, Required
from typing import Optional
from pprint import pprint
from email_validator import validate_email
class User(BaseModel):
id: int
name: str
age: int
dept: Optional[str]
email: str
@validator('name')
def validateName(cls, name):
print('Length of Name:', len(name))
if (len(name) < 3):
raise ValueError('Name length must be > 3')
return name
@validator('email')
def validateEmail(cls, email):
valid_email = validate_email(email)
return valid_email.email
try:
user = User(**data)
pprint(user)
except ValidationError as e:
print(e.json())
Output
User(id=20, name='Sameer', age=42, dept=None, email='sameer@abc.com')
Let’s change the value of email to incorrect email-id:
data = {"id":20, "name":"Sameer", "age":42, "email":"sameer"}
Error
[
{
"loc": [
"email"
],
"msg": "The email address is not valid. It must have exactly one @-sign.",
"type": "value_error.emailsyntax"
}
]
It clearly indicates that the @ sign is missing. After providing the correct email-id, it returns everything in order.
Conclusion
Pydantic can be used with any Python-based framework and it supports native JSON encoding and decoding as well. As we have seen throughout the article, adopting Pydantic is simple, and it has various built-in classes and decorators which help in efficient data modeling, validation, and error handling.
Opinions expressed by DZone contributors are their own.
Comments