Skip to content

JSON Schema

The json_schema module contains classes and functions to allow the way JSON Schema is generated to be customized.

In general you shouldn’t need to use this module directly; instead, you can use BaseModel.model_json_schema and TypeAdapter.json_schema.

PydanticJsonSchemaWarning

Bases: UserWarning

This class is used to emit warnings produced during JSON schema generation. See the GenerateJsonSchema.emit_warning and GenerateJsonSchema.render_warning_message methods for more details; these can be overridden to control warning behavior.

GenerateJsonSchema

A class for generating JSON schemas.

This class generates JSON schemas based on configured parameters. The default schema dialect is https://json-schema.org/draft/2020-12/schema. The class uses by_alias to configure how fields with multiple names are handled and ref_template to format reference names.

Attributes

schema_dialect

The JSON schema dialect used to generate the schema. See Declaring a Dialect in the JSON Schema documentation for more information about dialects.

ignored_warning_kinds

Warnings to ignore when generating the schema. self.render_warning_message will do nothing if its argument kind is in ignored_warning_kinds; this value can be modified on subclasses to easily control which warnings are emitted.

Type: set[JsonSchemaWarningKind]

by_alias

Whether to use field aliases when generating the schema.

ref_template

The format string used when generating reference names.

core_to_json_refs

A mapping of core refs to JSON refs.

Type: dict[CoreModeRef, JsonRef]

core_to_defs_refs

A mapping of core refs to definition refs.

Type: dict[CoreModeRef, DefsRef]

defs_to_core_refs

A mapping of definition refs to core refs.

Type: dict[DefsRef, CoreModeRef]

json_to_defs_refs

A mapping of JSON refs to definition refs.

Type: dict[JsonRef, DefsRef]

definitions

Definitions in the schema.

Type: dict[DefsRef, JsonSchemaValue]

Constructor Parameters

by_alias : bool Default: True

Whether to use field aliases in the generated schemas.

ref_template : str Default: DEFAULT_REF_TEMPLATE

The format string to use when generating reference names.

union_format : Literal[‘any_of’, ‘primitive_type_array’] Default: 'any_of'

The format to use when combining schemas from unions together. Can be one of:

  • 'any_of': Use the anyOf keyword to combine schemas (the default).
  • 'primitive_type_array': Use the type keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.

Methods

build_schema_type_to_method

def build_schema_type_to_method(

) -> dict[CoreSchemaOrFieldType, Callable[[CoreSchemaOrField], JsonSchemaValue]]

Builds a dictionary mapping fields to methods for generating JSON schemas.

Returns

dict[CoreSchemaOrFieldType, Callable[[CoreSchemaOrField], JsonSchemaValue]] — A dictionary containing the mapping of CoreSchemaOrFieldType to a handler method.

Raises
  • TypeError — If no method has been defined for generating a JSON schema for a given pydantic core schema type.

generate_definitions

def generate_definitions(
    inputs: Sequence[tuple[JsonSchemaKeyT, JsonSchemaMode, core_schema.CoreSchema]],
) -> tuple[dict[tuple[JsonSchemaKeyT, JsonSchemaMode], JsonSchemaValue], dict[DefsRef, JsonSchemaValue]]

Generates JSON schema definitions from a list of core schemas, pairing the generated definitions with a mapping that links the input keys to the definition references.

Returns

tuple[dict[tuple[JsonSchemaKeyT, JsonSchemaMode], JsonSchemaValue], dict[DefsRef, JsonSchemaValue]] — A tuple where:

  • The first element is a dictionary whose keys are tuples of JSON schema key type and JSON mode, and whose values are the JSON schema corresponding to that pair of inputs. (These schemas may have JsonRef references to definitions that are defined in the second returned element.)
  • The second element is a dictionary whose keys are definition references for the JSON schemas from the first returned element, and whose values are the actual JSON schema definitions.
Parameters

inputs : Sequence[tuple[JsonSchemaKeyT, JsonSchemaMode, core_schema.CoreSchema]]

A sequence of tuples, where:

  • The first element is a JSON schema key type.
  • The second element is the JSON mode: either ‘validation’ or ‘serialization’.
  • The third element is a core schema.
Raises
  • PydanticUserError — Raised if the JSON schema generator has already been used to generate a JSON schema.

generate

def generate(schema: CoreSchema, mode: JsonSchemaMode = 'validation') -> JsonSchemaValue

Generates a JSON schema for a specified schema in a specified mode.

Returns

JsonSchemaValue — A JSON schema representing the specified schema.

Parameters

schema : CoreSchema

A Pydantic model.

mode : JsonSchemaMode Default: 'validation'

The mode in which to generate the schema. Defaults to ‘validation’.

Raises
  • PydanticUserError — If the JSON schema generator has already been used to generate a JSON schema.

generate_inner

def generate_inner(schema: CoreSchemaOrField) -> JsonSchemaValue

Generates a JSON schema for a given core schema.

TODO: the nested function definitions here seem like bad practice, I’d like to unpack these in a future PR. It’d be great if we could shorten the call stack a bit for JSON schema generation, and I think there’s potential for that here.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : CoreSchemaOrField

The given core schema.

sort

def sort(value: JsonSchemaValue, parent_key: str | None = None) -> JsonSchemaValue

Override this method to customize the sorting of the JSON schema (e.g., don’t sort at all, sort all keys unconditionally, etc.)

By default, alphabetically sort the keys in the JSON schema, skipping the ‘properties’ and ‘default’ keys to preserve field definition order. This sort is recursive, so it will sort all nested dictionaries as well.

Returns

JsonSchemaValue

invalid_schema

def invalid_schema(schema: core_schema.InvalidSchema) -> JsonSchemaValue

Placeholder - should never be called.

Returns

JsonSchemaValue

any_schema

def any_schema(schema: core_schema.AnySchema) -> JsonSchemaValue

Generates a JSON schema that matches any value.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.AnySchema

The core schema.

none_schema

def none_schema(schema: core_schema.NoneSchema) -> JsonSchemaValue

Generates a JSON schema that matches None.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.NoneSchema

The core schema.

bool_schema

def bool_schema(schema: core_schema.BoolSchema) -> JsonSchemaValue

Generates a JSON schema that matches a bool value.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.BoolSchema

The core schema.

int_schema

def int_schema(schema: core_schema.IntSchema) -> JsonSchemaValue

Generates a JSON schema that matches an int value.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.IntSchema

The core schema.

float_schema

def float_schema(schema: core_schema.FloatSchema) -> JsonSchemaValue

Generates a JSON schema that matches a float value.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.FloatSchema

The core schema.

decimal_schema

def decimal_schema(schema: core_schema.DecimalSchema) -> JsonSchemaValue

Generates a JSON schema that matches a decimal value.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.DecimalSchema

The core schema.

str_schema

def str_schema(schema: core_schema.StringSchema) -> JsonSchemaValue

Generates a JSON schema that matches a string value.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.StringSchema

The core schema.

bytes_schema

def bytes_schema(schema: core_schema.BytesSchema) -> JsonSchemaValue

Generates a JSON schema that matches a bytes value.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.BytesSchema

The core schema.

date_schema

def date_schema(schema: core_schema.DateSchema) -> JsonSchemaValue

Generates a JSON schema that matches a date value.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.DateSchema

The core schema.

time_schema

def time_schema(schema: core_schema.TimeSchema) -> JsonSchemaValue

Generates a JSON schema that matches a time value.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.TimeSchema

The core schema.

datetime_schema

def datetime_schema(schema: core_schema.DatetimeSchema) -> JsonSchemaValue

Generates a JSON schema that matches a datetime value.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.DatetimeSchema

The core schema.

timedelta_schema

def timedelta_schema(schema: core_schema.TimedeltaSchema) -> JsonSchemaValue

Generates a JSON schema that matches a timedelta value.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.TimedeltaSchema

The core schema.

literal_schema

def literal_schema(schema: core_schema.LiteralSchema) -> JsonSchemaValue

Generates a JSON schema that matches a literal value.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.LiteralSchema

The core schema.

missing_sentinel_schema

def missing_sentinel_schema(
    schema: core_schema.MissingSentinelSchema,
) -> JsonSchemaValue

Generates a JSON schema that matches the MISSING sentinel value.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.MissingSentinelSchema

The core schema.

enum_schema

def enum_schema(schema: core_schema.EnumSchema) -> JsonSchemaValue

Generates a JSON schema that matches an Enum value.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.EnumSchema

The core schema.

is_instance_schema

def is_instance_schema(schema: core_schema.IsInstanceSchema) -> JsonSchemaValue

Handles JSON schema generation for a core schema that checks if a value is an instance of a class.

Unless overridden in a subclass, this raises an error.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.IsInstanceSchema

The core schema.

is_subclass_schema

def is_subclass_schema(schema: core_schema.IsSubclassSchema) -> JsonSchemaValue

Handles JSON schema generation for a core schema that checks if a value is a subclass of a class.

For backwards compatibility with v1, this does not raise an error, but can be overridden to change this.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.IsSubclassSchema

The core schema.

callable_schema

def callable_schema(schema: core_schema.CallableSchema) -> JsonSchemaValue

Generates a JSON schema that matches a callable value.

Unless overridden in a subclass, this raises an error.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.CallableSchema

The core schema.

list_schema

def list_schema(schema: core_schema.ListSchema) -> JsonSchemaValue

Returns a schema that matches a list schema.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.ListSchema

The core schema.

tuple_positional_schema

def tuple_positional_schema(schema: core_schema.TupleSchema) -> JsonSchemaValue

Replaced by tuple_schema.

Returns

JsonSchemaValue

tuple_variable_schema

def tuple_variable_schema(schema: core_schema.TupleSchema) -> JsonSchemaValue

Replaced by tuple_schema.

Returns

JsonSchemaValue

tuple_schema

def tuple_schema(schema: core_schema.TupleSchema) -> JsonSchemaValue

Generates a JSON schema that matches a tuple schema e.g. tuple[int, str, bool] or tuple[int, ...].

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.TupleSchema

The core schema.

set_schema

def set_schema(schema: core_schema.SetSchema) -> JsonSchemaValue

Generates a JSON schema that matches a set schema.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.SetSchema

The core schema.

frozenset_schema

def frozenset_schema(schema: core_schema.FrozenSetSchema) -> JsonSchemaValue

Generates a JSON schema that matches a frozenset schema.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.FrozenSetSchema

The core schema.

generator_schema

def generator_schema(schema: core_schema.GeneratorSchema) -> JsonSchemaValue

Returns a JSON schema that represents the provided GeneratorSchema.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.GeneratorSchema

The schema.

dict_schema

def dict_schema(schema: core_schema.DictSchema) -> JsonSchemaValue

Generates a JSON schema that matches a dict schema.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.DictSchema

The core schema.

function_before_schema

def function_before_schema(
    schema: core_schema.BeforeValidatorFunctionSchema,
) -> JsonSchemaValue

Generates a JSON schema that matches a function-before schema.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.BeforeValidatorFunctionSchema

The core schema.

function_after_schema

def function_after_schema(
    schema: core_schema.AfterValidatorFunctionSchema,
) -> JsonSchemaValue

Generates a JSON schema that matches a function-after schema.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.AfterValidatorFunctionSchema

The core schema.

function_plain_schema

def function_plain_schema(
    schema: core_schema.PlainValidatorFunctionSchema,
) -> JsonSchemaValue

Generates a JSON schema that matches a function-plain schema.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.PlainValidatorFunctionSchema

The core schema.

function_wrap_schema

def function_wrap_schema(
    schema: core_schema.WrapValidatorFunctionSchema,
) -> JsonSchemaValue

Generates a JSON schema that matches a function-wrap schema.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.WrapValidatorFunctionSchema

The core schema.

default_schema

def default_schema(schema: core_schema.WithDefaultSchema) -> JsonSchemaValue

Generates a JSON schema that matches a schema with a default value.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.WithDefaultSchema

The core schema.

get_default_value

def get_default_value(schema: core_schema.WithDefaultSchema) -> Any

Get the default value to be used when generating a JSON Schema for a core schema with a default.

The default implementation is to use the statically defined default value. This method can be overridden if you want to make use of the default factory.

Returns

Any — The default value to use, or NoDefault if no default value is available.

Parameters

schema : core_schema.WithDefaultSchema

The 'with-default' core schema.

nullable_schema

def nullable_schema(schema: core_schema.NullableSchema) -> JsonSchemaValue

Generates a JSON schema that matches a schema that allows null values.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.NullableSchema

The core schema.

union_schema

def union_schema(schema: core_schema.UnionSchema) -> JsonSchemaValue

Generates a JSON schema that matches a schema that allows values matching any of the given schemas.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.UnionSchema

The core schema.

get_union_of_schemas

def get_union_of_schemas(schemas: list[JsonSchemaValue]) -> JsonSchemaValue

Returns the JSON Schema representation for the union of the provided JSON Schemas.

The result depends on the configured 'union_format'.

Returns

JsonSchemaValue — The JSON Schema representing the union of schemas.

Parameters

schemas : list[JsonSchemaValue]

The list of JSON Schemas to be included in the union.

tagged_union_schema

def tagged_union_schema(schema: core_schema.TaggedUnionSchema) -> JsonSchemaValue

Generates a JSON schema that matches a schema that allows values matching any of the given schemas, where the schemas are tagged with a discriminator field that indicates which schema should be used to validate the value.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.TaggedUnionSchema

The core schema.

chain_schema

def chain_schema(schema: core_schema.ChainSchema) -> JsonSchemaValue

Generates a JSON schema that matches a core_schema.ChainSchema.

When generating a schema for validation, we return the validation JSON schema for the first step in the chain. For serialization, we return the serialization JSON schema for the last step in the chain.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.ChainSchema

The core schema.

lax_or_strict_schema

def lax_or_strict_schema(schema: core_schema.LaxOrStrictSchema) -> JsonSchemaValue

Generates a JSON schema that matches a schema that allows values matching either the lax schema or the strict schema.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.LaxOrStrictSchema

The core schema.

json_or_python_schema

def json_or_python_schema(schema: core_schema.JsonOrPythonSchema) -> JsonSchemaValue

Generates a JSON schema that matches a schema that allows values matching either the JSON schema or the Python schema.

The JSON schema is used instead of the Python schema. If you want to use the Python schema, you should override this method.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.JsonOrPythonSchema

The core schema.

typed_dict_schema

def typed_dict_schema(schema: core_schema.TypedDictSchema) -> JsonSchemaValue

Generates a JSON schema that matches a schema that defines a typed dict.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.TypedDictSchema

The core schema.

typed_dict_field_schema

def typed_dict_field_schema(schema: core_schema.TypedDictField) -> JsonSchemaValue

Generates a JSON schema that matches a schema that defines a typed dict field.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.TypedDictField

The core schema.

dataclass_field_schema

def dataclass_field_schema(schema: core_schema.DataclassField) -> JsonSchemaValue

Generates a JSON schema that matches a schema that defines a dataclass field.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.DataclassField

The core schema.

model_field_schema

def model_field_schema(schema: core_schema.ModelField) -> JsonSchemaValue

Generates a JSON schema that matches a schema that defines a model field.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.ModelField

The core schema.

computed_field_schema

def computed_field_schema(schema: core_schema.ComputedField) -> JsonSchemaValue

Generates a JSON schema that matches a schema that defines a computed field.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.ComputedField

The core schema.

model_schema

def model_schema(schema: core_schema.ModelSchema) -> JsonSchemaValue

Generates a JSON schema that matches a schema that defines a model.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.ModelSchema

The core schema.

resolve_ref_schema

def resolve_ref_schema(json_schema: JsonSchemaValue) -> JsonSchemaValue

Resolve a JsonSchemaValue to the non-ref schema if it is a $ref schema.

Returns

JsonSchemaValue — The resolved schema.

Parameters

json_schema : JsonSchemaValue

The schema to resolve.

Raises
  • RuntimeError — If the schema reference can’t be found in definitions.

model_fields_schema

def model_fields_schema(schema: core_schema.ModelFieldsSchema) -> JsonSchemaValue

Generates a JSON schema that matches a schema that defines a model’s fields.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.ModelFieldsSchema

The core schema.

field_is_present

def field_is_present(field: CoreSchemaField) -> bool

Whether the field should be included in the generated JSON schema.

Returns

boolTrue if the field should be included in the generated JSON schema, False otherwise.

Parameters

field : CoreSchemaField

The schema for the field itself.

field_is_required

def field_is_required(
    field: core_schema.ModelField | core_schema.DataclassField | core_schema.TypedDictField,
    total: bool,
) -> bool

Whether the field should be marked as required in the generated JSON schema. (Note that this is irrelevant if the field is not present in the JSON schema.).

Returns

boolTrue if the field should be marked as required in the generated JSON schema, False otherwise.

Parameters

field : core_schema.ModelField | core_schema.DataclassField | core_schema.TypedDictField

The schema for the field itself.

total : bool

Only applies to TypedDictFields. Indicates if the TypedDict this field belongs to is total, in which case any fields that don’t explicitly specify required=False are required.

dataclass_args_schema

def dataclass_args_schema(schema: core_schema.DataclassArgsSchema) -> JsonSchemaValue

Generates a JSON schema that matches a schema that defines a dataclass’s constructor arguments.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.DataclassArgsSchema

The core schema.

dataclass_schema

def dataclass_schema(schema: core_schema.DataclassSchema) -> JsonSchemaValue

Generates a JSON schema that matches a schema that defines a dataclass.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.DataclassSchema

The core schema.

arguments_schema

def arguments_schema(schema: core_schema.ArgumentsSchema) -> JsonSchemaValue

Generates a JSON schema that matches a schema that defines a function’s arguments.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.ArgumentsSchema

The core schema.

kw_arguments_schema

def kw_arguments_schema(
    arguments: list[core_schema.ArgumentsParameter],
    var_kwargs_schema: CoreSchema | None,
) -> JsonSchemaValue

Generates a JSON schema that matches a schema that defines a function’s keyword arguments.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

arguments : list[core_schema.ArgumentsParameter]

The core schema.

p_arguments_schema

def p_arguments_schema(
    arguments: list[core_schema.ArgumentsParameter],
    var_args_schema: CoreSchema | None,
) -> JsonSchemaValue

Generates a JSON schema that matches a schema that defines a function’s positional arguments.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

arguments : list[core_schema.ArgumentsParameter]

The core schema.

get_argument_name

def get_argument_name(
    argument: core_schema.ArgumentsParameter | core_schema.ArgumentsV3Parameter,
) -> str

Retrieves the name of an argument.

Returns

str — The name of the argument.

Parameters

argument : core_schema.ArgumentsParameter | core_schema.ArgumentsV3Parameter

The core schema.

arguments_v3_schema

def arguments_v3_schema(schema: core_schema.ArgumentsV3Schema) -> JsonSchemaValue

Generates a JSON schema that matches a schema that defines a function’s arguments.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.ArgumentsV3Schema

The core schema.

call_schema

def call_schema(schema: core_schema.CallSchema) -> JsonSchemaValue

Generates a JSON schema that matches a schema that defines a function call.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.CallSchema

The core schema.

custom_error_schema

def custom_error_schema(schema: core_schema.CustomErrorSchema) -> JsonSchemaValue

Generates a JSON schema that matches a schema that defines a custom error.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.CustomErrorSchema

The core schema.

json_schema

def json_schema(schema: core_schema.JsonSchema) -> JsonSchemaValue

Generates a JSON schema that matches a schema that defines a JSON object.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.JsonSchema

The core schema.

url_schema

def url_schema(schema: core_schema.UrlSchema) -> JsonSchemaValue

Generates a JSON schema that matches a schema that defines a URL.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.UrlSchema

The core schema.

multi_host_url_schema

def multi_host_url_schema(schema: core_schema.MultiHostUrlSchema) -> JsonSchemaValue

Generates a JSON schema that matches a schema that defines a URL that can be used with multiple hosts.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.MultiHostUrlSchema

The core schema.

uuid_schema

def uuid_schema(schema: core_schema.UuidSchema) -> JsonSchemaValue

Generates a JSON schema that matches a UUID.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.UuidSchema

The core schema.

definitions_schema

def definitions_schema(schema: core_schema.DefinitionsSchema) -> JsonSchemaValue

Generates a JSON schema that matches a schema that defines a JSON object with definitions.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.DefinitionsSchema

The core schema.

definition_ref_schema

def definition_ref_schema(
    schema: core_schema.DefinitionReferenceSchema,
) -> JsonSchemaValue

Generates a JSON schema that matches a schema that references a definition.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.DefinitionReferenceSchema

The core schema.

ser_schema

def ser_schema(
    schema: core_schema.SerSchema | core_schema.IncExSeqSerSchema | core_schema.IncExDictSerSchema,
) -> JsonSchemaValue | None

Generates a JSON schema that matches a schema that defines a serialized object.

Returns

JsonSchemaValue | None — The generated JSON schema.

Parameters

schema : core_schema.SerSchema | core_schema.IncExSeqSerSchema | core_schema.IncExDictSerSchema

The core schema.

complex_schema

def complex_schema(schema: core_schema.ComplexSchema) -> JsonSchemaValue

Generates a JSON schema that matches a complex number.

JSON has no standard way to represent complex numbers. Complex number is not a numeric type. Here we represent complex number as strings following the rule defined by Python. For instance, ‘1+2j’ is an accepted complex string. Details can be found in Python’s complex documentation.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.ComplexSchema

The core schema.

get_title_from_name

def get_title_from_name(name: str) -> str

Retrieves a title from a name.

Returns

str — The title.

Parameters

name : str

The name to retrieve a title from.

field_title_should_be_set

def field_title_should_be_set(schema: CoreSchemaOrField) -> bool

Returns true if a field with the given schema should have a title set based on the field name.

Intuitively, we want this to return true for schemas that wouldn’t otherwise provide their own title (e.g., int, float, str), and false for those that would (e.g., BaseModel subclasses).

Returns

boolTrue if the field should have a title set, False otherwise.

Parameters

schema : CoreSchemaOrField

The schema to check.

normalize_name

def normalize_name(name: str) -> str

Normalizes a name to be used as a key in a dictionary.

Returns

str — The normalized name.

Parameters

name : str

The name to normalize.

get_defs_ref

def get_defs_ref(core_mode_ref: CoreModeRef) -> DefsRef

Override this method to change the way that definitions keys are generated from a core reference.

Returns

DefsRef — The definitions key.

Parameters

core_mode_ref : CoreModeRef

The core reference.

get_cache_defs_ref_schema

def get_cache_defs_ref_schema(core_ref: CoreRef) -> tuple[DefsRef, JsonSchemaValue]

This method wraps the get_defs_ref method with some cache-lookup/population logic, and returns both the produced defs_ref and the JSON schema that will refer to the right definition.

Returns

tuple[DefsRef, JsonSchemaValue] — A tuple of the definitions reference and the JSON schema that will refer to it.

Parameters

core_ref : CoreRef

The core reference to get the definitions reference for.

handle_ref_overrides

def handle_ref_overrides(json_schema: JsonSchemaValue) -> JsonSchemaValue

Remove any sibling keys that are redundant with the referenced schema.

Returns

JsonSchemaValue — The schema with redundant sibling keys removed.

Parameters

json_schema : JsonSchemaValue

The schema to remove redundant sibling keys from.

encode_default

def encode_default(dft: Any) -> Any

Encode a default value to a JSON-serializable value.

This is used to encode default values for fields in the generated JSON schema.

Returns

Any — The encoded default value.

Parameters

dft : Any

The default value to encode.

update_with_validations

def update_with_validations(
    json_schema: JsonSchemaValue,
    core_schema: CoreSchema,
    mapping: dict[str, str],
) -> None

Update the json_schema with the corresponding validations specified in the core_schema, using the provided mapping to translate keys in core_schema to the appropriate keys for a JSON schema.

Returns

None

Parameters

json_schema : JsonSchemaValue

The JSON schema to update.

core_schema : CoreSchema

The core schema to get the validations from.

mapping : dict[str, str]

A mapping from core_schema attribute names to the corresponding JSON schema attribute names.

get_json_ref_counts

def get_json_ref_counts(json_schema: JsonSchemaValue) -> dict[JsonRef, int]

Get all values corresponding to the key ‘$ref’ anywhere in the json_schema.

Returns

dict[JsonRef, int]

emit_warning

def emit_warning(kind: JsonSchemaWarningKind, detail: str) -> None

This method simply emits PydanticJsonSchemaWarnings based on handling in the warning_message method.

Returns

None

render_warning_message

def render_warning_message(kind: JsonSchemaWarningKind, detail: str) -> str | None

This method is responsible for ignoring warnings as desired, and for formatting the warning messages.

You can override the value of ignored_warning_kinds in a subclass of GenerateJsonSchema to modify what warnings are generated. If you want more control, you can override this method; just return None in situations where you don’t want warnings to be emitted.

Returns

str | None — The formatted warning message, or None if no warning should be emitted.

Parameters

kind : JsonSchemaWarningKind

The kind of warning to render. It can be one of the following:

  • ‘skipped-choice’: A choice field was skipped because it had no valid choices.
  • ‘non-serializable-default’: A default value was skipped because it was not JSON-serializable.

detail : str

A string with additional details about the warning.

WithJsonSchema

Add this as an annotation on a field to override the (base) JSON schema that would be generated for that field. This provides a way to set a JSON schema for types that would otherwise raise errors when producing a JSON schema, such as Callable, or types that have an is-instance core schema, without needing to go so far as creating a custom subclass of pydantic.json_schema.GenerateJsonSchema. Note that any modifications to the schema that would normally be made (such as setting the title for model fields) will still be performed.

If mode is set this will only apply to that schema generation mode, allowing you to set different json schemas for validation and serialization.

Examples

Add examples to a JSON schema.

If the JSON Schema already contains examples, the provided examples will be appended.

If mode is set this will only apply to that schema generation mode, allowing you to add different examples for validation and serialization.

SkipJsonSchema

Add this as an annotation on a field to skip generating a JSON schema for that field.

model_json_schema

def model_json_schema(
    cls: type[BaseModel] | type[PydanticDataclass],
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
    schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
    mode: JsonSchemaMode = 'validation',
) -> dict[str, Any]

Utility function to generate a JSON Schema for a model.

Returns

dict[str, Any] — The generated JSON Schema.

Parameters

cls : type[BaseModel] | type[PydanticDataclass]

The model class to generate a JSON Schema for.

by_alias : bool Default: True

If True (the default), fields will be serialized according to their alias. If False, fields will be serialized according to their attribute name.

ref_template : str Default: DEFAULT_REF_TEMPLATE

The template to use for generating JSON Schema references.

union_format : Literal[‘any_of’, ‘primitive_type_array’] Default: 'any_of'

The format to use when combining schemas from unions together. Can be one of:

  • 'any_of': Use the anyOf keyword to combine schemas (the default).
  • 'primitive_type_array': Use the type keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.

schema_generator : type[GenerateJsonSchema] Default: GenerateJsonSchema

The class to use for generating the JSON Schema.

mode : JsonSchemaMode Default: 'validation'

The mode to use for generating the JSON Schema. It can be one of the following:

  • ‘validation’: Generate a JSON Schema for validating data.
  • ‘serialization’: Generate a JSON Schema for serializing data.

models_json_schema

def models_json_schema(
    models: Sequence[tuple[type[BaseModel] | type[PydanticDataclass], JsonSchemaMode]],
    by_alias: bool = True,
    title: str | None = None,
    description: str | None = None,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
    schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
) -> tuple[dict[tuple[type[BaseModel] | type[PydanticDataclass], JsonSchemaMode], JsonSchemaValue], JsonSchemaValue]

Utility function to generate a JSON Schema for multiple models.

Returns

tuple[dict[tuple[type[BaseModel] | type[PydanticDataclass], JsonSchemaMode], JsonSchemaValue], JsonSchemaValue] — A tuple where:

  • The first element is a dictionary whose keys are tuples of JSON schema key type and JSON mode, and whose values are the JSON schema corresponding to that pair of inputs. (These schemas may have JsonRef references to definitions that are defined in the second returned element.)
  • The second element is a JSON schema containing all definitions referenced in the first returned element, along with the optional title and description keys.

Parameters

models : Sequence[tuple[type[BaseModel] | type[PydanticDataclass], JsonSchemaMode]]

A sequence of tuples of the form (model, mode).

by_alias : bool Default: True

Whether field aliases should be used as keys in the generated JSON Schema.

title : str | None Default: None

The title of the generated JSON Schema.

description : str | None Default: None

The description of the generated JSON Schema.

ref_template : str Default: DEFAULT_REF_TEMPLATE

The reference template to use for generating JSON Schema references.

union_format : Literal[‘any_of’, ‘primitive_type_array’] Default: 'any_of'

The format to use when combining schemas from unions together. Can be one of:

  • 'any_of': Use the anyOf keyword to combine schemas (the default).
  • 'primitive_type_array': Use the type keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.

schema_generator : type[GenerateJsonSchema] Default: GenerateJsonSchema

The schema generator to use for generating the JSON Schema.

CoreSchemaOrFieldType

A type alias for defined schema types that represents a union of core_schema.CoreSchemaType and core_schema.CoreSchemaFieldType.

Default: Literal[core_schema.CoreSchemaType, core_schema.CoreSchemaFieldType]

JsonSchemaValue

A type alias for a JSON schema value. This is a dictionary of string keys to arbitrary JSON values.

Default: dict[str, Any]

JsonSchemaMode

A type alias that represents the mode of a JSON schema; either ‘validation’ or ‘serialization’.

For some types, the inputs to validation differ from the outputs of serialization. For example, computed fields will only be present when serializing, and should not be provided when validating. This flag provides a way to indicate whether you want the JSON schema required for validation inputs, or that will be matched by serialization outputs.

Default: Literal['validation', 'serialization']

JsonSchemaWarningKind

A type alias representing the kinds of warnings that can be emitted during JSON schema generation.

See GenerateJsonSchema.render_warning_message for more details.

Default: Literal['skipped-choice', 'non-serializable-default', 'skipped-discriminator']

NoDefault

A sentinel value used to indicate that no default value should be used when generating a JSON Schema for a core schema with a default value.

Default: object()

DEFAULT_REF_TEMPLATE

The default format string used to generate reference names.

Default: '#/$defs/\{model\}'