The previous article explained how to validate data using a regular python class, then using dataclass, and the benefit of using it.
Now I will explain validation using pydantic; its documentation can be found at the following link
Pydantic is a data validation and settings management tool that uses type annotations in Python. It can be used with Python from version 3.6 onward.
To install pydantic, use pip:
pip install pydantic
Pydantic vs Dataclasses vs regular python class
Regular python class
As explained in the previous article, the attributes of the class are defined, in this case producto:
class Producto():
def __init__(self, titulo, descripcion, precio, publicado, id):
self.titulo = titulo
self.descripcion = descripcion
self.precio = precio
self.publicado = publicado
self.id = id
Python dataclass
from dataclasses import dataclass
@dataclass
class Producto:
titulo: str
descripcion: str
precio: int
publicado: bool
id: int
Pydantic
In the case of pydantic, BaseModel is imported from pydantic and Optional from typing.
from pydantic import BaseModel
from typing import Optional
from random import randrange
class Producto(BaseModel):
titulo: str
descripcion: str
precio: int
publicado: Optional[bool]= True
id: Optional[int]= None
Unlike dataclass, with pydantic you can define whether a field is optional or not, and its default value. In the case of the field publicado it is a boolean, optional, with True as the default value; in the case of id it is an optional integer, with None as the default value.
Define an example data point:
dato = {
"titulo": "Xiaomi Mi 10T",
"descripcion": "Xiaomi",
"precio": 300,
"id": randrange(0, 100000000)
}
Validate the data with the Producto class and print the content:
producto = Producto(**dato)
print(producto)
titulo='Xiaomi Mi 10T' descripcion='Xiaomi' precio=300 publicado=True id=59872935
Pydantic gives more versatility in data validation; thanks to Pydantic you can validate the data inputs of an API endpoint, and the next article will explain how to do it using FastAPI.
This article is based on the following articles:
- Getting started with Pydantic, a Python data validation library (broken link)
- Pydantic — Better Data Validation for Python (broken link)
- Pydantic documentation
Make a donation! If you liked this article you can donate with Bitcoin (BTC) using the digital wallet of your choice to the following address: 17MtNybhdkA9GV3UNS6BTwPcuhjXoPrSzV
Or by scanning the QR code from your wallet:
