Pydantic Tutorial by example | The Dev Tool | Toolel.com

Pydantic library is a tool to work with data validation and parsing. Basically, it uses type annotations for validation and provides user-friendly errors when data is invalid. It's one of the best data serialization and validation libraries you can use for development. FastAPI - a high-performance web framework has Pydantic as a required dependency.

You can find the Pydantic on the Github link and for the documentation here.

Installing Pydantic

It can be easily installed with:

pip install pydantic

The library supports Python 3.7+.

Simple example of use

In the example below we have created a basic model "Employee" which is just a class that inherits from the BaseModel of Pydantic. The model properties are declared with type annotations that will be used for data validation and conversion. All fields except id are optional and have their default values. If we don't pass id into the external_data dict or pass some argument of wrong type there will occur validation error with a detailed explanation of issue. It's possible to use any type annotations including datetime, enum and custom types.

from datetime import date
from typing import Optional

from pydantic import BaseModel


class Employee(BaseModel):
    id: int
    name: str = ""
    age: Optional[int] = None
    join_date: Optional[date] = None


external_data = {
    'id': 1,
    'name': 'Kate Doe',
    'age': 28,
    'join_date': '2022-05-01',
}

employee = Employee(**external_data)
print(employee.id)
#> 1

print(employee.name)
#> Kate Doe

print(repr(employee.join_date))
#> datetime.date(2022, 5, 1)

print(employee.age)
#> 28

print(employee.dict())
"""
{
    'id': 1,
    'name': 'Kate Doe',
    'age': 28,
    'join_date': datetime.date(2022, 5, 1)
}
"""

Example of validation error handling

(This code requires the previous example)

from pydantic import ValidationError

try:
    employee = Employee(id='not number', name='Kate Doe')
except ValidationError as e:
    print(e.json())

#>

"""
  {
    "loc": [
      "id"
    ],
    "msg": "value is not a valid integer",
    "type": "type_error.integer"
  }
"""

Pydantic provides nice breakdown of what was wrong, but also it's possible to create own custom validators and return your error messages.

Optional fields

In Pydantic you can make any field optional using an Optional type hint from the Python's typing module or by setting a default value. All fields in the Pydantic data model are "required" by default.

Pydantic model to dict

It’s possible to convert your Pydantic data model to dict. All you need is to call dict() method of your model object. Moreover, there is a row of arguments that can be passed to the method, such as include, exclude and others.

from typing import Optional
from pydantic import BaseModel


class Employee(BaseModel):
   id: int = 1
   name: str = ""
   age: Optional[int]


default_employee = Employee()
employee_1 = Employee(id=1, name='Kate', age=21)


print('default employee -> ', default_employee.dict())
#> default employee ->  {'id': 1, 'name': '', 'age': None}

print('employee 1 -> ', employee_1.dict())
#> employee 1 ->  {'id': 1, 'name': 'Kate', 'age': 21}

print('employee without id -> ',  employee_1.dict(exclude={'id'}))
#> employee without id ->  {'name': 'Kate', 'age': 21}

Pydantic model to json

It's also possible to use json() method to return a JSON string representation dictionary.

Pydantic schema

Pydantic model can easily be represented as JSON shema. There is schema() method for this, it returns schema as a dict, but schema_json() returns it as a json string.

Created by: Kristina

Comments

This page is only partially working without JavaScript. It will show content, but the tools and interactivity cannot be shown without JavaScript enabled. Please enable JavaScript for this page. About Us