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
Section titled “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
Section titled “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
Section titled “Attributes”schema_dialect
Section titled “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
Section titled “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
Section titled “by_alias”Whether to use field aliases when generating the schema.
ref_template
Section titled “ref_template”The format string used when generating reference names.
core_to_json_refs
Section titled “core_to_json_refs”A mapping of core refs to JSON refs.
Type: dict[CoreModeRef, JsonRef]
core_to_defs_refs
Section titled “core_to_defs_refs”A mapping of core refs to definition refs.
Type: dict[CoreModeRef, DefsRef]
defs_to_core_refs
Section titled “defs_to_core_refs”A mapping of definition refs to core refs.
Type: dict[DefsRef, CoreModeRef]
json_to_defs_refs
Section titled “json_to_defs_refs”A mapping of JSON refs to definition refs.
Type: dict[JsonRef, DefsRef]
definitions
Section titled “definitions”Definitions in the schema.
Type: dict[DefsRef, JsonSchemaValue]
Constructor Parameters
Section titled “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 theanyOfkeyword to combine schemas (the default).'primitive_type_array': Use thetypekeyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string,boolean,null,integerornumber) or contains constraints/metadata, falls back toany_of.
Methods
Section titled “Methods”build_schema_type_to_method
Section titled “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
Section titled “Returns”dict[CoreSchemaOrFieldType, Callable[[CoreSchemaOrField], JsonSchemaValue]] — A dictionary containing the mapping of CoreSchemaOrFieldType to a handler method.
Raises
Section titled “Raises”TypeError— If no method has been defined for generating a JSON schema for a given pydantic core schema type.
generate_definitions
Section titled “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
Section titled “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
Section titled “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
Section titled “Raises”PydanticUserError— Raised if the JSON schema generator has already been used to generate a JSON schema.
generate
Section titled “generate”def generate(schema: CoreSchema, mode: JsonSchemaMode = 'validation') -> JsonSchemaValueGenerates a JSON schema for a specified schema in a specified mode.
Returns
Section titled “Returns”JsonSchemaValue — A JSON schema representing the specified schema.
Parameters
Section titled “Parameters”schema : CoreSchema
A Pydantic model.
mode : JsonSchemaMode Default: 'validation'
The mode in which to generate the schema. Defaults to ‘validation’.
Raises
Section titled “Raises”PydanticUserError— If the JSON schema generator has already been used to generate a JSON schema.
generate_inner
Section titled “generate_inner”def generate_inner(schema: CoreSchemaOrField) -> JsonSchemaValueGenerates 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
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : CoreSchemaOrField
The given core schema.
def sort(value: JsonSchemaValue, parent_key: str | None = None) -> JsonSchemaValueOverride 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
Section titled “Returns”JsonSchemaValue
invalid_schema
Section titled “invalid_schema”def invalid_schema(schema: core_schema.InvalidSchema) -> JsonSchemaValuePlaceholder - should never be called.
Returns
Section titled “Returns”JsonSchemaValue
any_schema
Section titled “any_schema”def any_schema(schema: core_schema.AnySchema) -> JsonSchemaValueGenerates a JSON schema that matches any value.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.AnySchema
The core schema.
none_schema
Section titled “none_schema”def none_schema(schema: core_schema.NoneSchema) -> JsonSchemaValueGenerates a JSON schema that matches None.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.NoneSchema
The core schema.
bool_schema
Section titled “bool_schema”def bool_schema(schema: core_schema.BoolSchema) -> JsonSchemaValueGenerates a JSON schema that matches a bool value.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.BoolSchema
The core schema.
int_schema
Section titled “int_schema”def int_schema(schema: core_schema.IntSchema) -> JsonSchemaValueGenerates a JSON schema that matches an int value.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.IntSchema
The core schema.
float_schema
Section titled “float_schema”def float_schema(schema: core_schema.FloatSchema) -> JsonSchemaValueGenerates a JSON schema that matches a float value.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.FloatSchema
The core schema.
decimal_schema
Section titled “decimal_schema”def decimal_schema(schema: core_schema.DecimalSchema) -> JsonSchemaValueGenerates a JSON schema that matches a decimal value.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.DecimalSchema
The core schema.
str_schema
Section titled “str_schema”def str_schema(schema: core_schema.StringSchema) -> JsonSchemaValueGenerates a JSON schema that matches a string value.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.StringSchema
The core schema.
bytes_schema
Section titled “bytes_schema”def bytes_schema(schema: core_schema.BytesSchema) -> JsonSchemaValueGenerates a JSON schema that matches a bytes value.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.BytesSchema
The core schema.
date_schema
Section titled “date_schema”def date_schema(schema: core_schema.DateSchema) -> JsonSchemaValueGenerates a JSON schema that matches a date value.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.DateSchema
The core schema.
time_schema
Section titled “time_schema”def time_schema(schema: core_schema.TimeSchema) -> JsonSchemaValueGenerates a JSON schema that matches a time value.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.TimeSchema
The core schema.
datetime_schema
Section titled “datetime_schema”def datetime_schema(schema: core_schema.DatetimeSchema) -> JsonSchemaValueGenerates a JSON schema that matches a datetime value.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.DatetimeSchema
The core schema.
timedelta_schema
Section titled “timedelta_schema”def timedelta_schema(schema: core_schema.TimedeltaSchema) -> JsonSchemaValueGenerates a JSON schema that matches a timedelta value.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.TimedeltaSchema
The core schema.
literal_schema
Section titled “literal_schema”def literal_schema(schema: core_schema.LiteralSchema) -> JsonSchemaValueGenerates a JSON schema that matches a literal value.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.LiteralSchema
The core schema.
missing_sentinel_schema
Section titled “missing_sentinel_schema”def missing_sentinel_schema(
schema: core_schema.MissingSentinelSchema,
) -> JsonSchemaValueGenerates a JSON schema that matches the MISSING sentinel value.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.MissingSentinelSchema
The core schema.
enum_schema
Section titled “enum_schema”def enum_schema(schema: core_schema.EnumSchema) -> JsonSchemaValueGenerates a JSON schema that matches an Enum value.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.EnumSchema
The core schema.
is_instance_schema
Section titled “is_instance_schema”def is_instance_schema(schema: core_schema.IsInstanceSchema) -> JsonSchemaValueHandles 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
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.IsInstanceSchema
The core schema.
is_subclass_schema
Section titled “is_subclass_schema”def is_subclass_schema(schema: core_schema.IsSubclassSchema) -> JsonSchemaValueHandles 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
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.IsSubclassSchema
The core schema.
callable_schema
Section titled “callable_schema”def callable_schema(schema: core_schema.CallableSchema) -> JsonSchemaValueGenerates a JSON schema that matches a callable value.
Unless overridden in a subclass, this raises an error.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.CallableSchema
The core schema.
list_schema
Section titled “list_schema”def list_schema(schema: core_schema.ListSchema) -> JsonSchemaValueReturns a schema that matches a list schema.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.ListSchema
The core schema.
tuple_positional_schema
Section titled “tuple_positional_schema”def tuple_positional_schema(schema: core_schema.TupleSchema) -> JsonSchemaValueReplaced by tuple_schema.
Returns
Section titled “Returns”JsonSchemaValue
tuple_variable_schema
Section titled “tuple_variable_schema”def tuple_variable_schema(schema: core_schema.TupleSchema) -> JsonSchemaValueReplaced by tuple_schema.
Returns
Section titled “Returns”JsonSchemaValue
tuple_schema
Section titled “tuple_schema”def tuple_schema(schema: core_schema.TupleSchema) -> JsonSchemaValueGenerates a JSON schema that matches a tuple schema e.g. tuple[int, str, bool] or tuple[int, ...].
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.TupleSchema
The core schema.
set_schema
Section titled “set_schema”def set_schema(schema: core_schema.SetSchema) -> JsonSchemaValueGenerates a JSON schema that matches a set schema.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.SetSchema
The core schema.
frozenset_schema
Section titled “frozenset_schema”def frozenset_schema(schema: core_schema.FrozenSetSchema) -> JsonSchemaValueGenerates a JSON schema that matches a frozenset schema.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.FrozenSetSchema
The core schema.
generator_schema
Section titled “generator_schema”def generator_schema(schema: core_schema.GeneratorSchema) -> JsonSchemaValueReturns a JSON schema that represents the provided GeneratorSchema.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.GeneratorSchema
The schema.
dict_schema
Section titled “dict_schema”def dict_schema(schema: core_schema.DictSchema) -> JsonSchemaValueGenerates a JSON schema that matches a dict schema.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.DictSchema
The core schema.
function_before_schema
Section titled “function_before_schema”def function_before_schema(
schema: core_schema.BeforeValidatorFunctionSchema,
) -> JsonSchemaValueGenerates a JSON schema that matches a function-before schema.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.BeforeValidatorFunctionSchema
The core schema.
function_after_schema
Section titled “function_after_schema”def function_after_schema(
schema: core_schema.AfterValidatorFunctionSchema,
) -> JsonSchemaValueGenerates a JSON schema that matches a function-after schema.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.AfterValidatorFunctionSchema
The core schema.
function_plain_schema
Section titled “function_plain_schema”def function_plain_schema(
schema: core_schema.PlainValidatorFunctionSchema,
) -> JsonSchemaValueGenerates a JSON schema that matches a function-plain schema.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.PlainValidatorFunctionSchema
The core schema.
function_wrap_schema
Section titled “function_wrap_schema”def function_wrap_schema(
schema: core_schema.WrapValidatorFunctionSchema,
) -> JsonSchemaValueGenerates a JSON schema that matches a function-wrap schema.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.WrapValidatorFunctionSchema
The core schema.
default_schema
Section titled “default_schema”def default_schema(schema: core_schema.WithDefaultSchema) -> JsonSchemaValueGenerates a JSON schema that matches a schema with a default value.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.WithDefaultSchema
The core schema.
get_default_value
Section titled “get_default_value”def get_default_value(schema: core_schema.WithDefaultSchema) -> AnyGet 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
Section titled “Returns”Any — The default value to use, or NoDefault if no default value is available.
Parameters
Section titled “Parameters”schema : core_schema.WithDefaultSchema
The 'with-default' core schema.
nullable_schema
Section titled “nullable_schema”def nullable_schema(schema: core_schema.NullableSchema) -> JsonSchemaValueGenerates a JSON schema that matches a schema that allows null values.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.NullableSchema
The core schema.
union_schema
Section titled “union_schema”def union_schema(schema: core_schema.UnionSchema) -> JsonSchemaValueGenerates a JSON schema that matches a schema that allows values matching any of the given schemas.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.UnionSchema
The core schema.
get_union_of_schemas
Section titled “get_union_of_schemas”def get_union_of_schemas(schemas: list[JsonSchemaValue]) -> JsonSchemaValueReturns the JSON Schema representation for the union of the provided JSON Schemas.
The result depends on the configured 'union_format'.
Returns
Section titled “Returns”JsonSchemaValue — The JSON Schema representing the union of schemas.
Parameters
Section titled “Parameters”schemas : list[JsonSchemaValue]
The list of JSON Schemas to be included in the union.
tagged_union_schema
Section titled “tagged_union_schema”def tagged_union_schema(schema: core_schema.TaggedUnionSchema) -> JsonSchemaValueGenerates 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
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.TaggedUnionSchema
The core schema.
chain_schema
Section titled “chain_schema”def chain_schema(schema: core_schema.ChainSchema) -> JsonSchemaValueGenerates 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
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.ChainSchema
The core schema.
lax_or_strict_schema
Section titled “lax_or_strict_schema”def lax_or_strict_schema(schema: core_schema.LaxOrStrictSchema) -> JsonSchemaValueGenerates a JSON schema that matches a schema that allows values matching either the lax schema or the strict schema.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.LaxOrStrictSchema
The core schema.
json_or_python_schema
Section titled “json_or_python_schema”def json_or_python_schema(schema: core_schema.JsonOrPythonSchema) -> JsonSchemaValueGenerates 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
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.JsonOrPythonSchema
The core schema.
typed_dict_schema
Section titled “typed_dict_schema”def typed_dict_schema(schema: core_schema.TypedDictSchema) -> JsonSchemaValueGenerates a JSON schema that matches a schema that defines a typed dict.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.TypedDictSchema
The core schema.
typed_dict_field_schema
Section titled “typed_dict_field_schema”def typed_dict_field_schema(schema: core_schema.TypedDictField) -> JsonSchemaValueGenerates a JSON schema that matches a schema that defines a typed dict field.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.TypedDictField
The core schema.
dataclass_field_schema
Section titled “dataclass_field_schema”def dataclass_field_schema(schema: core_schema.DataclassField) -> JsonSchemaValueGenerates a JSON schema that matches a schema that defines a dataclass field.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.DataclassField
The core schema.
model_field_schema
Section titled “model_field_schema”def model_field_schema(schema: core_schema.ModelField) -> JsonSchemaValueGenerates a JSON schema that matches a schema that defines a model field.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.ModelField
The core schema.
computed_field_schema
Section titled “computed_field_schema”def computed_field_schema(schema: core_schema.ComputedField) -> JsonSchemaValueGenerates a JSON schema that matches a schema that defines a computed field.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.ComputedField
The core schema.
model_schema
Section titled “model_schema”def model_schema(schema: core_schema.ModelSchema) -> JsonSchemaValueGenerates a JSON schema that matches a schema that defines a model.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.ModelSchema
The core schema.
resolve_ref_schema
Section titled “resolve_ref_schema”def resolve_ref_schema(json_schema: JsonSchemaValue) -> JsonSchemaValueResolve a JsonSchemaValue to the non-ref schema if it is a $ref schema.
Returns
Section titled “Returns”JsonSchemaValue — The resolved schema.
Parameters
Section titled “Parameters”json_schema : JsonSchemaValue
The schema to resolve.
Raises
Section titled “Raises”RuntimeError— If the schema reference can’t be found in definitions.
model_fields_schema
Section titled “model_fields_schema”def model_fields_schema(schema: core_schema.ModelFieldsSchema) -> JsonSchemaValueGenerates a JSON schema that matches a schema that defines a model’s fields.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.ModelFieldsSchema
The core schema.
field_is_present
Section titled “field_is_present”def field_is_present(field: CoreSchemaField) -> boolWhether the field should be included in the generated JSON schema.
Returns
Section titled “Returns”bool — True if the field should be included in the generated JSON schema, False otherwise.
Parameters
Section titled “Parameters”field : CoreSchemaField
The schema for the field itself.
field_is_required
Section titled “field_is_required”def field_is_required(
field: core_schema.ModelField | core_schema.DataclassField | core_schema.TypedDictField,
total: bool,
) -> boolWhether 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
Section titled “Returns”bool — True if the field should be marked as required in the generated JSON schema, False otherwise.
Parameters
Section titled “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
Section titled “dataclass_args_schema”def dataclass_args_schema(schema: core_schema.DataclassArgsSchema) -> JsonSchemaValueGenerates a JSON schema that matches a schema that defines a dataclass’s constructor arguments.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.DataclassArgsSchema
The core schema.
dataclass_schema
Section titled “dataclass_schema”def dataclass_schema(schema: core_schema.DataclassSchema) -> JsonSchemaValueGenerates a JSON schema that matches a schema that defines a dataclass.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.DataclassSchema
The core schema.
arguments_schema
Section titled “arguments_schema”def arguments_schema(schema: core_schema.ArgumentsSchema) -> JsonSchemaValueGenerates a JSON schema that matches a schema that defines a function’s arguments.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.ArgumentsSchema
The core schema.
kw_arguments_schema
Section titled “kw_arguments_schema”def kw_arguments_schema(
arguments: list[core_schema.ArgumentsParameter],
var_kwargs_schema: CoreSchema | None,
) -> JsonSchemaValueGenerates a JSON schema that matches a schema that defines a function’s keyword arguments.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”arguments : list[core_schema.ArgumentsParameter]
The core schema.
p_arguments_schema
Section titled “p_arguments_schema”def p_arguments_schema(
arguments: list[core_schema.ArgumentsParameter],
var_args_schema: CoreSchema | None,
) -> JsonSchemaValueGenerates a JSON schema that matches a schema that defines a function’s positional arguments.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”arguments : list[core_schema.ArgumentsParameter]
The core schema.
get_argument_name
Section titled “get_argument_name”def get_argument_name(
argument: core_schema.ArgumentsParameter | core_schema.ArgumentsV3Parameter,
) -> strRetrieves the name of an argument.
Returns
Section titled “Returns”str — The name of the argument.
Parameters
Section titled “Parameters”argument : core_schema.ArgumentsParameter | core_schema.ArgumentsV3Parameter
The core schema.
arguments_v3_schema
Section titled “arguments_v3_schema”def arguments_v3_schema(schema: core_schema.ArgumentsV3Schema) -> JsonSchemaValueGenerates a JSON schema that matches a schema that defines a function’s arguments.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.ArgumentsV3Schema
The core schema.
call_schema
Section titled “call_schema”def call_schema(schema: core_schema.CallSchema) -> JsonSchemaValueGenerates a JSON schema that matches a schema that defines a function call.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.CallSchema
The core schema.
custom_error_schema
Section titled “custom_error_schema”def custom_error_schema(schema: core_schema.CustomErrorSchema) -> JsonSchemaValueGenerates a JSON schema that matches a schema that defines a custom error.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.CustomErrorSchema
The core schema.
json_schema
Section titled “json_schema”def json_schema(schema: core_schema.JsonSchema) -> JsonSchemaValueGenerates a JSON schema that matches a schema that defines a JSON object.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.JsonSchema
The core schema.
url_schema
Section titled “url_schema”def url_schema(schema: core_schema.UrlSchema) -> JsonSchemaValueGenerates a JSON schema that matches a schema that defines a URL.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.UrlSchema
The core schema.
multi_host_url_schema
Section titled “multi_host_url_schema”def multi_host_url_schema(schema: core_schema.MultiHostUrlSchema) -> JsonSchemaValueGenerates a JSON schema that matches a schema that defines a URL that can be used with multiple hosts.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.MultiHostUrlSchema
The core schema.
uuid_schema
Section titled “uuid_schema”def uuid_schema(schema: core_schema.UuidSchema) -> JsonSchemaValueGenerates a JSON schema that matches a UUID.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.UuidSchema
The core schema.
definitions_schema
Section titled “definitions_schema”def definitions_schema(schema: core_schema.DefinitionsSchema) -> JsonSchemaValueGenerates a JSON schema that matches a schema that defines a JSON object with definitions.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.DefinitionsSchema
The core schema.
definition_ref_schema
Section titled “definition_ref_schema”def definition_ref_schema(
schema: core_schema.DefinitionReferenceSchema,
) -> JsonSchemaValueGenerates a JSON schema that matches a schema that references a definition.
Returns
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.DefinitionReferenceSchema
The core schema.
ser_schema
Section titled “ser_schema”def ser_schema(
schema: core_schema.SerSchema | core_schema.IncExSeqSerSchema | core_schema.IncExDictSerSchema,
) -> JsonSchemaValue | NoneGenerates a JSON schema that matches a schema that defines a serialized object.
Returns
Section titled “Returns”JsonSchemaValue | None — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.SerSchema | core_schema.IncExSeqSerSchema | core_schema.IncExDictSerSchema
The core schema.
complex_schema
Section titled “complex_schema”def complex_schema(schema: core_schema.ComplexSchema) -> JsonSchemaValueGenerates 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
Section titled “Returns”JsonSchemaValue — The generated JSON schema.
Parameters
Section titled “Parameters”schema : core_schema.ComplexSchema
The core schema.
get_title_from_name
Section titled “get_title_from_name”def get_title_from_name(name: str) -> strRetrieves a title from a name.
Returns
Section titled “Returns”str — The title.
Parameters
Section titled “Parameters”name : str
The name to retrieve a title from.
field_title_should_be_set
Section titled “field_title_should_be_set”def field_title_should_be_set(schema: CoreSchemaOrField) -> boolReturns 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
Section titled “Returns”bool — True if the field should have a title set, False otherwise.
Parameters
Section titled “Parameters”schema : CoreSchemaOrField
The schema to check.
normalize_name
Section titled “normalize_name”def normalize_name(name: str) -> strNormalizes a name to be used as a key in a dictionary.
Returns
Section titled “Returns”str — The normalized name.
Parameters
Section titled “Parameters”name : str
The name to normalize.
get_defs_ref
Section titled “get_defs_ref”def get_defs_ref(core_mode_ref: CoreModeRef) -> DefsRefOverride this method to change the way that definitions keys are generated from a core reference.
Returns
Section titled “Returns”DefsRef — The definitions key.
Parameters
Section titled “Parameters”core_mode_ref : CoreModeRef
The core reference.
get_cache_defs_ref_schema
Section titled “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
Section titled “Returns”tuple[DefsRef, JsonSchemaValue] — A tuple of the definitions reference and the JSON schema that will refer to it.
Parameters
Section titled “Parameters”core_ref : CoreRef
The core reference to get the definitions reference for.
handle_ref_overrides
Section titled “handle_ref_overrides”def handle_ref_overrides(json_schema: JsonSchemaValue) -> JsonSchemaValueRemove any sibling keys that are redundant with the referenced schema.
Returns
Section titled “Returns”JsonSchemaValue — The schema with redundant sibling keys removed.
Parameters
Section titled “Parameters”json_schema : JsonSchemaValue
The schema to remove redundant sibling keys from.
encode_default
Section titled “encode_default”def encode_default(dft: Any) -> AnyEncode a default value to a JSON-serializable value.
This is used to encode default values for fields in the generated JSON schema.
Returns
Section titled “Returns”Any — The encoded default value.
Parameters
Section titled “Parameters”dft : Any
The default value to encode.
update_with_validations
Section titled “update_with_validations”def update_with_validations(
json_schema: JsonSchemaValue,
core_schema: CoreSchema,
mapping: dict[str, str],
) -> NoneUpdate 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
Section titled “Returns”Parameters
Section titled “Parameters”json_schema : JsonSchemaValue
The JSON schema to update.
core_schema : CoreSchema
The core schema to get the validations from.
A mapping from core_schema attribute names to the corresponding JSON schema attribute names.
get_json_ref_counts
Section titled “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
Section titled “Returns”emit_warning
Section titled “emit_warning”def emit_warning(kind: JsonSchemaWarningKind, detail: str) -> NoneThis method simply emits PydanticJsonSchemaWarnings based on handling in the warning_message method.
Returns
Section titled “Returns”render_warning_message
Section titled “render_warning_message”def render_warning_message(kind: JsonSchemaWarningKind, detail: str) -> str | NoneThis 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
Section titled “Returns”str | None — The formatted warning message, or None if no warning should be emitted.
Parameters
Section titled “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
Section titled “WithJsonSchema”An annotation used to override the JSON Schema for a type.
This is useful when you want to set a JSON Schema for a type that don’t produce any JSON Schemas by default (e.g. Callable).
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
Section titled “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
Section titled “SkipJsonSchema”Add this as an annotation on a field to skip generating a JSON schema for that field.
model_json_schema
Section titled “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
Section titled “Returns”dict[str, Any] — The generated JSON Schema.
Parameters
Section titled “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 theanyOfkeyword to combine schemas (the default).'primitive_type_array': Use thetypekeyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string,boolean,null,integerornumber) or contains constraints/metadata, falls back toany_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
Section titled “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
Section titled “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
Section titled “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 theanyOfkeyword to combine schemas (the default).'primitive_type_array': Use thetypekeyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string,boolean,null,integerornumber) or contains constraints/metadata, falls back toany_of.
schema_generator : type[GenerateJsonSchema] Default: GenerateJsonSchema
The schema generator to use for generating the JSON Schema.
CoreSchemaOrFieldType
Section titled “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
Section titled “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
Section titled “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
Section titled “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
Section titled “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
Section titled “DEFAULT_REF_TEMPLATE”The default format string used to generate reference names.
Default: '#/$defs/{model}'
Was this page helpful?