Lesson 3 of 5 · 2 min
Pydantic: a contract for data
Pydantic turns a class into a checker. It converts what can safely be converted and rejects the rest with a clear message you can send back to the model.
from pydantic import BaseModel, Field, ValidationError
class Candidate(BaseModel):
name: str
score: int = Field(ge=0, le=100)
skills: list[str]
good = Candidate.model_validate_json('{"name": "Asha", "score": "87", "skills": ["python"]}')
print(good.score + 3)
try:
Candidate.model_validate_json('{"name": "Ravi", "score": 140, "skills": []}')
except ValidationError as e:
print(e.errors()[0]["loc"], e.errors()[0]["msg"])
