Validations in Pydantic V2

Validating with Field, Annotated, field validator, and model validator

Photo by Max Di Capua on Unsplash

Pydantic is the data validation library for Python, integrating seamlessly with FastAPI, classes, data classes, and functions. Data validation refers to the validation of input fields to be the appropriate data types (and performing data conversions automatically in non-strict modes), to impose simple numeric or character limits for input fields, or even impose custom and complex constraints.

With larger classes and more fields to perform validation on, and with validations being able to process and modify the raw inputs, it is important to know the different types of validators, and their order of precedence in execution.

This article will discuss the different types of validation that Pydantic offers and the order of precedence of the different types of validation with code examples, which are not covered in great detail in Pydantic’s documentation. The focus will be on the validation of classes, also referred to as BaseModel.

Table of Contents