FastAPI - Pydantic



Pydantic is a Python library for data parsing and validation. It uses the type hinting mechanism of the newer versions of Python (version 3.6 onwards) and validates the types during the runtime. Pydantic defines BaseModel class. It acts as the base class for creating user defined models.

Following code defines a Student class as a model based on BaseModel.

from typing import List
from pydantic import BaseModel
class Student(BaseModel):
   id: int
   name :str
   subjects: List[str] = []

The attributes of the Student class are declared with type hints. Note that the subjects attribute is of List type defined in typing module and of builtin list type.

Example - Usage of Pydantic

We can populate an object of Student class with a model_dump with matching structure as follows −

main.py

from typing import List
from pydantic import BaseModel

class Student(BaseModel):
   id: int
   name :str
   subjects: List[str] = []
   
data = {
   'id': 1,
   'name': 'Ravikumar',
   'subjects': ["Eng", "Maths", "Sci"],
}

s1=Student(**data)

print(s1)

print(s1.model_dump())

Output

Run the code and verify the output.

id=1 name='Ravikumar' subjects=['Eng', 'Maths', 'Sci']
{'id': 1, 'name': 'Ravikumar', 'subjects': ['Eng', 'Maths', 'Sci']}

Example - Error in case Conversion is not feasible

Pydantic will automatically get the data types converted whenever possible. For example, even if the id key in the dictionary is assigned a string representation of a number (such as '123'), it will coerce it into an integer. But whenever not possible, an exception will be raised.

main.py

from typing import List
from pydantic import BaseModel

class Student(BaseModel):
   id: int
   name :str
   subjects: List[str] = []
   
data = {
   'id': 1,
   'name': 'Ravikumar',
   'subjects': ["Eng", "Maths", "Sci"],
}

s1=Student(**data)

Output

Run the code and verify the output.

Traceback (most recent call last):
  File "D:\Projects\python\myenv\main.py", line 15, in 
    s1=Student(**data)
  File "D:\Projects\python\myenv\Lib\site-packages\pydantic\main.py", line 250, in __init__
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
pydantic_core._pydantic_core.ValidationError: 1 validation error for Student
id
  Input should be a valid integer [type=int_type, input_value=[1, 2], input_type=list]
    For further information visit https://errors.pydantic.dev/2.12/v/int_type

Example - Validation Error

Pydantic also contains a Field class to declare metadata and validation rules for the model attributes. First modify the Student class to apply Field type on "name" attribute as follows −

from typing import List
from pydantic import BaseModel, Field

class Student(BaseModel):
   id: int
   name :str = Field(None, title="The description of the item", max_length=10)
   subjects: List[str] = []

Populate the data as shown below. The name here is exceeding the max_length stipulated. Pydantic throws ValidationError as expected.

main.py

from typing import List
from pydantic import BaseModel, Field

class Student(BaseModel):
   id: int
   name :str = Field(None, title="The description of the item", max_length=10)
   subjects: List[str] = []
   
data = {
   'id': 1,
   'name': 'Ravikumar Sharma',
   'subjects': ["Eng", "Maths", "Sci"],
}
s1=Student(**data)

Output

Run the code and verify the output.

Traceback (most recent call last):
  File "D:\Projects\python\myenv\main.py", line 14, in 
    s1=Student(**data)
  File "D:\Projects\python\myenv\Lib\site-packages\pydantic\main.py", line 250, in __init__
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
pydantic_core._pydantic_core.ValidationError: 1 validation error for Student
name
  String should have at most 10 characters [type=string_too_long, input_value='Ravikumar Sharma', input_type=str]
    For further information visit https://errors.pydantic.dev/2.12/v/string_too_long

Pydantic models can be used to map with ORM models like SQLAlchemy or Peewee.

Advertisements