Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 38 ยท Serialization

JSON Schema Generation

Generate JSON Schema from Pydantic models with model_json_schema, read $defs and required, add titles and examples, use json_schema_extra and understand modes and use cases.

JSON Schema is a standard way to describe the shape of JSON: which keys exist, their types, which are required, and what limits apply. Pydantic can generate a schema from any model, so a single class gives you validation in Python and a description that other languages, tools and people can use. FastAPI builds its automatic interactive documentation from exactly this output.

Your first schema

Model.model_json_schema() returns a dictionary:

Python A model's schema

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.

Read it like this:

  • title is the class name (the class docstring becomes description).
  • properties lists each field with its JSON type and constraints (minLength, exclusiveMinimum).
  • required lists the fields with no default. Fields with defaults carry a default value.
  • Constraints you wrote with Field appear automatically; there is nothing to keep in sync.

Nested models and $defs

When a model contains another model, the inner schema is placed once in $defs and referenced with $ref. That keeps the schema small when the same model is used in many places.

Python References with $defs

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.

Input schema or output schema

Validation and serialization can see a model differently. A field with a default is optional in the input but always present in the output, and a computed field exists only in the output. So model_json_schema takes mode:

  • mode="validation" (default): what the model accepts.
  • mode="serialization": what the model produces when dumped.
Python validation versus serialization

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.

In the validation schema only name is required. In the serialization schema qty and label are guaranteed to be present as well. (FastAPI picks the right mode for requests and responses for you.)

Enriching the schema

Tool What it adds
Field(title=..., description=..., examples=[...]) documentation for one field
Class docstring description of the model
ConfigDict(title="...") a custom model title
ConfigDict(json_schema_extra={...}) any extra keys, for example a model-wide example
Field(json_schema_extra={...}) any extra keys for one field
Python Examples and extras

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.

Keys that begin with x- are the conventional place for custom extensions, since tools ignore ones they do not understand.

Schemas for any type: TypeAdapter

You can also generate a schema for types that are not models, such as list[int] or a union, through TypeAdapter (covered in the last lesson of this chapter):

Python A schema for a plain type

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.

What people do with schemas

flowchart LR
    M["Pydantic model"] --> S["JSON Schema"]
    S --> D["API docs<br/>OpenAPI, Swagger UI"]
    S --> F["Form generators"]
    S --> C["Client code generators"]
    S --> L["LLM tool and<br/>structured output specs"]
    S --> V["Validation in other<br/>languages"]

One Python class, many consumers.

Besides API documentation, schemas are widely used to describe tool parameters and structured outputs for language models, to generate forms, and to validate configuration files in an editor. Saving Model.model_json_schema() to a file with json.dump is the usual first step.

Pydantic follows JSON Schema draft 2020-12, the dialect used by OpenAPI 3.1. Some constraints that Pydantic enforces in Python, such as custom validators, cannot be expressed in JSON Schema, so the schema may be looser than the real validation.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where does Pydantic put the schema of a nested model used in several fields?

    Reusable schemas go in $defs and each use is a $ref.
  2. 2. Which fields appear in the schema's required list?

    Required mirrors validation: fields with no default must be provided.
  3. 3. Why does model_json_schema have a mode argument?

    mode='validation' describes accepted input; mode='serialization' describes dumped output.
  4. 4. Which Field argument adds an example to the schema?

    Field(examples=[...]) is carried into the schema, where documentation tools display it.

Summary

  • Model.model_json_schema() turns a model, its constraints and its docstring into JSON Schema.
  • Nested models are stored once in $defs and referenced with $ref; required lists fields without defaults.
  • Use mode="validation" for inputs and mode="serialization" for outputs.
  • Enrich with Field(description, examples), ConfigDict(title, json_schema_extra).
  • Schemas feed API docs, forms, code generators and LLM tool definitions; custom validators cannot always be expressed in the schema.

Next: TypeAdapter and Dataclasses