Pydantic

Pydantic#

Pydantic is a data validation package for python.

import pydantic

JSON#

To validate a JSON object against a Pydantic model, use the model_validate_json method.

Note it takes str, bytes or bytearray as input. For dictionaries, use the syntax Model(**dictionary).

Check more in model_validate_json section of API reference.


The following cell defines a Pydantic model and its corresponding input.

class MyModel(pydantic.BaseModel):
    a: int
    b: float

inp = '{"a": 10, "b": 3.14}'

The following cell performs validation with model_validate_json method.

MyModel.model_validate_json(inp)
MyModel(a=10, b=3.14)

The following cell shows the validation example of a bytes input.

bytes_inp = inp.encode("utf-8")
print(bytes_inp)
MyModel.model_validate_json(bytes_inp)
b'{"a": 10, "b": 3.14}'
MyModel(a=10, b=3.14)

JSON Schema#

To get json schema from model use BaseModel.model_json_schema method.

Check more in JSON Schema page.


The following cell demonstrates the application of the model_json_schema method to the pydantic model.

from pprint import pprint

class MyModel(pydantic.BaseModel):
    a: int
    b: float

pprint(MyModel.model_json_schema())
{'properties': {'a': {'title': 'A', 'type': 'integer'},
                'b': {'title': 'B', 'type': 'number'}},
 'required': ['a', 'b'],
 'title': 'MyModel',
 'type': 'object'}

Type Adapter#

The pydantic.TypeAdapter allows to deal with some basic python types as if they were Pydantic models.

Check more in:


Consider popular example: the list of pydantic models.

class Model(pydantic.BaseModel):
    value: int

type_adapter = pydantic.TypeAdapter(list[Model])
[{'value': 10}, {'value': 11}]

For example, you might want to validate a basic python structure which attributes correspond to the pydantic model.

type_adapter.validate_python([{"value": 10}, {"value": 22}])
[Model(value=10), Model(value=22)]

In case the value is the wrong type.

try:
    type_adapter.validate_python([{"value": "hello"}])
except Exception as e:
    print(type(e))
    print(e)
<class 'pydantic_core._pydantic_core.ValidationError'>
1 validation error for list[Model]
0.value
  Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='hello', input_type=str]
    For further information visit https://errors.pydantic.dev/2.11/v/int_parsing

Or with the dump_python method you can convert a list of Pydantic model instances into the basic Python structure.

lst_mod = [
    Model(value=10),
    Model(value=11)
]
type_adapter.dump_python(lst_mod)
[{'value': 10}, {'value': 11}]