Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 38 ยท Getting Started

Your First Pydantic Model

Create a Pydantic BaseModel, set field types, defaults and required fields, read attributes, validate dicts and JSON, and understand how models behave like objects.

A Pydantic model is a class that describes a piece of data. You write the field names and their types, and Pydantic builds the rest: an __init__ that validates, a readable repr, equality, and methods to convert to and from dictionaries and JSON. In this lesson you will build and use a model from scratch.

Declaring a model

Inherit from BaseModel and add annotated attributes:

Python A model with defaults

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The rules are simple:

  • A field with no default is required.
  • A field with a default (= True) is optional; if you leave it out, the default is used.
  • Attributes are read with a dot, like any object: book.title.
  • Field order follows the order in the class body.

Pydantic models only accept keyword arguments. Book("Dune", "Frank Herbert", 412) raises an error because positional arguments are ambiguous.

Three ways to create a model

Way Use it when
Book(title="Dune", ...) you have the values as separate keywords
Book(**data) you have a dict and trust it has only known keys
Book.model_validate(data) you have a dict (or an object) of untrusted input; the clearest choice
Book.model_validate_json(text) you have raw JSON text
Python Dicts and JSON text

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

model_validate_json parses the JSON text and validates it in a single step, inside the Rust core. It is faster than json.loads followed by model_validate, and it gives better error messages that point into the JSON.

Models are real classes

Because a model is a normal class, you can add methods and properties:

Python Adding behaviour

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that width=3 was an int, but the field is float, so Pydantic stored 3.0. Plain methods and properties are never treated as fields: only annotated class attributes are.

An attribute without an annotation, such as colour = "red", is not a field. Pydantic v2 raises an error for it, because it is almost always a forgotten annotation. Write colour: str = "red".

Changing values

By default models are mutable and assignments are not validated:

Python Assignment is not checked by default

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Turn on validate_assignment=True when you want every change checked. For values that should never change, use a frozen model: ConfigDict(frozen=True) makes instances immutable and hashable. You will learn more about configuration in Models and Types.

Useful built-in members

Every model comes with a small, consistently named API. All methods start with model_ so they never clash with your field names.

Member What it does
model_validate(obj) build a model from a dict or object
model_validate_json(text) build a model from JSON text
model_dump() convert to a plain dict
model_dump_json() convert to a JSON string
model_copy(update={...}) make a copy with changes
model_fields information about the fields (a class attribute)
model_fields_set which fields were explicitly provided
Python Peeking at the built-ins

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

model_copy(update=...) does not validate the new values. Use it with trusted data, or rebuild the model with model_validate if you want checks.

Pydantic v1 names

Older tutorials use .dict(), .json(), .parse_obj() and .copy(). Those still exist in v2 but are deprecated and print a warning. Prefer the model_* names shown above. The next lesson explains what happens during validation.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A model field is declared as nickname: str. What happens if you create the model without a nickname?

    A field with no default is required. Leaving it out raises a ValidationError with type=missing.
  2. 2. Which call is best for building a model from untrusted JSON text?

    model_validate_json parses and validates in one step, quickly, with errors that point into the JSON.
  3. 3. By default, what happens when you assign a wrong-typed value to an existing field (instance.count = 'abc')?

    Validation runs on creation only. Set validate_assignment=True in the model config to check assignments.
  4. 4. Why do all built-in Pydantic methods start with model_?

    The model_ prefix is a reserved namespace, which keeps built-in names separate from your field names.

Summary

  • A model is a class inheriting BaseModel with annotated attributes; fields without a default are required.
  • Create instances with keywords, model_validate(dict) or model_validate_json(text).
  • Models can have methods and properties; only annotated attributes are fields.
  • Assignments are not validated unless you set validate_assignment=True; frozen=True makes a model immutable.
  • Use model_dump, model_dump_json, model_copy and model_fields instead of the deprecated v1 names.

Next: How Validation Works