Skip to main content

1. Why Pydantic?

While Python’s standard type hints and dataclasses help document and organize code, they do not enforce types at runtime. If you pass a string "100" to a dataclass attribute annotated as an integer, Python will allow it without raising any errors. To guarantee that data actually conforms to your types at runtime (e.g., when receiving request payloads from a client), we use Pydantic — the industry standard data validation library.

Dataclasses vs. Pydantic


2. Defining a BaseModel

To define a schema, create a class that inherits from pydantic.BaseModel.

3. Field Constraints (Field)

Use Field to add validation constraints like numeric limits, string length limits, or metadata:

4. Custom Validators (@field_validator)

For complex validation rules, use the @field_validator decorator:

5. Nested Models & Collections

Pydantic handles nested schemas, collections (list, dict, set), and unions (|) seamlessly.

6. Serialization & Deserialization

Pydantic provides easy built-in methods to convert your models back into dictionaries or JSON strings: