BaseModel: conversion, errors and parsing
Pydantic runs in your browser. The error "type" strings are stable codes; the "msg" text can change slightly between Pydantic versions.
Pydantic turns type hints into real checks: you describe the shape of your data as a class, and it converts and validates incoming dictionaries or JSON, collects clear errors, and can produce a JSON Schema. FastAPI, the AI SDKs and agent frameworks are built on it.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Create a model Product with name (non-empty text), price (a number above 0) and in_stock (boolean defaulting to True). Show that Product(name="Pen", price="2.5") works.
Show the error loc and type when price is -1.
Add a validator so name is stored with the first letter capitalised and surrounding spaces removed.
Explain it without notes
What does Pydantic do that type hints alone do not?
What does a ValidationError contain, and why is that useful?
How do you add a rule that built-in constraints cannot express?
Why is model_json_schema() important for AI applications?
What is the difference between lax and strict mode, and is a Pydantic object always valid?
Expected output
id=7 name='Asha' email=None tags=[]
id is int
{'id': 7, 'name': 'Asha', 'email': None, 'tags': []}
{"id":7,"name":"Asha","email":null,"tags":[]}
error count: 3
('id',) | int_parsing | Input should be a valid integer, unable to parse string as an integer
('name',) | string_type | Input should be a valid string
('tags',) | list_type | Input should be a valid list
id=9 name='Ben' email=None tags=[]
id=10 name='Cy' email=None tags=['a']