In Pydantic 2, why can model_json_schema() differ between mode='validation' and mode='serialization', and which one should document an event you publish?
answer
- what is accepted versus what is written
- Decimal in, string out
- computed fields only on output
- the default mode is validation
basics
~20 sPydantic 2's default validation-mode schema describes what the model accepts, while serialization mode describes what a dump writes: Decimal as a string only, computed fields as readOnly, custom serializers' return types. A published event is documented in serialization mode.
solid answer
~40 s`model_json_schema()` defaults to `mode='validation'`, which describes the input the model accepts, lax conversions included: a `Decimal` field accepts a number or a string, so its schema is an `anyOf`. `mode='serialization'` describes what `model_dump_json()` writes: the same `Decimal` is a `string`, every `@computed_field` appears as a `readOnly` property, and a field serializer's return annotation replaces the field's own type. For an event my service publishes, consumers need the serialization schema, generated with the same alias setting as the dump; for a request body my service receives, the validation schema is the contract. The two can also be pinned with `json_schema_mode_override` in `model_config`. And `model_json_schema()` describes the class; it is not `model_dump_json()`, which serializes an instance.
code
python · 14 linesfrom decimal import Decimal
from pydantic import BaseModel
class Model(BaseModel):
a: Decimal = Decimal('12.34')
print(Model.model_json_schema(mode='validation'))
#> {'properties': {'a': {'anyOf': [{'type': 'number'}, {'type': 'string'}], 'default': '12.34', 'title': 'A'}}, 'title': 'Model', 'type': 'object'}
print(Model.model_json_schema(mode='serialization'))
#> {'properties': {'a': {'default': '12.34', 'title': 'A', 'type': 'string'}}, 'title': 'Model', 'type': 'object'}go deeper
Recall that model_json_schema() returns a JSON Schema dict for the class, and that it has a validation mode, the default, and a serialization mode.
Explain which features make the modes differ, Decimal, computed fields, serializer return types and aliases, and which mode suits input versus output contracts.
Show you can keep a published event contract honest: serialization-mode schema, the same alias policy as the dump, annotated serializers, and a CI diff of the schema.
Decide how schemas are published across teams, which mode each contract uses and how changes are reviewed, so consumers code against what producers actually emit.
## One model, two contracts A Pydantic 2 model is used in two directions. It **validates** input, often leniently: lax mode turns the string `'12.34'` into a `Decimal`, a JSON array into a `tuple`. It also **serializes** output, usually in a single canonical form. A JSON Schema can describe either direction, so `model_json_schema()` and `TypeAdapter.json_schema()` take a `mode` argument, a `JsonSchemaMode` with two values: - `'validation'`, **the default**, describes what the model accepts; - `'serialization'` describes what a dump in JSON mode produces. Do not confuse either with `model_dump_json()`: the schema methods return a dict describing the **class**, while the dump methods serialize an **instance's data**. ## Where the two modes diverge | Model feature | `mode='validation'` | `mode='serialization'` | |---|---|---| | `Decimal` field | `anyOf` number or string, since both are accepted | `string`, since dumps write a string | | `@computed_field` property | absent, because it is not input | present, marked `readOnly`, and listed as required | | field with a serializer that has a return annotation | the field's own type | the serializer's return type | | `Json[int]` field | a string with `contentMediaType` and an inner schema | `integer`, the parsed value that dumps write | | aliases | validation aliases | serialization aliases | | `datetime` with `ser_json_temporal='seconds'` | a `date-time` string | a number, since 2.14 takes the setting into account | Each difference has the same cause: the schema is generated from the validator or the serializer that Pydantic built, and those two genuinely differ. ## Which mode documents what 1. **An event you publish, or a response you return:** consumers parse what you write, so give them the **serialization** schema. A consumer coding to the validation schema of a `Decimal` field would expect numbers as well as strings, and would not know your computed fields exist. 2. **A request or message you consume:** producers must send what you accept, so the **validation** schema is the right contract. 3. **One model used in both directions:** generate both. When a framework or a schema tool must put both into one document and they differ, Pydantic distinguishes the definitions by appending `-Input` and `-Output` to their references. 4. **Forcing one view:** `ConfigDict(json_schema_mode_override='validation')` or `'serialization'` (since 2.4) makes the model always produce that mode, whatever the call asks for, which also removes those suffixes. ## Settings that must match the dump - **Aliases.** `model_json_schema()` defaults to `by_alias=True`, whereas a dump uses aliases only when `by_alias=True` is passed or `serialize_by_alias=True` is set. Publish a schema with aliases and dump without them, and the contract is wrong from the first message. - **Serializer precision.** A plain serializer without a return annotation gives the schema nothing precise to say about the output, so annotate serializers whose output appears in a published schema. - **Conditional exclusion.** Since 2.14, a computed field with `exclude_if` is not listed as required, because it may be left out. ## Generating schemas in practice - `Model.model_json_schema(mode='serialization')` covers one model; nested models land under `$defs` and are referenced with `$ref`. - `TypeAdapter(list[Event]).json_schema(mode='serialization')` covers a type that is not a model, such as a batch of events. - `models_json_schema()` from `pydantic.json_schema` takes a list of `(model, mode)` pairs and returns one combined document with shared definitions, which is how one file can carry an input and an output view side by side. - `ref_template` changes how references are written, for example when the definitions will live under a different key in a larger document. ## A practical routine for published events - Generate the serialization-mode schema in CI for every event model and diff it against the version consumers have, so a field rename or type change is reviewed rather than discovered. - Keep the alias policy in one place, a shared base class, so the schema and the payload cannot disagree. - Treat a change from validation-mode thinking, for example "a Decimal can be a number", as a defect in the event contract: on the wire it is a string unless a custom serializer says otherwise. The rule of thumb for an interview: validation mode documents what you **accept**, serialization mode documents what you **emit**, and Pydantic defaults to the first.
- Why does a computed field appear as required in the serialization schema but not at all in the validation schema?A computed field is written by every dump and is never accepted as input, so the serialization schema lists it, marked `readOnly`, among the required properties, while the validation schema has no field to describe. Since 2.14 a computed field with `exclude_if` is left out of the required list, because a dump may omit it.
- How do you get the schema for a list of events, or another type that is not a model?Wrap it in a `TypeAdapter`, for example `TypeAdapter(list[ParcelShipped])`, and call `json_schema(mode='serialization')`. It takes the same `mode` and `by_alias` arguments as `model_json_schema()`, and nested models still land in `$defs` with references.
- model_json_schema() describes the output by default
- Both schema modes are identical unless you add custom serializers
- A Decimal field is a number in both schemas
- model_json_schema() and model_dump_json() both serialize the model to JSON
- Computed fields appear in the validation schema as optional inputs