Data Validation with Pydantic

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.

Learn Data Validation with Pydantic in our free Python course — an interactive lesson with runnable examples, a practice exercise and a quick reference.

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.

What You'll Learn in This Lesson

Real data is messy: missing keys, strings where numbers belong, extra fields. Pydantic validates it at runtime so the rest of your code can trust it.

You describe the shape of your data with normal Python type hints, and Pydantic enforces it.

Notice that "42" became the integer 42 — Pydantic coerces compatible types by default.

When data does not fit, Pydantic raises ValidationError :

The error object lists every failing field, the bad value, and why it failed.

Use Field() to add bounds, defaults, and metadata:

For rules that constraints cannot express, use @field_validator (Pydantic v2):

Validators can also transform values (here we lowercased the username).

Models can contain other models, validated recursively:

The inner dict was validated and turned into a real Address instance.

Pydantic's settings classes load configuration from environment variables, with validation:

Use a dataclass for simple in-memory records; use Pydantic when data crosses a boundary and must be validated.

✔ Validate external data with plain type hints

✔ Coerce and clean messy inputs automatically

Define the shape once, and trust your data everywhere after.

📋 Quick Reference — Pydantic

You can now model and validate real-world data with confidence using Pydantic.

Up next: NumPy — fast numerical computing with arrays and vectorized operations.

Practice quiz

What base class do you inherit from to define a Pydantic model?

  • BaseModel
  • DataModel
  • Schema
  • Validator

Answer: BaseModel. Pydantic models subclass pydantic.BaseModel, which drives validation, parsing, and serialization.

How does Pydantic decide what to validate on each field?

  • From a separate schema file
  • From method names
  • From the field's type annotation
  • From docstrings

Answer: From the field's type annotation. Pydantic reads the standard type annotations (name: str, age: int) and validates incoming data against them.

If you pass the string '42' to an int field in a Pydantic v2 model, what happens by default?

  • It raises ValidationError immediately
  • It is coerced to the integer 42
  • It stays as the string '42'
  • The field is set to None

Answer: It is coerced to the integer 42. By default Pydantic coerces compatible types, so '42' becomes the int 42. Use strict mode to forbid this.

Which exception does Pydantic raise when input data fails validation?

  • AssertionError
  • TypeError
  • ValueError
  • ValidationError

Answer: ValidationError. Pydantic raises pydantic.ValidationError, which collects every field error in one structured report.

Which helper adds constraints like a minimum value or max length to a field?

  • Field()
  • Constraint()
  • Validate()
  • Rule()

Answer: Field(). Field() lets you set constraints such as gt, ge, lt, le, min_length, max_length, and a default value.

In Pydantic v2, which decorator defines a custom validator for one or more fields?

  • @constraint
  • @field_validator
  • @validator
  • @check

Answer: @field_validator. Pydantic v2 uses @field_validator (the v1 @validator is deprecated) to run custom validation logic on fields.

What does the Pydantic v2 method model_dump() return?

  • A new model instance
  • The model's schema
  • A JSON string
  • A dict of the model's data

Answer: A dict of the model's data. model_dump() serializes the model into a plain dict; model_dump_json() produces a JSON string.

Which classmethod validates a dict (or object) into a model instance in Pydantic v2?

  • model_load()
  • model_build()
  • model_validate()
  • model_parse()

Answer: model_validate(). model_validate() takes external data and returns a validated model instance, replacing v1's parse_obj().

How do you model a field that itself contains another structured object?

  • Use a dict type only
  • Annotate the field with another BaseModel subclass
  • Use a tuple
  • It is not supported

Answer: Annotate the field with another BaseModel subclass. Nested models are just fields annotated with another BaseModel subclass; Pydantic validates them recursively.

Compared with a plain dataclass, what does Pydantic add automatically?

  • Runtime data validation and type coercion
  • Faster attribute access
  • Nothing, they are identical
  • Only a __repr__

Answer: Runtime data validation and type coercion. Dataclasses just store fields; Pydantic validates and coerces incoming data at runtime against the annotations.