Data Validation with Pydantic

Published by Brayan K

Pydantic turns ordinary type hints into a powerful runtime validation engine. Define a model once and Pydantic parses, validates, and coerces messy external data into clean, typed Python objects — or tells you exactly what went wrong.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Validate at the boundary, then work with the parsed model

A JSON object can have the right keys and still contain unusable values. This lesson builds an order boundary: convert compatible input deliberately, reject impossible quantities, and pass a validated model to the rest of the program. A normal Python annotation does not perform these checks; Type Hints & Static Typing with mypy owns annotation basics.

These examples use Pydantic 2.13.4. Install that version in a virtual environment with python -m pip install pydantic==2.13.4. The site’s browser runtime carries Pydantic 1, so examples using the v2 API need local Python. The commands install a dependency; the programs below make no network calls.

from pydantic import BaseModel, Field

class Order(BaseModel):
    product: str
    quantity: int = Field(gt=0)

incoming = {"product": "notebook", "quantity": "3"}
order = Order.model_validate(incoming)
print(order.product, order.quantity)
print(type(order.quantity).__name__)
print(incoming["quantity"] == "3")
print(order.model_dump())

# ✅ Expected output:
# notebook 3
# int
# True
# {'product': 'notebook', 'quantity': 3}

The string quantity is accepted and converted to an integer. The original dictionary stays unchanged in this example. Validation describes the resulting model; it does not promise that every accepted input already had exactly those types. If conversion would hide an input error, ask for strict validation.

Choose coercion, strictness and extra-field policy separately

from pydantic import BaseModel, Field, ValidationError

class Order(BaseModel):
    quantity: int = Field(gt=0)

for payload in [{"quantity": "3"}, {"quantity": 0}]:
    try:
        Order.model_validate(payload, strict=True)
    except ValidationError as problem:
        for issue in problem.errors(include_url=False):
            print(issue["loc"], issue["type"], issue["msg"])

# ✅ Expected output:
# ('quantity',) int_type Input should be a valid integer
# ('quantity',) greater_than Input should be greater than 0

Strict validation rejects the string before it can become an integer. The positive-value constraint is a different rule and rejects zero even though zero has the right type. The displayed messages are taken from the actual ValidationError. Strict mode has type- and input-format-specific behavior; do not assume Python-input and JSON-input acceptance are identical for every date or other specialized type.

from pydantic import BaseModel, ConfigDict, ValidationError

class Order(BaseModel):
    model_config = ConfigDict(extra="forbid")
    quantity: int

try:
    Order.model_validate({"quantity": 2, "quantitty": 9})
except ValidationError as problem:
    issue = problem.errors(include_url=False)[0]
    print(issue["loc"], issue["type"], issue["msg"])

# ✅ Expected output:
# ('quantitty',) extra_forbidden Extra inputs are not permitted

Models ignore unknown fields by default. For a small input contract, extra="forbid" makes a typo visible. Use extra="allow" only when keeping unknown data is intentional. Strictness controls value conversion; extra controls unexpected keys. Neither replaces authorization or an application’s business rules.

Nullable is not the same as optional to supply

from pydantic import BaseModel, ValidationError

class RequiredNote(BaseModel):
    note: str | None

class OptionalNote(BaseModel):
    note: str | None = None

print(RequiredNote.model_validate({"note": None}).note)
print(OptionalNote.model_validate({}).note)
try:
    RequiredNote.model_validate({})
except ValidationError as problem:
    print(problem.errors(include_url=False)[0]["msg"])

# ✅ Expected output:
# None
# None
# Field required

The union allows a stored None. The default allows the key to be absent. This distinction matters in create and update requests: absent can mean “keep the old value,” while explicit None can mean “clear it.” model_fields_set records which fields were explicitly supplied.

from pydantic import BaseModel

class Update(BaseModel):
    note: str | None = None

empty = Update.model_validate({})
clear = Update.model_validate({"note": None})
print(empty.model_dump(exclude_unset=True))
print(clear.model_dump(exclude_unset=True))
print("note" in empty.model_fields_set, "note" in clear.model_fields_set)

# ✅ Expected output:
# {}
# {'note': None}
# False True

Do not use exclude_none as a substitute: it would discard the explicit clearing request too. For defaults that require their own checks, use Field(validate_default=True) or the matching model configuration; defaults are not validated by default.

Normalize a field, then enforce a relationship between fields

from typing import Self
from pydantic import BaseModel, Field, field_validator, model_validator, ValidationError

class Reservation(BaseModel):
    name: str
    seats: int = Field(gt=0)
    capacity: int = Field(gt=0)

    @field_validator("name")
    @classmethod
    def clean_name(cls, value: str) -> str:
        cleaned = value.strip()
        if not cleaned:
            raise ValueError("name must contain a visible character")
        return cleaned

    @model_validator(mode="after")
    def fits(self) -> Self:
        if self.seats > self.capacity:
            raise ValueError("seats exceed capacity")
        return self

ok = Reservation.model_validate({"name": "  Ada  ", "seats": 2, "capacity": 4})
print(ok.name, ok.seats)
for data in [
    {"name": "   ", "seats": 2, "capacity": 4},
    {"name": "Ada", "seats": 5, "capacity": 4},
]:
    try:
        Reservation.model_validate(data)
    except ValidationError as problem:
        print(problem.errors(include_url=False)[0]["msg"])

# ✅ Expected output:
# Ada 2
# Value error, name must contain a visible character
# Value error, seats exceed capacity

The field validator receives an already parsed string and must return the cleaned value. The after-model validator sees the validated fields together and returns the model. Raise ValueError for invalid user data; an accidental TypeError in a validator is a programming error, not automatically a ValidationError in v2. Never use an assert for a required validation rule because optimized Python can remove assertions.

Nested input has a location; serialization has a target format

from pydantic import BaseModel, Field, ValidationError

class Line(BaseModel):
    name: str
    count: int = Field(gt=0)

class Basket(BaseModel):
    lines: list[Line]

try:
    Basket.model_validate({"lines": [{"name": "pen", "count": 2}, {"name": "pad", "count": 0}]})
except ValidationError as problem:
    issue = problem.errors(include_url=False)[0]
    print(issue["loc"])
    print(issue["msg"])

# ✅ Expected output:
# ('lines', 1, 'count')
# Input should be greater than 0

The location identifies the field, list index and inner field, rather than requiring you to parse a long exception string. Keep sensitive submitted values out of public logs: errors can include input data. A model validates shape and rules; it does not sanitize a string for HTML or SQL.

from datetime import date
from pydantic import BaseModel

class Delivery(BaseModel):
    day: date

delivery = Delivery.model_validate({"day": "2026-05-12"})
print(type(delivery.model_dump()["day"]).__name__)
print(delivery.model_dump(mode="json"))
print(delivery.model_dump_json())

# ✅ Expected output:
# date
# {'day': '2026-05-12'}
# {"day":"2026-05-12"}

model_dump normally keeps Python values such as date objects. JSON mode converts supported values to JSON-compatible forms; model_dump_json returns serialized text. Working with JSON owns JSON’s data model and parsing errors.

Validation is not a permanent guard around every mutation

from pydantic import BaseModel, ConfigDict, Field, ValidationError

class Stock(BaseModel):
    model_config = ConfigDict(validate_assignment=True)
    count: int = Field(ge=0)

stock = Stock.model_validate({"count": 3})
try:
    stock.count = -1
except ValidationError as problem:
    print(problem.errors(include_url=False)[0]["msg"])
print(stock.count)

# ✅ Expected output:
# Input should be greater than or equal to 0
# 3

Without validate_assignment, assigning a field later does not run validation. Even with it, mutating a nested list in place is not a field assignment. Prefer validated operations at the boundary of a state change. model_construct skips validation, and model_copy(update=...) trusts its update data: neither is a shortcut for accepting untrusted input.

Complete a strict stock boundary

Reject unknown keys, require a strictly typed positive integer count, and serialize the accepted model. Fill the two blanks with the literal hints. A boolean must not count as stock.

from pydantic import BaseModel, ConfigDict, Field

class Stock(BaseModel):
    model_config = ConfigDict(extra=___)
    count: int = Field(gt=0, strict=___)

print(Stock.model_validate({"count": 4}).model_dump())

# 👉 replace ___ with "forbid"
# 👉 replace ___ with True

# ✅ Expected output:
# {'count': 4}

Build a checked parcel request

Accept a nonempty destination after trimming, a strictly typed positive integer item count, and a nullable note that may be absent. Reject extra keys. Demonstrate a valid request and two invalid requests: a blank destination and a boolean item count. Extract the actual error location and message for each failure.

from pydantic import BaseModel, ConfigDict, Field, field_validator, ValidationError

class Parcel(BaseModel):
    model_config = ConfigDict(extra="forbid")
    destination: str
    items: int = Field(gt=0, strict=True)
    note: str | None = None

    @field_validator("destination")
    @classmethod
    def destination_is_present(cls, value: str) -> str:
        value = value.strip()
        if not value:
            raise ValueError("destination must not be blank")
        return value

print(Parcel.model_validate({"destination": "  Desk A  ", "items": 2}).model_dump())
for payload in [{"destination": " ", "items": 2}, {"destination": "Desk A", "items": True}]:
    try:
        Parcel.model_validate(payload)
    except ValidationError as problem:
        issue = problem.errors(include_url=False)[0]
        print(issue["loc"], issue["msg"])

# ✅ Expected output:
# {'destination': 'Desk A', 'items': 2, 'note': None}
# ('destination',) Value error, destination must not be blank
# ('items',) Input should be a valid integer

A successful model is only this input contract. It does not prove that the destination exists or that the caller may ship there. Keep those decisions in the application layer and test them separately.

Practice quiz

What does this program print? from pydantic import BaseModel class Item(BaseModel): count: int item = Item.model_validate({"count": "4"}) print(item.count, type(item.count).__name__)

  • 4 int
  • 4 str
  • ValidationError
  • None NoneType

Answer: 4 int. Default validation converts this numeric string to int.

What does extra="forbid" control?

  • Whether int strings are converted
  • Whether unexpected keys are rejected
  • Whether fields can be reassigned
  • Whether JSON may contain null

Answer: Whether unexpected keys are rejected. Extra-field handling and strict value validation are separate policies.

What does this program print? from pydantic import BaseModel class Change(BaseModel): note: str | None = None print(Change.model_validate({}).model_dump(exclude_unset=True))

  • {"note": None}
  • None
  • {}
  • ValidationError

Answer: {}. exclude_unset omits fields that were not supplied.

Which annotation requires a field while allowing None?

  • note: str = ""
  • note: str | None = None
  • note: str = None
  • note: str | None

Answer: note: str | None. A nullable union has no implicit default in Pydantic v2.

Which method returns JSON text?

  • model_dump_json()
  • model_dump()
  • model_fields_set
  • model_construct()

Answer: model_dump_json(). model_dump_json serializes the model to a string.

What must an after field validator return?

  • A new model class
  • The accepted or normalized field value
  • A ValidationError instance
  • Nothing

Answer: The accepted or normalized field value. Returning the value passes it to the model. Raise an appropriate exception when invalid.

What is unsafe about model_copy(update=untrusted_data)?

  • It always deletes the original
  • It always converts strings to bytes
  • Its update data is not validated
  • It cannot copy models

Answer: Its update data is not validated. Do not use a trusted update shortcut as an untrusted-data boundary.

What does validate_assignment=True fail to guard automatically?

  • Assigning a negative constrained integer
  • Reassigning a string field
  • A direct checked field assignment
  • Appending an invalid item to an existing nested list

Answer: Appending an invalid item to an existing nested list. An in-place list mutation is not reassignment of the model field.

Continue this course

Related lessons