Search⌘ K
AI Features

Validating with Pydantic

Explore how to use Pydantic to define clear data models that validate AI-generated outputs automatically. Understand enforcing types, constraints, enums, and defaults to prevent runtime errors and ensure trustworthy backend data handling.

The previous lesson ended with a specific failure: a dictionary that parsed successfully but contained an invalid type in a field that downstream code depended on. We could keep writing manual if checks for every field, type, and allowed value, but that quickly becomes difficult to maintain, and individual validation checks can be missed as the schema grows. Pydantic provides a cleaner way to handle this validation: define the expected fields, types, and constraints in a model, then validate incoming data against those rules instead of scattering manual checks throughout the codebase.

A Pydantic model is a written contract, enforced automatically

Let's define the exact shape we want the model's output to match: the same severity and reason fields from the last two lessons, but this time as a real, enforced schema instead of a plain dictionary we hope is correct.

Python
from pydantic import BaseModel, Field, ValidationError
class SeverityAssessment(BaseModel):
severity: int = Field(ge=1, le=5)
reason: str
raw_json = '{"severity": 4, "reason": "Affects checkout for many users."}'
assessment = SeverityAssessment.model_validate_json(raw_json)
print("Parsed and validated:", assessment)
print("Type of severity:", type(assessment.severity).__name__)
  • Lines 4–6: SeverityAssessment is a class, not a dictionary shape described in a comment, severity and reason are declared with real Python types, and Field(ge=1, le=5) adds a constraint directly onto severity: it must be an integer greater than or equal to 1 and less than or equal to 5. ge and ...