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:
TypeAdapter concept.
TypeAdapter API reference.
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}]
Alias#
In the pydantic model, you can specify the aliases for attributes. An alias is an alternative name/path for an attribute in the data structure that the model is designed to consume.
The most usefull features are:
pydantic.AliasChoices: allows to specify several possible aliaces for the same attribute.pydantic.AliasPath: should be used if the value of the attribute is under nested structure.
Check more in the Alias page of the official documentation.
The following cell defines the pydantic model that have attributes with different aliaces.
class Model(pydantic.BaseModel):
some_attribute: int = pydantic.Field(
default=None,
alias="SomeAttribute",
)
choices_alias: int = pydantic.Field(
default=None,
alias=pydantic.AliasChoices("option1", "option2")
)
path_alias: int = pydantic.Field(
default=None,
alias=pydantic.AliasPath("outer", "nested")
)
Default alias, allows to consume the attribute with arbitrary name.
Model.model_validate({"SomeAttribute": 10})
Model(some_attribute=10, choices_alias=None)
The pydantic.AliasChoices enables different input attributes to be consumed as the same model attribute.
Model.model_validate({"option1": 3}), Model.model_validate({"option2": 10})
(Model(some_attribute=None, choices_alias=3, path_alias=None),
Model(some_attribute=None, choices_alias=10, path_alias=None))
The pydantic.AliasPath allows to consume nested attributes to be consumed by a flat Pydantic model.
Model.model_validate({"outer": {"nested": 5}})
Model(some_attribute=None, choices_alias=None, path_alias=5)