Pydantic is python library for data validation and parsing. It provides classes and API to validate, serialize, de-serialize class attributes. It’s similar to python dataclass.

Models Link to heading

One of the primary ways of defining schema in Pydantic is via models. Models are simply classes which inherit from pydantic.BaseModel and define fields as annotated attributes.

from typing import List, Optional
from pydantic import BaseModel


class Model(BaseModel):
    v: str
    id : int = 0
    size: Optional[float] = None
    bars: List[int]


m = Model(v="hello", bars=[1,2])
print(m)

v=‘hello’ id=0

There are super useful APIs.

In [15]: m.model_dump()
Out[15]: {'v': 'hello', 'id': 0, 'size': None, 'bars': [1, 2]}

In [17]: m.model_dump_json()
Out[17]: '{"v":"hello","id":0,"size":null,"bars":[1,2]}'

In [16]: m.model_json_schema()
Out[16]:
{'properties': {'v': {'title': 'V', 'type': 'string'},
  'id': {'default': 0, 'title': 'Id', 'type': 'integer'},
  'size': {'anyOf': [{'type': 'number'}, {'type': 'null'}],
   'default': None,
   'title': 'Size'},
  'bars': {'items': {'type': 'integer'}, 'title': 'Bars', 'type': 'array'}},
 'required': ['v', 'bars'],
 'title': 'Model',
 'type': 'object'}