TECHNOLOGIESTieInn Technologies

Data shapes with Pydantic: validate what comes in and goes out

Python for AI Apps · 10 questions

Short notes

Key idea

Pydantic models describe the shape of data and validate it: types are checked and converted, missing fields raise clear errors. Use them wherever data enters or leaves your app, including model output.

Syntax

from pydantic import BaseModel, Field, ValidationError

class Order(BaseModel):
    order_id: int
    amount: float = Field(gt=0)
    city: str | None = None
    tags: list[str] = []

o = Order.model_validate({"order_id": "17", "amount": 499})
o.model_dump()                 # back to a dict
Order.model_validate_json(text)
Order.model_json_schema()      # JSON schema for an LLM or API docs

Example

Order.model_validate({"order_id": "abc", "amount": -5}) raises a ValidationError listing both problems: order_id isn't an integer and amount must be greater than 0.

Traps

  • Pydantic converts compatible types ("17" → 17) by default; use strict mode if that's not wanted.
  • Catch ValidationError and decide what to do; don't let it crash a request.
  • Pydantic v1 and v2 differ: v2 uses model_validate and model_dump.
  • Lists as defaults are safe in Pydantic, unlike plain classes.

Want the full lesson with step-by-step examples, a project and a certificate? Python for AI Apps course, ₹180 →

Questions

Open in Code Lab5 free questions
5 questions

    Data shapes with Pydantic: validate what comes in and goes out

  1. Question 1easy

    What does this print?

    from pydantic import BaseModel
    class Order(BaseModel):
        order_id: int
    o = Order(order_id="57")
    print(o.order_id + 1)
  2. Data shapes with Pydantic: validate what comes in and goes out

  3. Question 2medium

    What does this print?

    from typing import Optional
    from pydantic import BaseModel
    class Ticket(BaseModel):
        message: str
        category: str = "other"
        order_id: Optional[int] = None
    t = Ticket(message="Hi")
    print(t.category, t.order_id)
  4. Data shapes with Pydantic: validate what comes in and goes out

  5. Question 3medium

    What does this print?

    from pydantic import BaseModel, Field, ValidationError
    class Item(BaseModel):
        quantity: int = Field(ge=1, le=10)
    results = []
    for q in [0, 1, 10, 11]:
        try:
            Item(quantity=q)
            results.append("ok")
        except ValidationError:
            results.append("bad")
    print(results)
  6. Data shapes with Pydantic: validate what comes in and goes out

  7. Question 4medium

    How many errors are reported?

    from pydantic import BaseModel, ValidationError
    class Order(BaseModel):
        order_id: int
        status: str
        amount: float
    try:
        Order(order_id="abc", amount="free")
    except ValidationError as e:
        print(e.error_count())
  8. Data shapes with Pydantic: validate what comes in and goes out

  9. Question 5hard

    Validate every row of product_reviews[["review_id", "rating", "review_text"]] against a model with review_id (int), rating (int from 1 to 5) and review_text (str of at least 10 characters). Store the number of rows that fail in result.

    The tables are ready as DataFrames with the same names. Store your answer in result.

    Tables

5 more questions on this topic, with hints, and tests

Sign up free for 21 days of every question and test.