Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 15.4 — Data Validation with Pydantic
Python · Example 1 of 2

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.

01

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.

02

Show the error loc and type when price is -1.

03

Add a validator so name is stored with the first letter capitalised and surrounding spaces removed.

Explain it without notes

01

What does Pydantic do that type hints alone do not?

02

What does a ValidationError contain, and why is that useful?

03

How do you add a rule that built-in constraints cannot express?

04

Why is model_json_schema() important for AI applications?

05

What is the difference between lax and strict mode, and is a Pydantic object always valid?

BaseModel: conversion, errors and parsing
Sign in to run this example in your browser.

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']