DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • JSON-Based Serialized LOB Pattern
  • Pydantic: Simplifying Data Validation in Python
  • How to Simplify Complex Conditions With Python's Match Statement
  • Modify JSON Data in Postgres and Hibernate 6

Trending

  • Introduction to Retrieval Augmented Generation (RAG)
  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • IoT and Cybersecurity: Addressing Data Privacy and Security Challenges
  • How GitHub Copilot Helps You Write More Secure Code
  1. DZone
  2. Data Engineering
  3. Data
  4. What Is Pydantic?

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.

By 
Sameer Shukla user avatar
Sameer Shukla
DZone Core CORE ·
Aug. 15, 22 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
25.5K Views

Join the DZone community and get the full member experience.

Join For Free

Pydantic 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 BaseModel class 
  • Optional in Pydantic
  • Validation in Pydantic
  • Custom validation 
  • Email validation using Pydantic optional email-validator module 

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.

Python
 
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:

Python
 
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:

Python
 
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

Python
 
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:

Python
 
try:

    user = User(**data)

    pprint(user)

except ValidationError as error:

    print(error.json())


This returns JSON:

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

Python
 
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

JSON
 
[

  {

    "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

Python
 
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

JSON
 
[

  {

    "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.

Data modeling IT JSON Typing Attribute (computing) Data (computing) Id (programming language) LESS Python (language) Data Types

Opinions expressed by DZone contributors are their own.

Related

  • JSON-Based Serialized LOB Pattern
  • Pydantic: Simplifying Data Validation in Python
  • How to Simplify Complex Conditions With Python's Match Statement
  • Modify JSON Data in Postgres and Hibernate 6

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!