Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 50 ยท Pydantic models and validation

Pydantic models for APIs

Learn how Pydantic v2 models describe API data in FastAPI: types, defaults, optional fields, model_dump, model_validate, JSON Schema, and coercion vs strict mode.

Every FastAPI request body and response is described by a Pydantic model. A model is a plain Python class whose attributes have type hints. Pydantic reads those hints, checks incoming data against them, converts what it can, and gives you a clean object, or a precise list of errors when the data is wrong.

You met models briefly in request bodies. This lesson is about the models themselves, without the web layer: what they accept, what they refuse, how to turn them back into dictionaries and JSON, and how FastAPI gets its OpenAPI documentation out of them. Everything here is Pydantic v2, the version FastAPI uses today.

What a model does

Describe Fields and types are declared as class attributes.
Validate Bad input raises a ValidationError.
Convert '42' becomes 42 when the type says int.
Export Dicts, JSON and JSON Schema come for free.

FastAPI wires all four into HTTP for you.

1 / 2

Declaring a model

Inherit from BaseModel and annotate attributes. A field without a default is required; a field with a default is optional for the caller.

Python A first model

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.

Pydantic collects all the problems in one go, so an API can tell the client everything that is wrong with a single request. Each entry has a loc (where the problem is), a machine-readable type and a human msg. That is exactly the structure behind FastAPI's 422 responses.

The tags: list[str] = [] default looks like the classic mutable-default bug, but Pydantic copies defaults for each instance, so every product gets its own list. For anything computed, use Field(default_factory=...), which you'll meet in field constraints.

Optional, nullable and defaults

Three different ideas hide behind "optional", and mixing them up causes real bugs:

Declaration Required? None allowed?
name: str yes no
name: str = "x" no no
name: str | None yes yes
name: str | None = None no yes

The third row surprises people coming from Pydantic v1: in v2, str | None without a default is required; the caller must send the key, even if the value is null. Add = None when the field may be left out.

Python Required, defaulted and nullable fields

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.

Look at the second input: nickname has no default, so omitting it is an error even though None is a legal value.

Coercion: what Pydantic converts

By default Pydantic runs in lax mode. It converts values when the conversion is unambiguous: the string "42" becomes the integer 42, "true" and 1 become True, an ISO date string becomes a date, and an integer 3 is fine for a float. This matches how data actually arrives over HTTP, where query strings and form fields are always text.

It still refuses nonsense, and some "obvious" conversions: "4.5" is not an int, and 3.7 is not silently truncated to 3.

Strict mode turns coercion off, so only the exact type passes. You can switch it on for one model with ConfigDict(strict=True), or for one field with Field(strict=True).

Python Lax vs strict

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.

For public APIs lax mode is usually the friendly choice. Reach for strict mode where a silent conversion would hide a client bug, for example money amounts or identifiers.

JSON bodies keep their types: {"count": 42} is already an integer. Coercion matters most for query strings, path parameters, headers and sloppy clients that send numbers as strings.

Turning models back into data

Models are not just input checkers; they are also how you produce output.

  • model_dump() returns a plain dict (nested models become dicts too).
  • model_dump_json() returns a JSON str.
  • model_validate(data) builds a model from a dict (like Product(**data), but it also accepts other objects with from_attributes=True).
  • model_validate_json(text) parses and validates a JSON string in one step.
  • model_copy(update={...}) makes a modified copy without re-validating.

Instances are mutable, but assignment is not validated unless you set validate_assignment=True in the config.

Python Dump, validate and copy

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.

mode="json" matters: plain model_dump() keeps a real date object, while mode="json" converts it to the string "2024-05-01". Notice the error locations for nested data, such as ('address', 'zip_code'): they are tuples that walk down the structure. FastAPI prefixes them with body.

JSON Schema and the docs

Because every field has a type, Pydantic can describe the model as JSON Schema with Model.model_json_schema(). FastAPI embeds that schema in /openapi.json, and Swagger UI draws its forms and examples from it. You never write the documentation by hand, and it can't drift away from the code.

Python The schema behind the docs

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.

Only title is listed as required, because the other fields have defaults. You will see the same schema appear under components in the OpenAPI document in response classes and OpenAPI docs.

Models in a FastAPI route

Putting a model in a function signature is all it takes. FastAPI parses the JSON body, validates it with the model, and hands your function a ready object. Invalid data never reaches your code.

Python A model as a request body

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 the string "2" for priority was accepted and converted, while the missing title and the impossible boolean were reported together.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In Pydantic v2, what does a field declared as nickname: str | None (no default) mean?

    Without a default the field is required. The | None only widens the allowed values. Write str | None = None to make it optional.
  2. 2. Which call turns a model, including a date field, into a dict containing only JSON-compatible values?

    mode="json" converts dates, UUIDs and similar types to strings. The default mode keeps the Python objects.
  3. 3. With the default lax mode, what happens to the input "42" for a field typed int?

    Lax mode converts unambiguous values. Strict mode would reject the string.
  4. 4. How does FastAPI know what to put in the documentation for a request body?

    Pydantic generates JSON Schema from the type hints and FastAPI embeds it in the OpenAPI document.

Summary

  • A BaseModel declares fields with type hints; required fields have no default.
  • X | None allows null, but only = None makes the field optional.
  • Lax mode coerces unambiguous values ("42" to 42); strict mode refuses them.
  • model_dump, model_dump_json, model_validate, model_validate_json and model_copy move data in and out.
  • Validation errors list every problem with loc, type and msg, and model_json_schema() feeds the OpenAPI docs.

Next: add limits and custom rules in field constraints and validators.