json_schema.py 123 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911
  1. """!!! abstract "Usage Documentation"
  2. [JSON Schema](../concepts/json_schema.md)
  3. The `json_schema` module contains classes and functions to allow the way [JSON Schema](https://json-schema.org/)
  4. is generated to be customized.
  5. In general you shouldn't need to use this module directly; instead, you can use
  6. [`BaseModel.model_json_schema`][pydantic.BaseModel.model_json_schema] and
  7. [`TypeAdapter.json_schema`][pydantic.TypeAdapter.json_schema].
  8. """
  9. from __future__ import annotations as _annotations
  10. import collections.abc
  11. import dataclasses
  12. import inspect
  13. import math
  14. import os
  15. import re
  16. import warnings
  17. from collections import Counter, defaultdict
  18. from collections.abc import Hashable, Iterable, Sequence
  19. from copy import deepcopy
  20. from enum import Enum
  21. from re import Pattern
  22. from typing import (
  23. TYPE_CHECKING,
  24. Annotated,
  25. Any,
  26. Callable,
  27. Literal,
  28. NewType,
  29. TypeVar,
  30. Union,
  31. cast,
  32. overload,
  33. )
  34. import pydantic_core
  35. from pydantic_core import MISSING, CoreSchema, PydanticOmit, core_schema, to_jsonable_python
  36. from pydantic_core.core_schema import ComputedField
  37. from typing_extensions import TypeAlias, assert_never, deprecated, final
  38. from typing_inspection.introspection import get_literal_values
  39. from pydantic.warnings import PydanticDeprecatedSince26, PydanticDeprecatedSince29
  40. from ._internal import (
  41. _config,
  42. _core_metadata,
  43. _core_utils,
  44. _decorators,
  45. _internal_dataclass,
  46. _mock_val_ser,
  47. _schema_generation_shared,
  48. _typing_extra,
  49. )
  50. from .annotated_handlers import GetJsonSchemaHandler
  51. from .config import JsonDict, JsonValue
  52. from .errors import PydanticInvalidForJsonSchema, PydanticSchemaGenerationError, PydanticUserError
  53. if TYPE_CHECKING:
  54. from . import ConfigDict
  55. from ._internal._core_utils import CoreSchemaField, CoreSchemaOrField
  56. from ._internal._dataclasses import PydanticDataclass
  57. from ._internal._schema_generation_shared import GetJsonSchemaFunction
  58. from .main import BaseModel
  59. CoreSchemaOrFieldType = Literal[core_schema.CoreSchemaType, core_schema.CoreSchemaFieldType]
  60. """
  61. A type alias for defined schema types that represents a union of
  62. `core_schema.CoreSchemaType` and
  63. `core_schema.CoreSchemaFieldType`.
  64. """
  65. JsonSchemaValue = dict[str, Any]
  66. """
  67. A type alias for a JSON schema value. This is a dictionary of string keys to arbitrary JSON values.
  68. """
  69. JsonSchemaMode = Literal['validation', 'serialization']
  70. """
  71. A type alias that represents the mode of a JSON schema; either 'validation' or 'serialization'.
  72. For some types, the inputs to validation differ from the outputs of serialization. For example,
  73. computed fields will only be present when serializing, and should not be provided when
  74. validating. This flag provides a way to indicate whether you want the JSON schema required
  75. for validation inputs, or that will be matched by serialization outputs.
  76. """
  77. _MODE_TITLE_MAPPING: dict[JsonSchemaMode, str] = {'validation': 'Input', 'serialization': 'Output'}
  78. JsonSchemaWarningKind = Literal['skipped-choice', 'non-serializable-default', 'skipped-discriminator']
  79. """
  80. A type alias representing the kinds of warnings that can be emitted during JSON schema generation.
  81. See [`GenerateJsonSchema.render_warning_message`][pydantic.json_schema.GenerateJsonSchema.render_warning_message]
  82. for more details.
  83. """
  84. class PydanticJsonSchemaWarning(UserWarning):
  85. """This class is used to emit warnings produced during JSON schema generation.
  86. See the [`GenerateJsonSchema.emit_warning`][pydantic.json_schema.GenerateJsonSchema.emit_warning] and
  87. [`GenerateJsonSchema.render_warning_message`][pydantic.json_schema.GenerateJsonSchema.render_warning_message]
  88. methods for more details; these can be overridden to control warning behavior.
  89. """
  90. NoDefault = object()
  91. """A sentinel value used to indicate that no default value should be used when generating a JSON Schema
  92. for a core schema with a default value.
  93. """
  94. # ##### JSON Schema Generation #####
  95. DEFAULT_REF_TEMPLATE = '#/$defs/{model}'
  96. """The default format string used to generate reference names."""
  97. # There are three types of references relevant to building JSON schemas:
  98. # 1. core_schema "ref" values; these are not exposed as part of the JSON schema
  99. # * these might look like the fully qualified path of a model, its id, or something similar
  100. CoreRef = NewType('CoreRef', str)
  101. # 2. keys of the "definitions" object that will eventually go into the JSON schema
  102. # * by default, these look like "MyModel", though may change in the presence of collisions
  103. # * eventually, we may want to make it easier to modify the way these names are generated
  104. DefsRef = NewType('DefsRef', str)
  105. # 3. the values corresponding to the "$ref" key in the schema
  106. # * By default, these look like "#/$defs/MyModel", as in {"$ref": "#/$defs/MyModel"}
  107. JsonRef = NewType('JsonRef', str)
  108. CoreModeRef = tuple[CoreRef, JsonSchemaMode]
  109. JsonSchemaKeyT = TypeVar('JsonSchemaKeyT', bound=Hashable)
  110. _PRIMITIVE_JSON_SCHEMA_TYPES = ('string', 'boolean', 'null', 'integer', 'number')
  111. @dataclasses.dataclass(**_internal_dataclass.slots_true)
  112. class _DefinitionsRemapping:
  113. defs_remapping: dict[DefsRef, DefsRef]
  114. json_remapping: dict[JsonRef, JsonRef]
  115. @staticmethod
  116. def from_prioritized_choices(
  117. prioritized_choices: dict[DefsRef, list[DefsRef]],
  118. defs_to_json: dict[DefsRef, JsonRef],
  119. definitions: dict[DefsRef, JsonSchemaValue],
  120. ) -> _DefinitionsRemapping:
  121. """
  122. This function should produce a remapping that replaces complex DefsRef with the simpler ones from the
  123. prioritized_choices such that applying the name remapping would result in an equivalent JSON schema.
  124. """
  125. # We need to iteratively simplify the definitions until we reach a fixed point.
  126. # The reason for this is that outer definitions may reference inner definitions that get simplified
  127. # into an equivalent reference, and the outer definitions won't be equivalent until we've simplified
  128. # the inner definitions.
  129. copied_definitions = deepcopy(definitions)
  130. definitions_schema = {'$defs': copied_definitions}
  131. for _iter in range(100): # prevent an infinite loop in the case of a bug, 100 iterations should be enough
  132. # For every possible remapped DefsRef, collect all schemas that DefsRef might be used for:
  133. schemas_for_alternatives: dict[DefsRef, list[JsonSchemaValue]] = defaultdict(list)
  134. for defs_ref in copied_definitions:
  135. alternatives = prioritized_choices[defs_ref]
  136. for alternative in alternatives:
  137. schemas_for_alternatives[alternative].append(copied_definitions[defs_ref])
  138. # Deduplicate the schemas for each alternative; the idea is that we only want to remap to a new DefsRef
  139. # if it introduces no ambiguity, i.e., there is only one distinct schema for that DefsRef.
  140. for defs_ref in schemas_for_alternatives:
  141. schemas_for_alternatives[defs_ref] = _deduplicate_schemas(schemas_for_alternatives[defs_ref])
  142. # Build the remapping
  143. defs_remapping: dict[DefsRef, DefsRef] = {}
  144. json_remapping: dict[JsonRef, JsonRef] = {}
  145. for original_defs_ref in definitions:
  146. alternatives = prioritized_choices[original_defs_ref]
  147. # Pick the first alternative that has only one schema, since that means there is no collision
  148. remapped_defs_ref = next(x for x in alternatives if len(schemas_for_alternatives[x]) == 1)
  149. defs_remapping[original_defs_ref] = remapped_defs_ref
  150. # Map all alternatives after the remapped one to the remapped one
  151. # This ensures that intermediate simplifications are also remapped
  152. remapped_index = alternatives.index(remapped_defs_ref)
  153. for alt in alternatives[remapped_index:]:
  154. json_remapping[defs_to_json[alt]] = defs_to_json[remapped_defs_ref]
  155. remapping = _DefinitionsRemapping(defs_remapping, json_remapping)
  156. new_definitions_schema = remapping.remap_json_schema({'$defs': copied_definitions})
  157. if definitions_schema == new_definitions_schema:
  158. # We've reached the fixed point
  159. return remapping
  160. definitions_schema = new_definitions_schema
  161. raise PydanticInvalidForJsonSchema('Failed to simplify the JSON schema definitions')
  162. def remap_defs_ref(self, ref: DefsRef) -> DefsRef:
  163. return self.defs_remapping.get(ref, ref)
  164. def remap_json_ref(self, ref: JsonRef) -> JsonRef:
  165. return self.json_remapping.get(ref, ref)
  166. def remap_json_schema(self, schema: Any) -> Any:
  167. """
  168. Recursively update the JSON schema replacing all $refs
  169. """
  170. if isinstance(schema, str):
  171. # Note: this may not really be a JsonRef; we rely on having no collisions between JsonRefs and other strings
  172. return self.remap_json_ref(JsonRef(schema))
  173. elif isinstance(schema, list):
  174. return [self.remap_json_schema(item) for item in schema]
  175. elif isinstance(schema, dict):
  176. for key, value in schema.items():
  177. if key == '$ref' and isinstance(value, str):
  178. schema['$ref'] = self.remap_json_ref(JsonRef(value))
  179. elif key == '$defs':
  180. schema['$defs'] = {
  181. self.remap_defs_ref(DefsRef(key)): self.remap_json_schema(value)
  182. for key, value in schema['$defs'].items()
  183. }
  184. else:
  185. schema[key] = self.remap_json_schema(value)
  186. return schema
  187. class GenerateJsonSchema:
  188. """!!! abstract "Usage Documentation"
  189. [Customizing the JSON Schema Generation Process](../concepts/json_schema.md#customizing-the-json-schema-generation-process)
  190. A class for generating JSON schemas.
  191. This class generates JSON schemas based on configured parameters. The default schema dialect
  192. is [https://json-schema.org/draft/2020-12/schema](https://json-schema.org/draft/2020-12/schema).
  193. The class uses `by_alias` to configure how fields with
  194. multiple names are handled and `ref_template` to format reference names.
  195. Attributes:
  196. schema_dialect: The JSON schema dialect used to generate the schema. See
  197. [Declaring a Dialect](https://json-schema.org/understanding-json-schema/reference/schema.html#id4)
  198. in the JSON Schema documentation for more information about dialects.
  199. ignored_warning_kinds: Warnings to ignore when generating the schema. `self.render_warning_message` will
  200. do nothing if its argument `kind` is in `ignored_warning_kinds`;
  201. this value can be modified on subclasses to easily control which warnings are emitted.
  202. by_alias: Whether to use field aliases when generating the schema.
  203. ref_template: The format string used when generating reference names.
  204. core_to_json_refs: A mapping of core refs to JSON refs.
  205. core_to_defs_refs: A mapping of core refs to definition refs.
  206. defs_to_core_refs: A mapping of definition refs to core refs.
  207. json_to_defs_refs: A mapping of JSON refs to definition refs.
  208. definitions: Definitions in the schema.
  209. Args:
  210. by_alias: Whether to use field aliases in the generated schemas.
  211. ref_template: The format string to use when generating reference names.
  212. union_format: The format to use when combining schemas from unions together. Can be one of:
  213. - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
  214. keyword to combine schemas (the default).
  215. - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
  216. keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
  217. type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
  218. `any_of`.
  219. Raises:
  220. JsonSchemaError: If the instance of the class is inadvertently reused after generating a schema.
  221. """
  222. schema_dialect = 'https://json-schema.org/draft/2020-12/schema'
  223. # `self.render_warning_message` will do nothing if its argument `kind` is in `ignored_warning_kinds`;
  224. # this value can be modified on subclasses to easily control which warnings are emitted
  225. ignored_warning_kinds: set[JsonSchemaWarningKind] = {'skipped-choice'}
  226. def __init__(
  227. self,
  228. by_alias: bool = True,
  229. ref_template: str = DEFAULT_REF_TEMPLATE,
  230. union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
  231. ) -> None:
  232. self.by_alias = by_alias
  233. self.ref_template = ref_template
  234. self.union_format: Literal['any_of', 'primitive_type_array'] = union_format
  235. self.core_to_json_refs: dict[CoreModeRef, JsonRef] = {}
  236. self.core_to_defs_refs: dict[CoreModeRef, DefsRef] = {}
  237. self.defs_to_core_refs: dict[DefsRef, CoreModeRef] = {}
  238. self.json_to_defs_refs: dict[JsonRef, DefsRef] = {}
  239. self.definitions: dict[DefsRef, JsonSchemaValue] = {}
  240. self._config_wrapper_stack = _config.ConfigWrapperStack(_config.ConfigWrapper({}))
  241. self._mode: JsonSchemaMode = 'validation'
  242. # The following includes a mapping of a fully-unique defs ref choice to a list of preferred
  243. # alternatives, which are generally simpler, such as only including the class name.
  244. # At the end of schema generation, we use these to produce a JSON schema with more human-readable
  245. # definitions, which would also work better in a generated OpenAPI client, etc.
  246. self._prioritized_defsref_choices: dict[DefsRef, list[DefsRef]] = {}
  247. self._collision_counter: dict[str, int] = defaultdict(int)
  248. self._collision_index: dict[str, int] = {}
  249. self._schema_type_to_method = self.build_schema_type_to_method()
  250. # When we encounter definitions we need to try to build them immediately
  251. # so that they are available schemas that reference them
  252. # But it's possible that CoreSchema was never going to be used
  253. # (e.g. because the CoreSchema that references short circuits is JSON schema generation without needing
  254. # the reference) so instead of failing altogether if we can't build a definition we
  255. # store the error raised and re-throw it if we end up needing that def
  256. self._core_defs_invalid_for_json_schema: dict[DefsRef, PydanticInvalidForJsonSchema] = {}
  257. # This changes to True after generating a schema, to prevent issues caused by accidental reuse
  258. # of a single instance of a schema generator
  259. self._used = False
  260. @property
  261. def _config(self) -> _config.ConfigWrapper:
  262. return self._config_wrapper_stack.tail
  263. @property
  264. def mode(self) -> JsonSchemaMode:
  265. if self._config.json_schema_mode_override is not None:
  266. return self._config.json_schema_mode_override
  267. else:
  268. return self._mode
  269. def build_schema_type_to_method(
  270. self,
  271. ) -> dict[CoreSchemaOrFieldType, Callable[[CoreSchemaOrField], JsonSchemaValue]]:
  272. """Builds a dictionary mapping fields to methods for generating JSON schemas.
  273. Returns:
  274. A dictionary containing the mapping of `CoreSchemaOrFieldType` to a handler method.
  275. Raises:
  276. TypeError: If no method has been defined for generating a JSON schema for a given pydantic core schema type.
  277. """
  278. mapping: dict[CoreSchemaOrFieldType, Callable[[CoreSchemaOrField], JsonSchemaValue]] = {}
  279. core_schema_types: list[CoreSchemaOrFieldType] = list(get_literal_values(CoreSchemaOrFieldType))
  280. for key in core_schema_types:
  281. method_name = f'{key.replace("-", "_")}_schema'
  282. try:
  283. mapping[key] = getattr(self, method_name)
  284. except AttributeError as e: # pragma: no cover
  285. if os.getenv('PYDANTIC_PRIVATE_ALLOW_UNHANDLED_SCHEMA_TYPES'):
  286. continue
  287. raise TypeError(
  288. f'No method for generating JsonSchema for core_schema.type={key!r} '
  289. f'(expected: {type(self).__name__}.{method_name})'
  290. ) from e
  291. return mapping
  292. def generate_definitions(
  293. self, inputs: Sequence[tuple[JsonSchemaKeyT, JsonSchemaMode, core_schema.CoreSchema]]
  294. ) -> tuple[dict[tuple[JsonSchemaKeyT, JsonSchemaMode], JsonSchemaValue], dict[DefsRef, JsonSchemaValue]]:
  295. """Generates JSON schema definitions from a list of core schemas, pairing the generated definitions with a
  296. mapping that links the input keys to the definition references.
  297. Args:
  298. inputs: A sequence of tuples, where:
  299. - The first element is a JSON schema key type.
  300. - The second element is the JSON mode: either 'validation' or 'serialization'.
  301. - The third element is a core schema.
  302. Returns:
  303. A tuple where:
  304. - The first element is a dictionary whose keys are tuples of JSON schema key type and JSON mode, and
  305. whose values are the JSON schema corresponding to that pair of inputs. (These schemas may have
  306. JsonRef references to definitions that are defined in the second returned element.)
  307. - The second element is a dictionary whose keys are definition references for the JSON schemas
  308. from the first returned element, and whose values are the actual JSON schema definitions.
  309. Raises:
  310. PydanticUserError: Raised if the JSON schema generator has already been used to generate a JSON schema.
  311. """
  312. if self._used:
  313. raise PydanticUserError(
  314. 'This JSON schema generator has already been used to generate a JSON schema. '
  315. f'You must create a new instance of {type(self).__name__} to generate a new JSON schema.',
  316. code='json-schema-already-used',
  317. )
  318. for _, mode, schema in inputs:
  319. self._mode = mode
  320. self.generate_inner(schema)
  321. definitions_remapping = self._build_definitions_remapping()
  322. json_schemas_map: dict[tuple[JsonSchemaKeyT, JsonSchemaMode], DefsRef] = {}
  323. for key, mode, schema in inputs:
  324. self._mode = mode
  325. json_schema = self.generate_inner(schema)
  326. json_schemas_map[(key, mode)] = definitions_remapping.remap_json_schema(json_schema)
  327. json_schema = {'$defs': self.definitions}
  328. json_schema = definitions_remapping.remap_json_schema(json_schema)
  329. self._used = True
  330. return json_schemas_map, self.sort(json_schema['$defs']) # type: ignore
  331. def generate(self, schema: CoreSchema, mode: JsonSchemaMode = 'validation') -> JsonSchemaValue:
  332. """Generates a JSON schema for a specified schema in a specified mode.
  333. Args:
  334. schema: A Pydantic model.
  335. mode: The mode in which to generate the schema. Defaults to 'validation'.
  336. Returns:
  337. A JSON schema representing the specified schema.
  338. Raises:
  339. PydanticUserError: If the JSON schema generator has already been used to generate a JSON schema.
  340. """
  341. self._mode = mode
  342. if self._used:
  343. raise PydanticUserError(
  344. 'This JSON schema generator has already been used to generate a JSON schema. '
  345. f'You must create a new instance of {type(self).__name__} to generate a new JSON schema.',
  346. code='json-schema-already-used',
  347. )
  348. json_schema: JsonSchemaValue = self.generate_inner(schema)
  349. json_ref_counts = self.get_json_ref_counts(json_schema)
  350. ref = cast(JsonRef, json_schema.get('$ref'))
  351. while ref is not None: # may need to unpack multiple levels
  352. ref_json_schema = self.get_schema_from_definitions(ref)
  353. if json_ref_counts[ref] == 1 and ref_json_schema is not None and len(json_schema) == 1:
  354. # "Unpack" the ref since this is the only reference and there are no sibling keys
  355. json_schema = ref_json_schema.copy() # copy to prevent recursive dict reference
  356. json_ref_counts[ref] -= 1
  357. ref = cast(JsonRef, json_schema.get('$ref'))
  358. ref = None
  359. self._garbage_collect_definitions(json_schema)
  360. definitions_remapping = self._build_definitions_remapping()
  361. if self.definitions:
  362. json_schema['$defs'] = self.definitions
  363. json_schema = definitions_remapping.remap_json_schema(json_schema)
  364. # For now, we will not set the $schema key. However, if desired, this can be easily added by overriding
  365. # this method and adding the following line after a call to super().generate(schema):
  366. # json_schema['$schema'] = self.schema_dialect
  367. self._used = True
  368. return self.sort(json_schema)
  369. def generate_inner(self, schema: CoreSchemaOrField) -> JsonSchemaValue: # noqa: C901
  370. """Generates a JSON schema for a given core schema.
  371. Args:
  372. schema: The given core schema.
  373. Returns:
  374. The generated JSON schema.
  375. TODO: the nested function definitions here seem like bad practice, I'd like to unpack these
  376. in a future PR. It'd be great if we could shorten the call stack a bit for JSON schema generation,
  377. and I think there's potential for that here.
  378. """
  379. # If a schema with the same CoreRef has been handled, just return a reference to it
  380. # Note that this assumes that it will _never_ be the case that the same CoreRef is used
  381. # on types that should have different JSON schemas
  382. if 'ref' in schema:
  383. core_ref = CoreRef(schema['ref']) # type: ignore[typeddict-item]
  384. core_mode_ref = (core_ref, self.mode)
  385. if core_mode_ref in self.core_to_defs_refs and self.core_to_defs_refs[core_mode_ref] in self.definitions:
  386. return {'$ref': self.core_to_json_refs[core_mode_ref]}
  387. def populate_defs(core_schema: CoreSchema, json_schema: JsonSchemaValue) -> JsonSchemaValue:
  388. if 'ref' in core_schema:
  389. core_ref = CoreRef(core_schema['ref']) # type: ignore[typeddict-item]
  390. defs_ref, ref_json_schema = self.get_cache_defs_ref_schema(core_ref)
  391. json_ref = JsonRef(ref_json_schema['$ref'])
  392. # Replace the schema if it's not a reference to itself
  393. # What we want to avoid is having the def be just a ref to itself
  394. # which is what would happen if we blindly assigned any
  395. if json_schema.get('$ref', None) != json_ref:
  396. self.definitions[defs_ref] = json_schema
  397. self._core_defs_invalid_for_json_schema.pop(defs_ref, None)
  398. json_schema = ref_json_schema
  399. return json_schema
  400. def handler_func(schema_or_field: CoreSchemaOrField) -> JsonSchemaValue:
  401. """Generate a JSON schema based on the input schema.
  402. Args:
  403. schema_or_field: The core schema to generate a JSON schema from.
  404. Returns:
  405. The generated JSON schema.
  406. Raises:
  407. TypeError: If an unexpected schema type is encountered.
  408. """
  409. # Generate the core-schema-type-specific bits of the schema generation:
  410. json_schema: JsonSchemaValue | None = None
  411. if self.mode == 'serialization' and 'serialization' in schema_or_field:
  412. # In this case, we skip the JSON Schema generation of the schema
  413. # and use the `'serialization'` schema instead (canonical example:
  414. # `Annotated[int, PlainSerializer(str)]`).
  415. ser_schema = schema_or_field['serialization'] # type: ignore
  416. json_schema = self.ser_schema(ser_schema)
  417. # It might be that the 'serialization'` is skipped depending on `when_used`.
  418. # This is only relevant for `nullable` schemas though, so we special case here.
  419. if (
  420. json_schema is not None
  421. and ser_schema.get('when_used') in ('unless-none', 'json-unless-none')
  422. and schema_or_field['type'] == 'nullable'
  423. ):
  424. json_schema = self.get_union_of_schemas([{'type': 'null'}, json_schema])
  425. if json_schema is None:
  426. if _core_utils.is_core_schema(schema_or_field) or _core_utils.is_core_schema_field(schema_or_field):
  427. generate_for_schema_type = self._schema_type_to_method[schema_or_field['type']]
  428. json_schema = generate_for_schema_type(schema_or_field)
  429. else:
  430. raise TypeError(f'Unexpected schema type: schema={schema_or_field}')
  431. return json_schema
  432. current_handler = _schema_generation_shared.GenerateJsonSchemaHandler(self, handler_func)
  433. metadata = cast(_core_metadata.CoreMetadata, schema.get('metadata', {}))
  434. # TODO: I dislike that we have to wrap these basic dict updates in callables, is there any way around this?
  435. if js_updates := metadata.get('pydantic_js_updates'):
  436. def js_updates_handler_func(
  437. schema_or_field: CoreSchemaOrField,
  438. current_handler: GetJsonSchemaHandler = current_handler,
  439. ) -> JsonSchemaValue:
  440. json_schema = {**current_handler(schema_or_field), **js_updates}
  441. return json_schema
  442. current_handler = _schema_generation_shared.GenerateJsonSchemaHandler(self, js_updates_handler_func)
  443. if js_extra := metadata.get('pydantic_js_extra'):
  444. def js_extra_handler_func(
  445. schema_or_field: CoreSchemaOrField,
  446. current_handler: GetJsonSchemaHandler = current_handler,
  447. ) -> JsonSchemaValue:
  448. json_schema = current_handler(schema_or_field)
  449. if isinstance(js_extra, dict):
  450. json_schema.update(to_jsonable_python(js_extra))
  451. elif callable(js_extra):
  452. # similar to typing issue in _update_class_schema when we're working with callable js extra
  453. js_extra(json_schema) # type: ignore
  454. return json_schema
  455. current_handler = _schema_generation_shared.GenerateJsonSchemaHandler(self, js_extra_handler_func)
  456. for js_modify_function in metadata.get('pydantic_js_functions', ()):
  457. def new_handler_func(
  458. schema_or_field: CoreSchemaOrField,
  459. current_handler: GetJsonSchemaHandler = current_handler,
  460. js_modify_function: GetJsonSchemaFunction = js_modify_function,
  461. ) -> JsonSchemaValue:
  462. json_schema = js_modify_function(schema_or_field, current_handler)
  463. if _core_utils.is_core_schema(schema_or_field):
  464. json_schema = populate_defs(schema_or_field, json_schema)
  465. original_schema = current_handler.resolve_ref_schema(json_schema)
  466. ref = json_schema.pop('$ref', None)
  467. if ref and json_schema:
  468. original_schema.update(json_schema)
  469. return original_schema
  470. current_handler = _schema_generation_shared.GenerateJsonSchemaHandler(self, new_handler_func)
  471. for js_modify_function in metadata.get('pydantic_js_annotation_functions', ()):
  472. def new_handler_func(
  473. schema_or_field: CoreSchemaOrField,
  474. current_handler: GetJsonSchemaHandler = current_handler,
  475. js_modify_function: GetJsonSchemaFunction = js_modify_function,
  476. ) -> JsonSchemaValue:
  477. return js_modify_function(schema_or_field, current_handler)
  478. current_handler = _schema_generation_shared.GenerateJsonSchemaHandler(self, new_handler_func)
  479. json_schema = current_handler(schema)
  480. if _core_utils.is_core_schema(schema):
  481. json_schema = populate_defs(schema, json_schema)
  482. return json_schema
  483. def sort(self, value: JsonSchemaValue, parent_key: str | None = None) -> JsonSchemaValue:
  484. """Override this method to customize the sorting of the JSON schema (e.g., don't sort at all, sort all keys unconditionally, etc.)
  485. By default, alphabetically sort the keys in the JSON schema, skipping the 'properties' and 'default' keys to preserve field definition order.
  486. This sort is recursive, so it will sort all nested dictionaries as well.
  487. """
  488. sorted_dict: dict[str, JsonSchemaValue] = {}
  489. keys = value.keys()
  490. if parent_key not in ('properties', 'default'):
  491. keys = sorted(keys)
  492. for key in keys:
  493. sorted_dict[key] = self._sort_recursive(value[key], parent_key=key)
  494. return sorted_dict
  495. def _sort_recursive(self, value: Any, parent_key: str | None = None) -> Any:
  496. """Recursively sort a JSON schema value."""
  497. if isinstance(value, dict):
  498. sorted_dict: dict[str, JsonSchemaValue] = {}
  499. keys = value.keys()
  500. if parent_key not in ('properties', 'default'):
  501. keys = sorted(keys)
  502. for key in keys:
  503. sorted_dict[key] = self._sort_recursive(value[key], parent_key=key)
  504. return sorted_dict
  505. elif isinstance(value, list):
  506. sorted_list: list[JsonSchemaValue] = [self._sort_recursive(item, parent_key) for item in value]
  507. return sorted_list
  508. else:
  509. return value
  510. # ### Schema generation methods
  511. def invalid_schema(self, schema: core_schema.InvalidSchema) -> JsonSchemaValue:
  512. """Placeholder - should never be called."""
  513. raise RuntimeError('Cannot generate schema for invalid_schema. This is a bug! Please report it.')
  514. def any_schema(self, schema: core_schema.AnySchema) -> JsonSchemaValue:
  515. """Generates a JSON schema that matches any value.
  516. Args:
  517. schema: The core schema.
  518. Returns:
  519. The generated JSON schema.
  520. """
  521. return {}
  522. def none_schema(self, schema: core_schema.NoneSchema) -> JsonSchemaValue:
  523. """Generates a JSON schema that matches `None`.
  524. Args:
  525. schema: The core schema.
  526. Returns:
  527. The generated JSON schema.
  528. """
  529. return {'type': 'null'}
  530. def bool_schema(self, schema: core_schema.BoolSchema) -> JsonSchemaValue:
  531. """Generates a JSON schema that matches a bool value.
  532. Args:
  533. schema: The core schema.
  534. Returns:
  535. The generated JSON schema.
  536. """
  537. return {'type': 'boolean'}
  538. def int_schema(self, schema: core_schema.IntSchema) -> JsonSchemaValue:
  539. """Generates a JSON schema that matches an int value.
  540. Args:
  541. schema: The core schema.
  542. Returns:
  543. The generated JSON schema.
  544. """
  545. json_schema: dict[str, Any] = {'type': 'integer'}
  546. self.update_with_validations(json_schema, schema, self.ValidationsMapping.numeric)
  547. json_schema = {k: v for k, v in json_schema.items() if v not in {math.inf, -math.inf}}
  548. return json_schema
  549. def float_schema(self, schema: core_schema.FloatSchema) -> JsonSchemaValue:
  550. """Generates a JSON schema that matches a float value.
  551. Args:
  552. schema: The core schema.
  553. Returns:
  554. The generated JSON schema.
  555. """
  556. json_schema: dict[str, Any] = {'type': 'number'}
  557. self.update_with_validations(json_schema, schema, self.ValidationsMapping.numeric)
  558. json_schema = {k: v for k, v in json_schema.items() if v not in {math.inf, -math.inf}}
  559. return json_schema
  560. def decimal_schema(self, schema: core_schema.DecimalSchema) -> JsonSchemaValue:
  561. """Generates a JSON schema that matches a decimal value.
  562. Args:
  563. schema: The core schema.
  564. Returns:
  565. The generated JSON schema.
  566. """
  567. def get_decimal_pattern(schema: core_schema.DecimalSchema) -> str:
  568. max_digits = schema.get('max_digits')
  569. decimal_places = schema.get('decimal_places')
  570. pattern = (
  571. r'^(?!^[-+.]*$)[+-]?0*' # check it is not empty string and not one or sequence of ".+-" characters.
  572. )
  573. # Case 1: Both max_digits and decimal_places are set
  574. if max_digits is not None and decimal_places is not None:
  575. integer_places = max(0, max_digits - decimal_places)
  576. pattern += (
  577. rf'(?:'
  578. rf'\d{{0,{integer_places}}}'
  579. rf'|'
  580. rf'(?=[\d.]{{1,{max_digits + 1}}}0*$)'
  581. rf'\d{{0,{integer_places}}}\.\d{{0,{decimal_places}}}0*$'
  582. rf')'
  583. )
  584. # Case 2: Only max_digits is set
  585. elif max_digits is not None and decimal_places is None:
  586. pattern += (
  587. rf'(?:'
  588. rf'\d{{0,{max_digits}}}'
  589. rf'|'
  590. rf'(?=[\d.]{{1,{max_digits + 1}}}0*$)'
  591. rf'\d*\.\d*0*$'
  592. rf')'
  593. )
  594. # Case 3: Only decimal_places is set
  595. elif max_digits is None and decimal_places is not None:
  596. pattern += rf'\d*\.?\d{{0,{decimal_places}}}0*$'
  597. # Case 4: Both are None (no restrictions)
  598. else:
  599. pattern += r'\d*\.?\d*$' # look for arbitrary integer or decimal
  600. return pattern
  601. json_schema = self.str_schema(core_schema.str_schema(pattern=get_decimal_pattern(schema)))
  602. if self.mode == 'validation':
  603. multiple_of = schema.get('multiple_of')
  604. le = schema.get('le')
  605. ge = schema.get('ge')
  606. lt = schema.get('lt')
  607. gt = schema.get('gt')
  608. json_schema = {
  609. 'anyOf': [
  610. self.float_schema(
  611. core_schema.float_schema(
  612. allow_inf_nan=schema.get('allow_inf_nan'),
  613. multiple_of=None if multiple_of is None else float(multiple_of),
  614. le=None if le is None else float(le),
  615. ge=None if ge is None else float(ge),
  616. lt=None if lt is None else float(lt),
  617. gt=None if gt is None else float(gt),
  618. )
  619. ),
  620. json_schema,
  621. ],
  622. }
  623. return json_schema
  624. def str_schema(self, schema: core_schema.StringSchema) -> JsonSchemaValue:
  625. """Generates a JSON schema that matches a string value.
  626. Args:
  627. schema: The core schema.
  628. Returns:
  629. The generated JSON schema.
  630. """
  631. json_schema = {'type': 'string'}
  632. self.update_with_validations(json_schema, schema, self.ValidationsMapping.string)
  633. if isinstance(json_schema.get('pattern'), Pattern):
  634. # TODO: should we add regex flags to the pattern?
  635. json_schema['pattern'] = json_schema.get('pattern').pattern # type: ignore
  636. return json_schema
  637. def bytes_schema(self, schema: core_schema.BytesSchema) -> JsonSchemaValue:
  638. """Generates a JSON schema that matches a bytes value.
  639. Args:
  640. schema: The core schema.
  641. Returns:
  642. The generated JSON schema.
  643. """
  644. json_schema = {'type': 'string', 'format': 'base64url' if self._config.ser_json_bytes == 'base64' else 'binary'}
  645. self.update_with_validations(json_schema, schema, self.ValidationsMapping.bytes)
  646. return json_schema
  647. def date_schema(self, schema: core_schema.DateSchema) -> JsonSchemaValue:
  648. """Generates a JSON schema that matches a date value.
  649. Args:
  650. schema: The core schema.
  651. Returns:
  652. The generated JSON schema.
  653. """
  654. return {'type': 'string', 'format': 'date'}
  655. def time_schema(self, schema: core_schema.TimeSchema) -> JsonSchemaValue:
  656. """Generates a JSON schema that matches a time value.
  657. Args:
  658. schema: The core schema.
  659. Returns:
  660. The generated JSON schema.
  661. """
  662. return {'type': 'string', 'format': 'time'}
  663. def datetime_schema(self, schema: core_schema.DatetimeSchema) -> JsonSchemaValue:
  664. """Generates a JSON schema that matches a datetime value.
  665. Args:
  666. schema: The core schema.
  667. Returns:
  668. The generated JSON schema.
  669. """
  670. return {'type': 'string', 'format': 'date-time'}
  671. def timedelta_schema(self, schema: core_schema.TimedeltaSchema) -> JsonSchemaValue:
  672. """Generates a JSON schema that matches a timedelta value.
  673. Args:
  674. schema: The core schema.
  675. Returns:
  676. The generated JSON schema.
  677. """
  678. if self._config.ser_json_timedelta == 'float':
  679. return {'type': 'number'}
  680. return {'type': 'string', 'format': 'duration'}
  681. def literal_schema(self, schema: core_schema.LiteralSchema) -> JsonSchemaValue:
  682. """Generates a JSON schema that matches a literal value.
  683. Args:
  684. schema: The core schema.
  685. Returns:
  686. The generated JSON schema.
  687. """
  688. expected = [to_jsonable_python(v.value if isinstance(v, Enum) else v) for v in schema['expected']]
  689. result: dict[str, Any] = {}
  690. if len(expected) == 1:
  691. result['const'] = expected[0]
  692. else:
  693. result['enum'] = expected
  694. types = {type(e) for e in expected}
  695. if types == {str}:
  696. result['type'] = 'string'
  697. elif types == {int}:
  698. result['type'] = 'integer'
  699. elif types == {float}:
  700. result['type'] = 'number'
  701. elif types == {bool}:
  702. result['type'] = 'boolean'
  703. elif types == {list}:
  704. result['type'] = 'array'
  705. elif types == {type(None)}:
  706. result['type'] = 'null'
  707. return result
  708. def missing_sentinel_schema(self, schema: core_schema.MissingSentinelSchema) -> JsonSchemaValue:
  709. """Generates a JSON schema that matches the `MISSING` sentinel value.
  710. Args:
  711. schema: The core schema.
  712. Returns:
  713. The generated JSON schema.
  714. """
  715. raise PydanticOmit
  716. def enum_schema(self, schema: core_schema.EnumSchema) -> JsonSchemaValue:
  717. """Generates a JSON schema that matches an Enum value.
  718. Args:
  719. schema: The core schema.
  720. Returns:
  721. The generated JSON schema.
  722. """
  723. enum_type = schema['cls']
  724. description = None if not enum_type.__doc__ else inspect.cleandoc(enum_type.__doc__)
  725. if (
  726. description == 'An enumeration.'
  727. ): # This is the default value provided by enum.EnumMeta.__new__; don't use it
  728. description = None
  729. result: dict[str, Any] = {'title': enum_type.__name__, 'description': description}
  730. result = {k: v for k, v in result.items() if v is not None}
  731. expected = [to_jsonable_python(v.value) for v in schema['members']]
  732. result['enum'] = expected
  733. types = {type(e) for e in expected}
  734. if isinstance(enum_type, str) or types == {str}:
  735. result['type'] = 'string'
  736. elif isinstance(enum_type, int) or types == {int}:
  737. result['type'] = 'integer'
  738. elif isinstance(enum_type, float) or types == {float}:
  739. result['type'] = 'number'
  740. elif types == {bool}:
  741. result['type'] = 'boolean'
  742. elif types == {list}:
  743. result['type'] = 'array'
  744. return result
  745. def is_instance_schema(self, schema: core_schema.IsInstanceSchema) -> JsonSchemaValue:
  746. """Handles JSON schema generation for a core schema that checks if a value is an instance of a class.
  747. Unless overridden in a subclass, this raises an error.
  748. Args:
  749. schema: The core schema.
  750. Returns:
  751. The generated JSON schema.
  752. """
  753. return self.handle_invalid_for_json_schema(schema, f'core_schema.IsInstanceSchema ({schema["cls"]})')
  754. def is_subclass_schema(self, schema: core_schema.IsSubclassSchema) -> JsonSchemaValue:
  755. """Handles JSON schema generation for a core schema that checks if a value is a subclass of a class.
  756. For backwards compatibility with v1, this does not raise an error, but can be overridden to change this.
  757. Args:
  758. schema: The core schema.
  759. Returns:
  760. The generated JSON schema.
  761. """
  762. # Note: This is for compatibility with V1; you can override if you want different behavior.
  763. return {}
  764. def callable_schema(self, schema: core_schema.CallableSchema) -> JsonSchemaValue:
  765. """Generates a JSON schema that matches a callable value.
  766. Unless overridden in a subclass, this raises an error.
  767. Args:
  768. schema: The core schema.
  769. Returns:
  770. The generated JSON schema.
  771. """
  772. return self.handle_invalid_for_json_schema(schema, 'core_schema.CallableSchema')
  773. def list_schema(self, schema: core_schema.ListSchema) -> JsonSchemaValue:
  774. """Returns a schema that matches a list schema.
  775. Args:
  776. schema: The core schema.
  777. Returns:
  778. The generated JSON schema.
  779. """
  780. items_schema = {} if 'items_schema' not in schema else self.generate_inner(schema['items_schema'])
  781. json_schema = {'type': 'array', 'items': items_schema}
  782. self.update_with_validations(json_schema, schema, self.ValidationsMapping.array)
  783. return json_schema
  784. @deprecated('`tuple_positional_schema` is deprecated. Use `tuple_schema` instead.', category=None)
  785. @final
  786. def tuple_positional_schema(self, schema: core_schema.TupleSchema) -> JsonSchemaValue:
  787. """Replaced by `tuple_schema`."""
  788. warnings.warn(
  789. '`tuple_positional_schema` is deprecated. Use `tuple_schema` instead.',
  790. PydanticDeprecatedSince26,
  791. stacklevel=2,
  792. )
  793. return self.tuple_schema(schema)
  794. @deprecated('`tuple_variable_schema` is deprecated. Use `tuple_schema` instead.', category=None)
  795. @final
  796. def tuple_variable_schema(self, schema: core_schema.TupleSchema) -> JsonSchemaValue:
  797. """Replaced by `tuple_schema`."""
  798. warnings.warn(
  799. '`tuple_variable_schema` is deprecated. Use `tuple_schema` instead.',
  800. PydanticDeprecatedSince26,
  801. stacklevel=2,
  802. )
  803. return self.tuple_schema(schema)
  804. def tuple_schema(self, schema: core_schema.TupleSchema) -> JsonSchemaValue:
  805. """Generates a JSON schema that matches a tuple schema e.g. `tuple[int,
  806. str, bool]` or `tuple[int, ...]`.
  807. Args:
  808. schema: The core schema.
  809. Returns:
  810. The generated JSON schema.
  811. """
  812. json_schema: JsonSchemaValue = {'type': 'array'}
  813. if 'variadic_item_index' in schema:
  814. variadic_item_index = schema['variadic_item_index']
  815. if variadic_item_index > 0:
  816. json_schema['minItems'] = variadic_item_index
  817. json_schema['prefixItems'] = [
  818. self.generate_inner(item) for item in schema['items_schema'][:variadic_item_index]
  819. ]
  820. if variadic_item_index + 1 == len(schema['items_schema']):
  821. # if the variadic item is the last item, then represent it faithfully
  822. json_schema['items'] = self.generate_inner(schema['items_schema'][variadic_item_index])
  823. else:
  824. # otherwise, 'items' represents the schema for the variadic
  825. # item plus the suffix, so just allow anything for simplicity
  826. # for now
  827. json_schema['items'] = True
  828. else:
  829. prefixItems = [self.generate_inner(item) for item in schema['items_schema']]
  830. if prefixItems:
  831. json_schema['prefixItems'] = prefixItems
  832. json_schema['minItems'] = len(prefixItems)
  833. json_schema['maxItems'] = len(prefixItems)
  834. self.update_with_validations(json_schema, schema, self.ValidationsMapping.array)
  835. return json_schema
  836. def set_schema(self, schema: core_schema.SetSchema) -> JsonSchemaValue:
  837. """Generates a JSON schema that matches a set schema.
  838. Args:
  839. schema: The core schema.
  840. Returns:
  841. The generated JSON schema.
  842. """
  843. return self._common_set_schema(schema)
  844. def frozenset_schema(self, schema: core_schema.FrozenSetSchema) -> JsonSchemaValue:
  845. """Generates a JSON schema that matches a frozenset schema.
  846. Args:
  847. schema: The core schema.
  848. Returns:
  849. The generated JSON schema.
  850. """
  851. return self._common_set_schema(schema)
  852. def _common_set_schema(self, schema: core_schema.SetSchema | core_schema.FrozenSetSchema) -> JsonSchemaValue:
  853. items_schema = {} if 'items_schema' not in schema else self.generate_inner(schema['items_schema'])
  854. json_schema = {'type': 'array', 'uniqueItems': True, 'items': items_schema}
  855. self.update_with_validations(json_schema, schema, self.ValidationsMapping.array)
  856. return json_schema
  857. def generator_schema(self, schema: core_schema.GeneratorSchema) -> JsonSchemaValue:
  858. """Returns a JSON schema that represents the provided GeneratorSchema.
  859. Args:
  860. schema: The schema.
  861. Returns:
  862. The generated JSON schema.
  863. """
  864. items_schema = {} if 'items_schema' not in schema else self.generate_inner(schema['items_schema'])
  865. json_schema = {'type': 'array', 'items': items_schema}
  866. self.update_with_validations(json_schema, schema, self.ValidationsMapping.array)
  867. return json_schema
  868. def dict_schema(self, schema: core_schema.DictSchema) -> JsonSchemaValue:
  869. """Generates a JSON schema that matches a dict schema.
  870. Args:
  871. schema: The core schema.
  872. Returns:
  873. The generated JSON schema.
  874. """
  875. json_schema: JsonSchemaValue = {'type': 'object'}
  876. keys_schema = self.generate_inner(schema['keys_schema']).copy() if 'keys_schema' in schema else {}
  877. if '$ref' not in keys_schema:
  878. keys_pattern = keys_schema.pop('pattern', None)
  879. # Don't give a title to patternProperties/propertyNames:
  880. keys_schema.pop('title', None)
  881. else:
  882. # Here, we assume that if the keys schema is a definition reference,
  883. # it can't be a simple string core schema (and thus no pattern can exist).
  884. # However, this is only in practice (in theory, a definition reference core
  885. # schema could be generated for a simple string schema).
  886. # Note that we avoid calling `self.resolve_ref_schema`, as it might not exist yet.
  887. keys_pattern = None
  888. values_schema = self.generate_inner(schema['values_schema']).copy() if 'values_schema' in schema else {}
  889. # don't give a title to additionalProperties:
  890. values_schema.pop('title', None)
  891. if values_schema or keys_pattern is not None:
  892. if keys_pattern is None:
  893. json_schema['additionalProperties'] = values_schema
  894. else:
  895. json_schema['patternProperties'] = {keys_pattern: values_schema}
  896. else: # for `dict[str, Any]`, we allow any key and any value, since `str` is the default key type
  897. json_schema['additionalProperties'] = True
  898. if (
  899. # The len check indicates that constraints are probably present:
  900. (keys_schema.get('type') == 'string' and len(keys_schema) > 1)
  901. # If this is a definition reference schema, it most likely has constraints:
  902. or '$ref' in keys_schema
  903. ):
  904. keys_schema.pop('type', None)
  905. json_schema['propertyNames'] = keys_schema
  906. self.update_with_validations(json_schema, schema, self.ValidationsMapping.object)
  907. return json_schema
  908. def function_before_schema(self, schema: core_schema.BeforeValidatorFunctionSchema) -> JsonSchemaValue:
  909. """Generates a JSON schema that matches a function-before schema.
  910. Args:
  911. schema: The core schema.
  912. Returns:
  913. The generated JSON schema.
  914. """
  915. if self.mode == 'validation' and (input_schema := schema.get('json_schema_input_schema')):
  916. return self.generate_inner(input_schema)
  917. return self.generate_inner(schema['schema'])
  918. def function_after_schema(self, schema: core_schema.AfterValidatorFunctionSchema) -> JsonSchemaValue:
  919. """Generates a JSON schema that matches a function-after schema.
  920. Args:
  921. schema: The core schema.
  922. Returns:
  923. The generated JSON schema.
  924. """
  925. return self.generate_inner(schema['schema'])
  926. def function_plain_schema(self, schema: core_schema.PlainValidatorFunctionSchema) -> JsonSchemaValue:
  927. """Generates a JSON schema that matches a function-plain schema.
  928. Args:
  929. schema: The core schema.
  930. Returns:
  931. The generated JSON schema.
  932. """
  933. if self.mode == 'validation' and (input_schema := schema.get('json_schema_input_schema')):
  934. return self.generate_inner(input_schema)
  935. return self.handle_invalid_for_json_schema(
  936. schema, f'core_schema.PlainValidatorFunctionSchema ({schema["function"]})'
  937. )
  938. def function_wrap_schema(self, schema: core_schema.WrapValidatorFunctionSchema) -> JsonSchemaValue:
  939. """Generates a JSON schema that matches a function-wrap schema.
  940. Args:
  941. schema: The core schema.
  942. Returns:
  943. The generated JSON schema.
  944. """
  945. if self.mode == 'validation' and (input_schema := schema.get('json_schema_input_schema')):
  946. return self.generate_inner(input_schema)
  947. return self.generate_inner(schema['schema'])
  948. def default_schema(self, schema: core_schema.WithDefaultSchema) -> JsonSchemaValue:
  949. """Generates a JSON schema that matches a schema with a default value.
  950. Args:
  951. schema: The core schema.
  952. Returns:
  953. The generated JSON schema.
  954. """
  955. json_schema = self.generate_inner(schema['schema'])
  956. default = self.get_default_value(schema)
  957. if default is NoDefault or default is MISSING:
  958. return json_schema
  959. # we reflect the application of custom plain, no-info serializers to defaults for
  960. # JSON Schemas viewed in serialization mode:
  961. # TODO: improvements along with https://github.com/pydantic/pydantic/issues/8208
  962. if self.mode == 'serialization':
  963. # `_get_ser_schema_for_default_value()` is used to unpack potentially nested validator schemas:
  964. ser_schema = _get_ser_schema_for_default_value(schema['schema'])
  965. if (
  966. ser_schema is not None
  967. and (ser_func := ser_schema.get('function'))
  968. and not (default is None and ser_schema.get('when_used') in ('unless-none', 'json-unless-none'))
  969. ):
  970. try:
  971. default = ser_func(default) # type: ignore
  972. except Exception:
  973. # It might be that the provided default needs to be validated (read: parsed) first
  974. # (assuming `validate_default` is enabled). However, we can't perform
  975. # such validation during JSON Schema generation so we don't support
  976. # this pattern for now.
  977. # (One example is when using `foo: ByteSize = '1MB'`, which validates and
  978. # serializes as an int. In this case, `ser_func` is `int` and `int('1MB')` fails).
  979. self.emit_warning(
  980. 'non-serializable-default',
  981. f'Unable to serialize value {default!r} with the plain serializer; excluding default from JSON schema',
  982. )
  983. return json_schema
  984. # Sort set/frozenset defaults to ensure deterministic JSON schema generation
  985. # We only sort if len > 1 because sets of size 0 or 1 are already deterministic
  986. if isinstance(default, collections.abc.Set) and len(default) > 1:
  987. try:
  988. default = sorted(default)
  989. except TypeError: # pragma: no cover
  990. # If items aren't comparable (e.g. mixed types), we can't sort them.
  991. pass
  992. try:
  993. encoded_default = self.encode_default(default)
  994. except pydantic_core.PydanticSerializationError:
  995. self.emit_warning(
  996. 'non-serializable-default',
  997. f'Default value {default} is not JSON serializable; excluding default from JSON schema',
  998. )
  999. # Return the inner schema, as though there was no default
  1000. return json_schema
  1001. json_schema['default'] = encoded_default
  1002. return json_schema
  1003. def get_default_value(self, schema: core_schema.WithDefaultSchema) -> Any:
  1004. """Get the default value to be used when generating a JSON Schema for a core schema with a default.
  1005. The default implementation is to use the statically defined default value. This method can be overridden
  1006. if you want to make use of the default factory.
  1007. Args:
  1008. schema: The `'with-default'` core schema.
  1009. Returns:
  1010. The default value to use, or [`NoDefault`][pydantic.json_schema.NoDefault] if no default
  1011. value is available.
  1012. """
  1013. return schema.get('default', NoDefault)
  1014. def nullable_schema(self, schema: core_schema.NullableSchema) -> JsonSchemaValue:
  1015. """Generates a JSON schema that matches a schema that allows null values.
  1016. Args:
  1017. schema: The core schema.
  1018. Returns:
  1019. The generated JSON schema.
  1020. """
  1021. null_schema = {'type': 'null'}
  1022. inner_json_schema = self.generate_inner(schema['schema'])
  1023. if inner_json_schema == null_schema:
  1024. return null_schema
  1025. else:
  1026. return self.get_union_of_schemas([inner_json_schema, null_schema])
  1027. def union_schema(self, schema: core_schema.UnionSchema) -> JsonSchemaValue:
  1028. """Generates a JSON schema that matches a schema that allows values matching any of the given schemas.
  1029. Args:
  1030. schema: The core schema.
  1031. Returns:
  1032. The generated JSON schema.
  1033. """
  1034. generated: list[JsonSchemaValue] = []
  1035. for choice in core_schema.iter_union_choices(schema):
  1036. try:
  1037. generated.append(self.generate_inner(choice))
  1038. except PydanticOmit: # noqa: PERF203
  1039. continue
  1040. except PydanticInvalidForJsonSchema as exc:
  1041. self.emit_warning('skipped-choice', exc.message)
  1042. if len(generated) == 1:
  1043. return generated[0]
  1044. return self.get_union_of_schemas(generated)
  1045. def get_union_of_schemas(self, schemas: list[JsonSchemaValue]) -> JsonSchemaValue:
  1046. """Returns the JSON Schema representation for the union of the provided JSON Schemas.
  1047. The result depends on the configured `'union_format'`.
  1048. Args:
  1049. schemas: The list of JSON Schemas to be included in the union.
  1050. Returns:
  1051. The JSON Schema representing the union of schemas.
  1052. """
  1053. if self.union_format == 'primitive_type_array':
  1054. types: list[str] = []
  1055. for schema in schemas:
  1056. schema_types: list[str] | str | None = schema.get('type')
  1057. if schema_types is None:
  1058. # No type, meaning it can be a ref or an empty schema.
  1059. break
  1060. if not isinstance(schema_types, list):
  1061. schema_types = [schema_types]
  1062. if not all(t in _PRIMITIVE_JSON_SCHEMA_TYPES for t in schema_types):
  1063. break
  1064. if len(schema) != 1:
  1065. # We only want to include types that don't have any constraints. For instance,
  1066. # if `schemas = [{'type': 'string', 'maxLength': 3}, {'type': 'string', 'minLength': 5}]`,
  1067. # we don't want to produce `{'type': 'string', 'maxLength': 3, 'minLength': 5}`.
  1068. # Same if we have some metadata (e.g. `title`) on a specific union member, we want to preserve it.
  1069. break
  1070. types.extend(schema_types)
  1071. else:
  1072. # If we got there, all the schemas where valid to be used with the `'primitive_type_array` format
  1073. return {'type': list(dict.fromkeys(types))}
  1074. return self.get_flattened_anyof(schemas)
  1075. def tagged_union_schema(self, schema: core_schema.TaggedUnionSchema) -> JsonSchemaValue:
  1076. """Generates a JSON schema that matches a schema that allows values matching any of the given schemas, where
  1077. the schemas are tagged with a discriminator field that indicates which schema should be used to validate
  1078. the value.
  1079. Args:
  1080. schema: The core schema.
  1081. Returns:
  1082. The generated JSON schema.
  1083. """
  1084. generated: dict[str, JsonSchemaValue] = {}
  1085. for k, v in schema['choices'].items():
  1086. if isinstance(k, Enum):
  1087. k = k.value
  1088. try:
  1089. # Use str(k) since keys must be strings for json; while not technically correct,
  1090. # it's the closest that can be represented in valid JSON
  1091. generated[str(k)] = self.generate_inner(v).copy()
  1092. except PydanticOmit:
  1093. continue
  1094. except PydanticInvalidForJsonSchema as exc:
  1095. self.emit_warning('skipped-choice', exc.message)
  1096. one_of_choices = _deduplicate_schemas(generated.values())
  1097. json_schema: JsonSchemaValue = {'oneOf': one_of_choices}
  1098. # This reflects the v1 behavior; TODO: we should make it possible to exclude OpenAPI stuff from the JSON schema
  1099. openapi_discriminator = self._extract_discriminator(schema, one_of_choices)
  1100. if openapi_discriminator is not None:
  1101. json_schema['discriminator'] = {
  1102. 'propertyName': openapi_discriminator,
  1103. 'mapping': {k: v.get('$ref', v) for k, v in generated.items()},
  1104. }
  1105. return json_schema
  1106. def _extract_discriminator(
  1107. self, schema: core_schema.TaggedUnionSchema, one_of_choices: list[JsonDict]
  1108. ) -> str | None:
  1109. """Extract a compatible OpenAPI discriminator from the schema and one_of choices that end up in the final
  1110. schema."""
  1111. openapi_discriminator: str | None = None
  1112. if isinstance(schema['discriminator'], str):
  1113. return schema['discriminator']
  1114. if isinstance(schema['discriminator'], list):
  1115. # If the discriminator is a single item list containing a string, that is equivalent to the string case
  1116. if len(schema['discriminator']) == 1 and isinstance(schema['discriminator'][0], str):
  1117. return schema['discriminator'][0]
  1118. # When an alias is used that is different from the field name, the discriminator will be a list of single
  1119. # str lists, one for the attribute and one for the actual alias. The logic here will work even if there is
  1120. # more than one possible attribute, and looks for whether a single alias choice is present as a documented
  1121. # property on all choices. If so, that property will be used as the OpenAPI discriminator.
  1122. for alias_path in schema['discriminator']:
  1123. if not isinstance(alias_path, list):
  1124. break # this means that the discriminator is not a list of alias paths
  1125. if len(alias_path) != 1:
  1126. continue # this means that the "alias" does not represent a single field
  1127. alias = alias_path[0]
  1128. if not isinstance(alias, str):
  1129. continue # this means that the "alias" does not represent a field
  1130. alias_is_present_on_all_choices = True
  1131. for choice in one_of_choices:
  1132. try:
  1133. choice = self.resolve_ref_schema(choice)
  1134. except RuntimeError as exc:
  1135. # TODO: fixme - this is a workaround for the fact that we can't always resolve refs
  1136. # for tagged union choices at this point in the schema gen process, we might need to do
  1137. # another pass at the end like we do for core schemas
  1138. self.emit_warning('skipped-discriminator', str(exc))
  1139. choice = {}
  1140. properties = choice.get('properties', {})
  1141. if not isinstance(properties, dict) or alias not in properties:
  1142. alias_is_present_on_all_choices = False
  1143. break
  1144. if alias_is_present_on_all_choices:
  1145. openapi_discriminator = alias
  1146. break
  1147. return openapi_discriminator
  1148. def chain_schema(self, schema: core_schema.ChainSchema) -> JsonSchemaValue:
  1149. """Generates a JSON schema that matches a core_schema.ChainSchema.
  1150. When generating a schema for validation, we return the validation JSON schema for the first step in the chain.
  1151. For serialization, we return the serialization JSON schema for the last step in the chain.
  1152. Args:
  1153. schema: The core schema.
  1154. Returns:
  1155. The generated JSON schema.
  1156. """
  1157. step_index = 0 if self.mode == 'validation' else -1 # use first step for validation, last for serialization
  1158. return self.generate_inner(schema['steps'][step_index])
  1159. def lax_or_strict_schema(self, schema: core_schema.LaxOrStrictSchema) -> JsonSchemaValue:
  1160. """Generates a JSON schema that matches a schema that allows values matching either the lax schema or the
  1161. strict schema.
  1162. Args:
  1163. schema: The core schema.
  1164. Returns:
  1165. The generated JSON schema.
  1166. """
  1167. # TODO: Need to read the default value off of model config or whatever
  1168. use_strict = schema.get('strict', False) # TODO: replace this default False
  1169. # If your JSON schema fails to generate it is probably
  1170. # because one of the following two branches failed.
  1171. if use_strict:
  1172. return self.generate_inner(schema['strict_schema'])
  1173. else:
  1174. return self.generate_inner(schema['lax_schema'])
  1175. def json_or_python_schema(self, schema: core_schema.JsonOrPythonSchema) -> JsonSchemaValue:
  1176. """Generates a JSON schema that matches a schema that allows values matching either the JSON schema or the
  1177. Python schema.
  1178. The JSON schema is used instead of the Python schema. If you want to use the Python schema, you should override
  1179. this method.
  1180. Args:
  1181. schema: The core schema.
  1182. Returns:
  1183. The generated JSON schema.
  1184. """
  1185. return self.generate_inner(schema['json_schema'])
  1186. def typed_dict_schema(self, schema: core_schema.TypedDictSchema) -> JsonSchemaValue:
  1187. """Generates a JSON schema that matches a schema that defines a typed dict.
  1188. Args:
  1189. schema: The core schema.
  1190. Returns:
  1191. The generated JSON schema.
  1192. """
  1193. total = schema.get('total', True)
  1194. named_required_fields: list[tuple[str, bool, CoreSchemaField]] = [
  1195. (name, self.field_is_required(field, total), field)
  1196. for name, field in schema['fields'].items()
  1197. if self.field_is_present(field)
  1198. ]
  1199. if self.mode == 'serialization':
  1200. named_required_fields.extend(self._name_required_computed_fields(schema.get('computed_fields', [])))
  1201. cls = schema.get('cls')
  1202. config = _get_typed_dict_config(cls)
  1203. with self._config_wrapper_stack.push(config):
  1204. json_schema = self._named_required_fields_schema(named_required_fields)
  1205. # There's some duplication between `extra_behavior` and
  1206. # the config's `extra`/core config's `extra_fields_behavior`.
  1207. # However, it is common to manually create TypedDictSchemas,
  1208. # where you don't necessarily have a class.
  1209. # At runtime, `extra_behavior` takes priority over the config
  1210. # for validation, so follow the same for the JSON Schema:
  1211. if 'extras_schema' in schema and schema['extras_schema'] != core_schema.any_schema():
  1212. allow_additional_props = self.generate_inner(schema['extras_schema'])
  1213. else:
  1214. allow_additional_props = True
  1215. if schema.get('extra_behavior') == 'forbid':
  1216. json_schema['additionalProperties'] = False
  1217. elif schema.get('extra_behavior') == 'allow':
  1218. json_schema['additionalProperties'] = allow_additional_props
  1219. if cls is not None:
  1220. # `_update_class_schema()` will not override
  1221. # `additionalProperties` if already present:
  1222. self._update_class_schema(json_schema, cls, config)
  1223. elif 'additionalProperties' not in json_schema:
  1224. extra = schema.get('config', {}).get('extra_fields_behavior')
  1225. if extra == 'forbid':
  1226. json_schema['additionalProperties'] = False
  1227. elif extra == 'allow':
  1228. json_schema['additionalProperties'] = allow_additional_props
  1229. return json_schema
  1230. @staticmethod
  1231. def _name_required_computed_fields(
  1232. computed_fields: list[ComputedField],
  1233. ) -> list[tuple[str, bool, core_schema.ComputedField]]:
  1234. return [(field['property_name'], True, field) for field in computed_fields]
  1235. def _named_required_fields_schema(
  1236. self, named_required_fields: Sequence[tuple[str, bool, CoreSchemaField]]
  1237. ) -> JsonSchemaValue:
  1238. properties: dict[str, JsonSchemaValue] = {}
  1239. required_fields: list[str] = []
  1240. for name, required, field in named_required_fields:
  1241. if self.by_alias:
  1242. name = self._get_alias_name(field, name)
  1243. try:
  1244. field_json_schema = self.generate_inner(field).copy()
  1245. except PydanticOmit:
  1246. continue
  1247. if 'title' not in field_json_schema and self.field_title_should_be_set(field):
  1248. title = self.get_title_from_name(name)
  1249. field_json_schema['title'] = title
  1250. field_json_schema = self.handle_ref_overrides(field_json_schema)
  1251. properties[name] = field_json_schema
  1252. if required:
  1253. required_fields.append(name)
  1254. json_schema = {'type': 'object', 'properties': properties}
  1255. if required_fields:
  1256. json_schema['required'] = required_fields
  1257. return json_schema
  1258. def _get_alias_name(self, field: CoreSchemaField, name: str) -> str:
  1259. if field['type'] == 'computed-field':
  1260. alias: Any = field.get('alias', name)
  1261. elif self.mode == 'validation':
  1262. alias = field.get('validation_alias', name)
  1263. else:
  1264. alias = field.get('serialization_alias', name)
  1265. if isinstance(alias, str):
  1266. name = alias
  1267. elif isinstance(alias, list):
  1268. alias = cast('list[str] | str', alias)
  1269. for path in alias:
  1270. if isinstance(path, list) and len(path) == 1 and isinstance(path[0], str):
  1271. # Use the first valid single-item string path; the code that constructs the alias array
  1272. # should ensure the first such item is what belongs in the JSON schema
  1273. name = path[0]
  1274. break
  1275. else:
  1276. assert_never(alias)
  1277. return name
  1278. def typed_dict_field_schema(self, schema: core_schema.TypedDictField) -> JsonSchemaValue:
  1279. """Generates a JSON schema that matches a schema that defines a typed dict field.
  1280. Args:
  1281. schema: The core schema.
  1282. Returns:
  1283. The generated JSON schema.
  1284. """
  1285. return self.generate_inner(schema['schema'])
  1286. def dataclass_field_schema(self, schema: core_schema.DataclassField) -> JsonSchemaValue:
  1287. """Generates a JSON schema that matches a schema that defines a dataclass field.
  1288. Args:
  1289. schema: The core schema.
  1290. Returns:
  1291. The generated JSON schema.
  1292. """
  1293. return self.generate_inner(schema['schema'])
  1294. def model_field_schema(self, schema: core_schema.ModelField) -> JsonSchemaValue:
  1295. """Generates a JSON schema that matches a schema that defines a model field.
  1296. Args:
  1297. schema: The core schema.
  1298. Returns:
  1299. The generated JSON schema.
  1300. """
  1301. return self.generate_inner(schema['schema'])
  1302. def computed_field_schema(self, schema: core_schema.ComputedField) -> JsonSchemaValue:
  1303. """Generates a JSON schema that matches a schema that defines a computed field.
  1304. Args:
  1305. schema: The core schema.
  1306. Returns:
  1307. The generated JSON schema.
  1308. """
  1309. return self.generate_inner(schema['return_schema'])
  1310. def model_schema(self, schema: core_schema.ModelSchema) -> JsonSchemaValue:
  1311. """Generates a JSON schema that matches a schema that defines a model.
  1312. Args:
  1313. schema: The core schema.
  1314. Returns:
  1315. The generated JSON schema.
  1316. """
  1317. # We do not use schema['model'].model_json_schema() here
  1318. # because it could lead to inconsistent refs handling, etc.
  1319. cls = cast('type[BaseModel]', schema['cls'])
  1320. config = cls.model_config
  1321. with self._config_wrapper_stack.push(config):
  1322. json_schema = self.generate_inner(schema['schema'])
  1323. self._update_class_schema(json_schema, cls, config)
  1324. return json_schema
  1325. def _update_class_schema(self, json_schema: JsonSchemaValue, cls: type[Any], config: ConfigDict) -> None:
  1326. """Update json_schema with the following, extracted from `config` and `cls`:
  1327. * title
  1328. * description
  1329. * additional properties
  1330. * json_schema_extra
  1331. * deprecated
  1332. Done in place, hence there's no return value as the original json_schema is mutated.
  1333. No ref resolving is involved here, as that's not appropriate for simple updates.
  1334. """
  1335. from ._internal._dataclasses import is_stdlib_dataclass
  1336. from .main import BaseModel
  1337. if (config_title := config.get('title')) is not None:
  1338. json_schema.setdefault('title', config_title)
  1339. elif model_title_generator := config.get('model_title_generator'):
  1340. title = model_title_generator(cls)
  1341. if not isinstance(title, str):
  1342. raise TypeError(f'model_title_generator {model_title_generator} must return str, not {title.__class__}')
  1343. json_schema.setdefault('title', title)
  1344. if 'title' not in json_schema:
  1345. json_schema['title'] = cls.__name__
  1346. # BaseModel and dataclasses; don't use cls.__doc__ as it will contain the verbose class signature by default
  1347. if cls is BaseModel:
  1348. docstring = None
  1349. elif is_stdlib_dataclass(cls): # For Pydantic dataclasses, we already handle this at class creation
  1350. # The `dataclass` module generates a `__doc__` based on the `inspect.signature()`
  1351. # result, which we don't want to use as a description. Such `__doc__` startswith
  1352. # `cls.__name__(`, which could lead to mistakenly discarding it if for some reason
  1353. # an explicitly set class docstring follows the same pattern, but this is unlikely
  1354. # to happen.
  1355. doc = cls.__doc__
  1356. docstring = None if doc is None or doc.startswith(f'{cls.__name__}(') else doc
  1357. else:
  1358. docstring = cls.__doc__
  1359. if docstring:
  1360. json_schema.setdefault('description', inspect.cleandoc(docstring))
  1361. extra = config.get('extra')
  1362. if 'additionalProperties' not in json_schema: # This check is particularly important for `typed_dict_schema()`
  1363. if extra == 'allow':
  1364. json_schema['additionalProperties'] = True
  1365. elif extra == 'forbid':
  1366. json_schema['additionalProperties'] = False
  1367. json_schema_extra = config.get('json_schema_extra')
  1368. if issubclass(cls, BaseModel) and cls.__pydantic_root_model__:
  1369. root_json_schema_extra = cls.model_fields['root'].json_schema_extra
  1370. if json_schema_extra and root_json_schema_extra:
  1371. raise ValueError(
  1372. '"model_config[\'json_schema_extra\']" and "Field.json_schema_extra" on "RootModel.root"'
  1373. ' field must not be set simultaneously'
  1374. )
  1375. if root_json_schema_extra:
  1376. json_schema_extra = root_json_schema_extra
  1377. if isinstance(json_schema_extra, (staticmethod, classmethod)):
  1378. # In older versions of python, this is necessary to ensure staticmethod/classmethods are callable
  1379. json_schema_extra = json_schema_extra.__get__(cls)
  1380. if isinstance(json_schema_extra, dict):
  1381. json_schema.update(json_schema_extra)
  1382. elif callable(json_schema_extra):
  1383. if len(_typing_extra.signature_no_eval(json_schema_extra).parameters) > 1:
  1384. json_schema_extra = cast(Callable[[JsonDict, type[Any]], None], json_schema_extra)
  1385. json_schema_extra(json_schema, cls)
  1386. else:
  1387. json_schema_extra = cast(Callable[[JsonDict], None], json_schema_extra)
  1388. json_schema_extra(json_schema)
  1389. elif json_schema_extra is not None:
  1390. raise ValueError(
  1391. f"model_config['json_schema_extra']={json_schema_extra} should be a dict, callable, or None"
  1392. )
  1393. if hasattr(cls, '__deprecated__'):
  1394. json_schema['deprecated'] = True
  1395. def resolve_ref_schema(self, json_schema: JsonSchemaValue) -> JsonSchemaValue:
  1396. """Resolve a JsonSchemaValue to the non-ref schema if it is a $ref schema.
  1397. Args:
  1398. json_schema: The schema to resolve.
  1399. Returns:
  1400. The resolved schema.
  1401. Raises:
  1402. RuntimeError: If the schema reference can't be found in definitions.
  1403. """
  1404. while '$ref' in json_schema:
  1405. ref = json_schema['$ref']
  1406. schema_to_update = self.get_schema_from_definitions(JsonRef(ref))
  1407. if schema_to_update is None:
  1408. raise RuntimeError(f'Cannot update undefined schema for $ref={ref}')
  1409. json_schema = schema_to_update
  1410. return json_schema
  1411. def model_fields_schema(self, schema: core_schema.ModelFieldsSchema) -> JsonSchemaValue:
  1412. """Generates a JSON schema that matches a schema that defines a model's fields.
  1413. Args:
  1414. schema: The core schema.
  1415. Returns:
  1416. The generated JSON schema.
  1417. """
  1418. named_required_fields: list[tuple[str, bool, CoreSchemaField]] = [
  1419. (name, self.field_is_required(field, total=True), field)
  1420. for name, field in schema['fields'].items()
  1421. if self.field_is_present(field)
  1422. ]
  1423. if self.mode == 'serialization':
  1424. named_required_fields.extend(self._name_required_computed_fields(schema.get('computed_fields', [])))
  1425. json_schema = self._named_required_fields_schema(named_required_fields)
  1426. extras_schema = schema.get('extras_schema', None)
  1427. if extras_schema is not None:
  1428. schema_to_update = self.resolve_ref_schema(json_schema)
  1429. schema_to_update['additionalProperties'] = self.generate_inner(extras_schema)
  1430. return json_schema
  1431. def field_is_present(self, field: CoreSchemaField) -> bool:
  1432. """Whether the field should be included in the generated JSON schema.
  1433. Args:
  1434. field: The schema for the field itself.
  1435. Returns:
  1436. `True` if the field should be included in the generated JSON schema, `False` otherwise.
  1437. """
  1438. if self.mode == 'serialization':
  1439. # If you still want to include the field in the generated JSON schema,
  1440. # override this method and return True
  1441. return not field.get('serialization_exclude')
  1442. elif self.mode == 'validation':
  1443. return True
  1444. else:
  1445. assert_never(self.mode)
  1446. def field_is_required(
  1447. self,
  1448. field: core_schema.ModelField | core_schema.DataclassField | core_schema.TypedDictField,
  1449. total: bool,
  1450. ) -> bool:
  1451. """Whether the field should be marked as required in the generated JSON schema.
  1452. (Note that this is irrelevant if the field is not present in the JSON schema.).
  1453. Args:
  1454. field: The schema for the field itself.
  1455. total: Only applies to `TypedDictField`s.
  1456. Indicates if the `TypedDict` this field belongs to is total, in which case any fields that don't
  1457. explicitly specify `required=False` are required.
  1458. Returns:
  1459. `True` if the field should be marked as required in the generated JSON schema, `False` otherwise.
  1460. """
  1461. if field['type'] == 'typed-dict-field':
  1462. required = field.get('required', total)
  1463. else:
  1464. required = field['schema']['type'] != 'default'
  1465. if self.mode == 'serialization':
  1466. has_exclude_if = field.get('serialization_exclude_if') is not None
  1467. if self._config.json_schema_serialization_defaults_required:
  1468. return not has_exclude_if
  1469. else:
  1470. return required and not has_exclude_if
  1471. else:
  1472. return required
  1473. def dataclass_args_schema(self, schema: core_schema.DataclassArgsSchema) -> JsonSchemaValue:
  1474. """Generates a JSON schema that matches a schema that defines a dataclass's constructor arguments.
  1475. Args:
  1476. schema: The core schema.
  1477. Returns:
  1478. The generated JSON schema.
  1479. """
  1480. named_required_fields: list[tuple[str, bool, CoreSchemaField]] = [
  1481. (field['name'], self.field_is_required(field, total=True), field)
  1482. for field in schema['fields']
  1483. if self.field_is_present(field)
  1484. ]
  1485. if self.mode == 'serialization':
  1486. named_required_fields.extend(self._name_required_computed_fields(schema.get('computed_fields', [])))
  1487. return self._named_required_fields_schema(named_required_fields)
  1488. def dataclass_schema(self, schema: core_schema.DataclassSchema) -> JsonSchemaValue:
  1489. """Generates a JSON schema that matches a schema that defines a dataclass.
  1490. Args:
  1491. schema: The core schema.
  1492. Returns:
  1493. The generated JSON schema.
  1494. """
  1495. cls = schema['cls']
  1496. config = cast('ConfigDict', getattr(cls, '__pydantic_config__', {}))
  1497. with self._config_wrapper_stack.push(config):
  1498. json_schema = self.generate_inner(schema['schema']).copy()
  1499. self._update_class_schema(json_schema, cls, config)
  1500. return json_schema
  1501. def arguments_schema(self, schema: core_schema.ArgumentsSchema) -> JsonSchemaValue:
  1502. """Generates a JSON schema that matches a schema that defines a function's arguments.
  1503. Args:
  1504. schema: The core schema.
  1505. Returns:
  1506. The generated JSON schema.
  1507. """
  1508. prefer_positional = schema.get('metadata', {}).get('pydantic_js_prefer_positional_arguments')
  1509. arguments = schema['arguments_schema']
  1510. kw_only_arguments = [a for a in arguments if a.get('mode') == 'keyword_only']
  1511. kw_or_p_arguments = [a for a in arguments if a.get('mode') in {'positional_or_keyword', None}]
  1512. p_only_arguments = [a for a in arguments if a.get('mode') == 'positional_only']
  1513. var_args_schema = schema.get('var_args_schema')
  1514. var_kwargs_schema = schema.get('var_kwargs_schema')
  1515. if prefer_positional:
  1516. positional_possible = not kw_only_arguments and not var_kwargs_schema
  1517. if positional_possible:
  1518. return self.p_arguments_schema(p_only_arguments + kw_or_p_arguments, var_args_schema)
  1519. keyword_possible = not p_only_arguments and not var_args_schema
  1520. if keyword_possible:
  1521. return self.kw_arguments_schema(kw_or_p_arguments + kw_only_arguments, var_kwargs_schema)
  1522. if not prefer_positional:
  1523. positional_possible = not kw_only_arguments and not var_kwargs_schema
  1524. if positional_possible:
  1525. return self.p_arguments_schema(p_only_arguments + kw_or_p_arguments, var_args_schema)
  1526. raise PydanticInvalidForJsonSchema(
  1527. 'Unable to generate JSON schema for arguments validator with positional-only and keyword-only arguments'
  1528. )
  1529. def kw_arguments_schema(
  1530. self, arguments: list[core_schema.ArgumentsParameter], var_kwargs_schema: CoreSchema | None
  1531. ) -> JsonSchemaValue:
  1532. """Generates a JSON schema that matches a schema that defines a function's keyword arguments.
  1533. Args:
  1534. arguments: The core schema.
  1535. Returns:
  1536. The generated JSON schema.
  1537. """
  1538. properties: dict[str, JsonSchemaValue] = {}
  1539. required: list[str] = []
  1540. for argument in arguments:
  1541. name = self.get_argument_name(argument)
  1542. argument_schema = self.generate_inner(argument['schema']).copy()
  1543. if 'title' not in argument_schema and self.field_title_should_be_set(argument['schema']):
  1544. argument_schema['title'] = self.get_title_from_name(name)
  1545. properties[name] = argument_schema
  1546. if argument['schema']['type'] != 'default':
  1547. # This assumes that if the argument has a default value,
  1548. # the inner schema must be of type WithDefaultSchema.
  1549. # I believe this is true, but I am not 100% sure
  1550. required.append(name)
  1551. json_schema: JsonSchemaValue = {'type': 'object', 'properties': properties}
  1552. if required:
  1553. json_schema['required'] = required
  1554. if var_kwargs_schema:
  1555. additional_properties_schema = self.generate_inner(var_kwargs_schema)
  1556. if additional_properties_schema:
  1557. json_schema['additionalProperties'] = additional_properties_schema
  1558. else:
  1559. json_schema['additionalProperties'] = False
  1560. return json_schema
  1561. def p_arguments_schema(
  1562. self, arguments: list[core_schema.ArgumentsParameter], var_args_schema: CoreSchema | None
  1563. ) -> JsonSchemaValue:
  1564. """Generates a JSON schema that matches a schema that defines a function's positional arguments.
  1565. Args:
  1566. arguments: The core schema.
  1567. Returns:
  1568. The generated JSON schema.
  1569. """
  1570. prefix_items: list[JsonSchemaValue] = []
  1571. min_items = 0
  1572. for argument in arguments:
  1573. name = self.get_argument_name(argument)
  1574. argument_schema = self.generate_inner(argument['schema']).copy()
  1575. if 'title' not in argument_schema and self.field_title_should_be_set(argument['schema']):
  1576. argument_schema['title'] = self.get_title_from_name(name)
  1577. prefix_items.append(argument_schema)
  1578. if argument['schema']['type'] != 'default':
  1579. # This assumes that if the argument has a default value,
  1580. # the inner schema must be of type WithDefaultSchema.
  1581. # I believe this is true, but I am not 100% sure
  1582. min_items += 1
  1583. json_schema: JsonSchemaValue = {'type': 'array'}
  1584. if prefix_items:
  1585. json_schema['prefixItems'] = prefix_items
  1586. if min_items:
  1587. json_schema['minItems'] = min_items
  1588. if var_args_schema:
  1589. items_schema = self.generate_inner(var_args_schema)
  1590. if items_schema:
  1591. json_schema['items'] = items_schema
  1592. else:
  1593. json_schema['maxItems'] = len(prefix_items)
  1594. return json_schema
  1595. def get_argument_name(self, argument: core_schema.ArgumentsParameter | core_schema.ArgumentsV3Parameter) -> str:
  1596. """Retrieves the name of an argument.
  1597. Args:
  1598. argument: The core schema.
  1599. Returns:
  1600. The name of the argument.
  1601. """
  1602. name = argument['name']
  1603. if self.by_alias:
  1604. alias = argument.get('alias')
  1605. if isinstance(alias, str):
  1606. name = alias
  1607. else:
  1608. pass # might want to do something else?
  1609. return name
  1610. def arguments_v3_schema(self, schema: core_schema.ArgumentsV3Schema) -> JsonSchemaValue:
  1611. """Generates a JSON schema that matches a schema that defines a function's arguments.
  1612. Args:
  1613. schema: The core schema.
  1614. Returns:
  1615. The generated JSON schema.
  1616. """
  1617. arguments = schema['arguments_schema']
  1618. properties: dict[str, JsonSchemaValue] = {}
  1619. required: list[str] = []
  1620. for argument in arguments:
  1621. mode = argument.get('mode', 'positional_or_keyword')
  1622. name = self.get_argument_name(argument)
  1623. argument_schema = self.generate_inner(argument['schema']).copy()
  1624. if mode == 'var_args':
  1625. argument_schema = {'type': 'array', 'items': argument_schema}
  1626. elif mode == 'var_kwargs_uniform':
  1627. argument_schema = {'type': 'object', 'additionalProperties': argument_schema}
  1628. argument_schema.setdefault('title', self.get_title_from_name(name))
  1629. properties[name] = argument_schema
  1630. if (
  1631. (mode == 'var_kwargs_unpacked_typed_dict' and 'required' in argument_schema)
  1632. or mode not in {'var_args', 'var_kwargs_uniform', 'var_kwargs_unpacked_typed_dict'}
  1633. and argument['schema']['type'] != 'default'
  1634. ):
  1635. # This assumes that if the argument has a default value,
  1636. # the inner schema must be of type WithDefaultSchema.
  1637. # I believe this is true, but I am not 100% sure
  1638. required.append(name)
  1639. json_schema: JsonSchemaValue = {'type': 'object', 'properties': properties}
  1640. if required:
  1641. json_schema['required'] = required
  1642. return json_schema
  1643. def call_schema(self, schema: core_schema.CallSchema) -> JsonSchemaValue:
  1644. """Generates a JSON schema that matches a schema that defines a function call.
  1645. Args:
  1646. schema: The core schema.
  1647. Returns:
  1648. The generated JSON schema.
  1649. """
  1650. return self.generate_inner(schema['arguments_schema'])
  1651. def custom_error_schema(self, schema: core_schema.CustomErrorSchema) -> JsonSchemaValue:
  1652. """Generates a JSON schema that matches a schema that defines a custom error.
  1653. Args:
  1654. schema: The core schema.
  1655. Returns:
  1656. The generated JSON schema.
  1657. """
  1658. return self.generate_inner(schema['schema'])
  1659. def json_schema(self, schema: core_schema.JsonSchema) -> JsonSchemaValue:
  1660. """Generates a JSON schema that matches a schema that defines a JSON object.
  1661. Args:
  1662. schema: The core schema.
  1663. Returns:
  1664. The generated JSON schema.
  1665. """
  1666. content_core_schema = schema.get('schema') or core_schema.any_schema()
  1667. content_json_schema = self.generate_inner(content_core_schema)
  1668. if self.mode == 'validation':
  1669. return {'type': 'string', 'contentMediaType': 'application/json', 'contentSchema': content_json_schema}
  1670. else:
  1671. # self.mode == 'serialization'
  1672. return content_json_schema
  1673. def url_schema(self, schema: core_schema.UrlSchema) -> JsonSchemaValue:
  1674. """Generates a JSON schema that matches a schema that defines a URL.
  1675. Args:
  1676. schema: The core schema.
  1677. Returns:
  1678. The generated JSON schema.
  1679. """
  1680. json_schema = {'type': 'string', 'format': 'uri', 'minLength': 1}
  1681. self.update_with_validations(json_schema, schema, self.ValidationsMapping.string)
  1682. return json_schema
  1683. def multi_host_url_schema(self, schema: core_schema.MultiHostUrlSchema) -> JsonSchemaValue:
  1684. """Generates a JSON schema that matches a schema that defines a URL that can be used with multiple hosts.
  1685. Args:
  1686. schema: The core schema.
  1687. Returns:
  1688. The generated JSON schema.
  1689. """
  1690. # Note: 'multi-host-uri' is a custom/pydantic-specific format, not part of the JSON Schema spec
  1691. json_schema = {'type': 'string', 'format': 'multi-host-uri', 'minLength': 1}
  1692. self.update_with_validations(json_schema, schema, self.ValidationsMapping.string)
  1693. return json_schema
  1694. def uuid_schema(self, schema: core_schema.UuidSchema) -> JsonSchemaValue:
  1695. """Generates a JSON schema that matches a UUID.
  1696. Args:
  1697. schema: The core schema.
  1698. Returns:
  1699. The generated JSON schema.
  1700. """
  1701. return {'type': 'string', 'format': 'uuid'}
  1702. def definitions_schema(self, schema: core_schema.DefinitionsSchema) -> JsonSchemaValue:
  1703. """Generates a JSON schema that matches a schema that defines a JSON object with definitions.
  1704. Args:
  1705. schema: The core schema.
  1706. Returns:
  1707. The generated JSON schema.
  1708. """
  1709. for definition in schema['definitions']:
  1710. try:
  1711. self.generate_inner(definition)
  1712. except PydanticInvalidForJsonSchema as e: # noqa: PERF203
  1713. core_ref: CoreRef = CoreRef(definition['ref']) # type: ignore
  1714. self._core_defs_invalid_for_json_schema[self.get_defs_ref((core_ref, self.mode))] = e
  1715. continue
  1716. return self.generate_inner(schema['schema'])
  1717. def definition_ref_schema(self, schema: core_schema.DefinitionReferenceSchema) -> JsonSchemaValue:
  1718. """Generates a JSON schema that matches a schema that references a definition.
  1719. Args:
  1720. schema: The core schema.
  1721. Returns:
  1722. The generated JSON schema.
  1723. """
  1724. core_ref = CoreRef(schema['schema_ref'])
  1725. _, ref_json_schema = self.get_cache_defs_ref_schema(core_ref)
  1726. return ref_json_schema
  1727. def ser_schema(
  1728. self, schema: core_schema.SerSchema | core_schema.IncExSeqSerSchema | core_schema.IncExDictSerSchema
  1729. ) -> JsonSchemaValue | None:
  1730. """Generates a JSON schema that matches a schema that defines a serialized object.
  1731. Args:
  1732. schema: The core schema.
  1733. Returns:
  1734. The generated JSON schema.
  1735. """
  1736. schema_type = schema['type']
  1737. if schema_type == 'function-plain' or schema_type == 'function-wrap':
  1738. # PlainSerializerFunctionSerSchema or WrapSerializerFunctionSerSchema
  1739. return_schema = schema.get('return_schema')
  1740. if return_schema is not None:
  1741. return self.generate_inner(return_schema)
  1742. elif schema_type == 'format' or schema_type == 'to-string':
  1743. # FormatSerSchema or ToStringSerSchema
  1744. return self.str_schema(core_schema.str_schema())
  1745. elif schema['type'] == 'model':
  1746. # ModelSerSchema
  1747. return self.generate_inner(schema['schema'])
  1748. return None
  1749. def complex_schema(self, schema: core_schema.ComplexSchema) -> JsonSchemaValue:
  1750. """Generates a JSON schema that matches a complex number.
  1751. JSON has no standard way to represent complex numbers. Complex number is not a numeric
  1752. type. Here we represent complex number as strings following the rule defined by Python.
  1753. For instance, '1+2j' is an accepted complex string. Details can be found in
  1754. [Python's `complex` documentation][complex].
  1755. Args:
  1756. schema: The core schema.
  1757. Returns:
  1758. The generated JSON schema.
  1759. """
  1760. return {'type': 'string'}
  1761. # ### Utility methods
  1762. def get_title_from_name(self, name: str) -> str:
  1763. """Retrieves a title from a name.
  1764. Args:
  1765. name: The name to retrieve a title from.
  1766. Returns:
  1767. The title.
  1768. """
  1769. return name.title().replace('_', ' ').strip()
  1770. def field_title_should_be_set(self, schema: CoreSchemaOrField) -> bool:
  1771. """Returns true if a field with the given schema should have a title set based on the field name.
  1772. Intuitively, we want this to return true for schemas that wouldn't otherwise provide their own title
  1773. (e.g., int, float, str), and false for those that would (e.g., BaseModel subclasses).
  1774. Args:
  1775. schema: The schema to check.
  1776. Returns:
  1777. `True` if the field should have a title set, `False` otherwise.
  1778. """
  1779. if _core_utils.is_core_schema_field(schema):
  1780. if schema['type'] == 'computed-field':
  1781. field_schema = schema['return_schema']
  1782. else:
  1783. field_schema = schema['schema']
  1784. return self.field_title_should_be_set(field_schema)
  1785. elif _core_utils.is_core_schema(schema):
  1786. if schema.get('ref'): # things with refs, such as models and enums, should not have titles set
  1787. return False
  1788. if schema['type'] in {'default', 'nullable', 'definitions'}:
  1789. return self.field_title_should_be_set(schema['schema']) # type: ignore[typeddict-item]
  1790. if _core_utils.is_function_with_inner_schema(schema):
  1791. return self.field_title_should_be_set(schema['schema'])
  1792. if schema['type'] == 'definition-ref':
  1793. # Referenced schemas should not have titles set for the same reason
  1794. # schemas with refs should not
  1795. return False
  1796. return True # anything else should have title set
  1797. else:
  1798. raise PydanticInvalidForJsonSchema(f'Unexpected schema type: schema={schema}') # pragma: no cover
  1799. def normalize_name(self, name: str) -> str:
  1800. """Normalizes a name to be used as a key in a dictionary.
  1801. Args:
  1802. name: The name to normalize.
  1803. Returns:
  1804. The normalized name.
  1805. """
  1806. return re.sub(r'[^a-zA-Z0-9.\-_]', '_', name).replace('.', '__')
  1807. def get_defs_ref(self, core_mode_ref: CoreModeRef) -> DefsRef:
  1808. """Override this method to change the way that definitions keys are generated from a core reference.
  1809. Args:
  1810. core_mode_ref: The core reference.
  1811. Returns:
  1812. The definitions key.
  1813. """
  1814. # Split the core ref into "components"; generic origins and arguments are each separate components
  1815. core_ref, mode = core_mode_ref
  1816. components = re.split(r'([\][,])', core_ref)
  1817. # Remove IDs from each component
  1818. components = [x.rsplit(':', 1)[0] for x in components]
  1819. core_ref_no_id = ''.join(components)
  1820. # Remove everything before the last period from each "component"
  1821. components = [re.sub(r'(?:[^.[\]]+\.)+((?:[^.[\]]+))', r'\1', x) for x in components]
  1822. short_ref = ''.join(components)
  1823. mode_title = _MODE_TITLE_MAPPING[mode]
  1824. # It is important that the generated defs_ref values be such that at least one choice will not
  1825. # be generated for any other core_ref. Currently, this should be the case because we include
  1826. # the id of the source type in the core_ref
  1827. name = DefsRef(self.normalize_name(short_ref))
  1828. name_mode = DefsRef(self.normalize_name(short_ref) + f'-{mode_title}')
  1829. module_qualname = DefsRef(self.normalize_name(core_ref_no_id))
  1830. module_qualname_mode = DefsRef(f'{module_qualname}-{mode_title}')
  1831. module_qualname_id = DefsRef(self.normalize_name(core_ref))
  1832. occurrence_index = self._collision_index.get(module_qualname_id)
  1833. if occurrence_index is None:
  1834. self._collision_counter[module_qualname] += 1
  1835. occurrence_index = self._collision_index[module_qualname_id] = self._collision_counter[module_qualname]
  1836. module_qualname_occurrence = DefsRef(f'{module_qualname}__{occurrence_index}')
  1837. module_qualname_occurrence_mode = DefsRef(f'{module_qualname_mode}__{occurrence_index}')
  1838. self._prioritized_defsref_choices[module_qualname_occurrence_mode] = [
  1839. name,
  1840. name_mode,
  1841. module_qualname,
  1842. module_qualname_mode,
  1843. module_qualname_occurrence,
  1844. module_qualname_occurrence_mode,
  1845. ]
  1846. return module_qualname_occurrence_mode
  1847. def get_cache_defs_ref_schema(self, core_ref: CoreRef) -> tuple[DefsRef, JsonSchemaValue]:
  1848. """This method wraps the get_defs_ref method with some cache-lookup/population logic,
  1849. and returns both the produced defs_ref and the JSON schema that will refer to the right definition.
  1850. Args:
  1851. core_ref: The core reference to get the definitions reference for.
  1852. Returns:
  1853. A tuple of the definitions reference and the JSON schema that will refer to it.
  1854. """
  1855. core_mode_ref = (core_ref, self.mode)
  1856. maybe_defs_ref = self.core_to_defs_refs.get(core_mode_ref)
  1857. if maybe_defs_ref is not None:
  1858. json_ref = self.core_to_json_refs[core_mode_ref]
  1859. return maybe_defs_ref, {'$ref': json_ref}
  1860. defs_ref = self.get_defs_ref(core_mode_ref)
  1861. # populate the ref translation mappings
  1862. self.core_to_defs_refs[core_mode_ref] = defs_ref
  1863. self.defs_to_core_refs[defs_ref] = core_mode_ref
  1864. json_ref = JsonRef(self.ref_template.format(model=defs_ref))
  1865. self.core_to_json_refs[core_mode_ref] = json_ref
  1866. self.json_to_defs_refs[json_ref] = defs_ref
  1867. ref_json_schema = {'$ref': json_ref}
  1868. return defs_ref, ref_json_schema
  1869. def handle_ref_overrides(self, json_schema: JsonSchemaValue) -> JsonSchemaValue:
  1870. """Remove any sibling keys that are redundant with the referenced schema.
  1871. Args:
  1872. json_schema: The schema to remove redundant sibling keys from.
  1873. Returns:
  1874. The schema with redundant sibling keys removed.
  1875. """
  1876. if '$ref' in json_schema:
  1877. # prevent modifications to the input; this copy may be safe to drop if there is significant overhead
  1878. json_schema = json_schema.copy()
  1879. referenced_json_schema = self.get_schema_from_definitions(JsonRef(json_schema['$ref']))
  1880. if referenced_json_schema is None:
  1881. # This can happen when building schemas for models with not-yet-defined references.
  1882. # It may be a good idea to do a recursive pass at the end of the generation to remove
  1883. # any redundant override keys.
  1884. return json_schema
  1885. for k, v in list(json_schema.items()):
  1886. if k == '$ref':
  1887. continue
  1888. if k in referenced_json_schema and referenced_json_schema[k] == v:
  1889. del json_schema[k] # redundant key
  1890. return json_schema
  1891. def get_schema_from_definitions(self, json_ref: JsonRef) -> JsonSchemaValue | None:
  1892. try:
  1893. def_ref = self.json_to_defs_refs[json_ref]
  1894. if def_ref in self._core_defs_invalid_for_json_schema:
  1895. raise self._core_defs_invalid_for_json_schema[def_ref]
  1896. return self.definitions.get(def_ref, None)
  1897. except KeyError:
  1898. if json_ref.startswith(('http://', 'https://')):
  1899. return None
  1900. raise
  1901. def encode_default(self, dft: Any) -> Any:
  1902. """Encode a default value to a JSON-serializable value.
  1903. This is used to encode default values for fields in the generated JSON schema.
  1904. Args:
  1905. dft: The default value to encode.
  1906. Returns:
  1907. The encoded default value.
  1908. """
  1909. from .type_adapter import TypeAdapter, _type_has_config
  1910. config = self._config
  1911. try:
  1912. default = (
  1913. dft
  1914. if _type_has_config(type(dft))
  1915. else TypeAdapter(type(dft), config=config.config_dict).dump_python(
  1916. dft, by_alias=self.by_alias, mode='json'
  1917. )
  1918. )
  1919. except PydanticSchemaGenerationError:
  1920. raise pydantic_core.PydanticSerializationError(f'Unable to encode default value {dft}')
  1921. return pydantic_core.to_jsonable_python(
  1922. default, timedelta_mode=config.ser_json_timedelta, bytes_mode=config.ser_json_bytes, by_alias=self.by_alias
  1923. )
  1924. def update_with_validations(
  1925. self, json_schema: JsonSchemaValue, core_schema: CoreSchema, mapping: dict[str, str]
  1926. ) -> None:
  1927. """Update the json_schema with the corresponding validations specified in the core_schema,
  1928. using the provided mapping to translate keys in core_schema to the appropriate keys for a JSON schema.
  1929. Args:
  1930. json_schema: The JSON schema to update.
  1931. core_schema: The core schema to get the validations from.
  1932. mapping: A mapping from core_schema attribute names to the corresponding JSON schema attribute names.
  1933. """
  1934. for core_key, json_schema_key in mapping.items():
  1935. if core_key in core_schema:
  1936. json_schema[json_schema_key] = core_schema[core_key]
  1937. class ValidationsMapping:
  1938. """This class just contains mappings from core_schema attribute names to the corresponding
  1939. JSON schema attribute names. While I suspect it is unlikely to be necessary, you can in
  1940. principle override this class in a subclass of GenerateJsonSchema (by inheriting from
  1941. GenerateJsonSchema.ValidationsMapping) to change these mappings.
  1942. """
  1943. numeric = {
  1944. 'multiple_of': 'multipleOf',
  1945. 'le': 'maximum',
  1946. 'ge': 'minimum',
  1947. 'lt': 'exclusiveMaximum',
  1948. 'gt': 'exclusiveMinimum',
  1949. }
  1950. bytes = {
  1951. 'min_length': 'minLength',
  1952. 'max_length': 'maxLength',
  1953. }
  1954. string = {
  1955. 'min_length': 'minLength',
  1956. 'max_length': 'maxLength',
  1957. 'pattern': 'pattern',
  1958. }
  1959. array = {
  1960. 'min_length': 'minItems',
  1961. 'max_length': 'maxItems',
  1962. }
  1963. object = {
  1964. 'min_length': 'minProperties',
  1965. 'max_length': 'maxProperties',
  1966. }
  1967. def get_flattened_anyof(self, schemas: list[JsonSchemaValue]) -> JsonSchemaValue:
  1968. members = []
  1969. for schema in schemas:
  1970. if len(schema) == 1 and 'anyOf' in schema:
  1971. members.extend(schema['anyOf'])
  1972. else:
  1973. members.append(schema)
  1974. members = _deduplicate_schemas(members)
  1975. if len(members) == 1:
  1976. return members[0]
  1977. return {'anyOf': members}
  1978. def get_json_ref_counts(self, json_schema: JsonSchemaValue) -> dict[JsonRef, int]:
  1979. """Get all values corresponding to the key '$ref' anywhere in the json_schema."""
  1980. json_refs: dict[JsonRef, int] = Counter()
  1981. def _add_json_refs(schema: Any) -> None:
  1982. if isinstance(schema, dict):
  1983. if '$ref' in schema:
  1984. json_ref = JsonRef(schema['$ref'])
  1985. if not isinstance(json_ref, str):
  1986. return # in this case, '$ref' might have been the name of a property
  1987. already_visited = json_ref in json_refs
  1988. json_refs[json_ref] += 1
  1989. if already_visited:
  1990. return # prevent recursion on a definition that was already visited
  1991. try:
  1992. defs_ref = self.json_to_defs_refs[json_ref]
  1993. if defs_ref in self._core_defs_invalid_for_json_schema:
  1994. raise self._core_defs_invalid_for_json_schema[defs_ref]
  1995. _add_json_refs(self.definitions[defs_ref])
  1996. except KeyError:
  1997. if not json_ref.startswith(('http://', 'https://')):
  1998. raise
  1999. for k, v in schema.items():
  2000. if k == 'examples' and isinstance(v, list):
  2001. # Skip examples that may contain arbitrary values and references
  2002. # (see the comment in `_get_all_json_refs` for more details).
  2003. continue
  2004. _add_json_refs(v)
  2005. elif isinstance(schema, list):
  2006. for v in schema:
  2007. _add_json_refs(v)
  2008. _add_json_refs(json_schema)
  2009. return json_refs
  2010. def handle_invalid_for_json_schema(self, schema: CoreSchemaOrField, error_info: str) -> JsonSchemaValue:
  2011. raise PydanticInvalidForJsonSchema(f'Cannot generate a JsonSchema for {error_info}')
  2012. def emit_warning(self, kind: JsonSchemaWarningKind, detail: str) -> None:
  2013. """This method simply emits PydanticJsonSchemaWarnings based on handling in the `warning_message` method."""
  2014. message = self.render_warning_message(kind, detail)
  2015. if message is not None:
  2016. warnings.warn(message, PydanticJsonSchemaWarning)
  2017. def render_warning_message(self, kind: JsonSchemaWarningKind, detail: str) -> str | None:
  2018. """This method is responsible for ignoring warnings as desired, and for formatting the warning messages.
  2019. You can override the value of `ignored_warning_kinds` in a subclass of GenerateJsonSchema
  2020. to modify what warnings are generated. If you want more control, you can override this method;
  2021. just return None in situations where you don't want warnings to be emitted.
  2022. Args:
  2023. kind: The kind of warning to render. It can be one of the following:
  2024. - 'skipped-choice': A choice field was skipped because it had no valid choices.
  2025. - 'non-serializable-default': A default value was skipped because it was not JSON-serializable.
  2026. detail: A string with additional details about the warning.
  2027. Returns:
  2028. The formatted warning message, or `None` if no warning should be emitted.
  2029. """
  2030. if kind in self.ignored_warning_kinds:
  2031. return None
  2032. return f'{detail} [{kind}]'
  2033. def _build_definitions_remapping(self) -> _DefinitionsRemapping:
  2034. defs_to_json: dict[DefsRef, JsonRef] = {}
  2035. for defs_refs in self._prioritized_defsref_choices.values():
  2036. for defs_ref in defs_refs:
  2037. json_ref = JsonRef(self.ref_template.format(model=defs_ref))
  2038. defs_to_json[defs_ref] = json_ref
  2039. return _DefinitionsRemapping.from_prioritized_choices(
  2040. self._prioritized_defsref_choices, defs_to_json, self.definitions
  2041. )
  2042. def _garbage_collect_definitions(self, schema: JsonSchemaValue) -> None:
  2043. visited_defs_refs: set[DefsRef] = set()
  2044. unvisited_json_refs = _get_all_json_refs(schema)
  2045. while unvisited_json_refs:
  2046. next_json_ref = unvisited_json_refs.pop()
  2047. try:
  2048. next_defs_ref = self.json_to_defs_refs[next_json_ref]
  2049. if next_defs_ref in visited_defs_refs:
  2050. continue
  2051. visited_defs_refs.add(next_defs_ref)
  2052. unvisited_json_refs.update(_get_all_json_refs(self.definitions[next_defs_ref]))
  2053. except KeyError:
  2054. if not next_json_ref.startswith(('http://', 'https://')):
  2055. raise
  2056. self.definitions = {k: v for k, v in self.definitions.items() if k in visited_defs_refs}
  2057. # ##### Start JSON Schema Generation Functions #####
  2058. def model_json_schema(
  2059. cls: type[BaseModel] | type[PydanticDataclass],
  2060. by_alias: bool = True,
  2061. ref_template: str = DEFAULT_REF_TEMPLATE,
  2062. union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
  2063. schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
  2064. mode: JsonSchemaMode = 'validation',
  2065. ) -> dict[str, Any]:
  2066. """Utility function to generate a JSON Schema for a model.
  2067. Args:
  2068. cls: The model class to generate a JSON Schema for.
  2069. by_alias: If `True` (the default), fields will be serialized according to their alias.
  2070. If `False`, fields will be serialized according to their attribute name.
  2071. ref_template: The template to use for generating JSON Schema references.
  2072. union_format: The format to use when combining schemas from unions together. Can be one of:
  2073. - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
  2074. keyword to combine schemas (the default).
  2075. - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
  2076. keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
  2077. type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
  2078. `any_of`.
  2079. schema_generator: The class to use for generating the JSON Schema.
  2080. mode: The mode to use for generating the JSON Schema. It can be one of the following:
  2081. - 'validation': Generate a JSON Schema for validating data.
  2082. - 'serialization': Generate a JSON Schema for serializing data.
  2083. Returns:
  2084. The generated JSON Schema.
  2085. """
  2086. from .main import BaseModel
  2087. schema_generator_instance = schema_generator(
  2088. by_alias=by_alias, ref_template=ref_template, union_format=union_format
  2089. )
  2090. if isinstance(cls.__pydantic_core_schema__, _mock_val_ser.MockCoreSchema):
  2091. cls.__pydantic_core_schema__.rebuild()
  2092. if cls is BaseModel:
  2093. raise AttributeError('model_json_schema() must be called on a subclass of BaseModel, not BaseModel itself.')
  2094. assert not isinstance(cls.__pydantic_core_schema__, _mock_val_ser.MockCoreSchema), 'this is a bug! please report it'
  2095. return schema_generator_instance.generate(cls.__pydantic_core_schema__, mode=mode)
  2096. def models_json_schema(
  2097. models: Sequence[tuple[type[BaseModel] | type[PydanticDataclass], JsonSchemaMode]],
  2098. *,
  2099. by_alias: bool = True,
  2100. title: str | None = None,
  2101. description: str | None = None,
  2102. ref_template: str = DEFAULT_REF_TEMPLATE,
  2103. union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
  2104. schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
  2105. ) -> tuple[dict[tuple[type[BaseModel] | type[PydanticDataclass], JsonSchemaMode], JsonSchemaValue], JsonSchemaValue]:
  2106. """Utility function to generate a JSON Schema for multiple models.
  2107. Args:
  2108. models: A sequence of tuples of the form (model, mode).
  2109. by_alias: Whether field aliases should be used as keys in the generated JSON Schema.
  2110. title: The title of the generated JSON Schema.
  2111. description: The description of the generated JSON Schema.
  2112. ref_template: The reference template to use for generating JSON Schema references.
  2113. union_format: The format to use when combining schemas from unions together. Can be one of:
  2114. - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
  2115. keyword to combine schemas (the default).
  2116. - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
  2117. keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
  2118. type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
  2119. `any_of`.
  2120. schema_generator: The schema generator to use for generating the JSON Schema.
  2121. Returns:
  2122. A tuple where:
  2123. - The first element is a dictionary whose keys are tuples of JSON schema key type and JSON mode, and
  2124. whose values are the JSON schema corresponding to that pair of inputs. (These schemas may have
  2125. JsonRef references to definitions that are defined in the second returned element.)
  2126. - The second element is a JSON schema containing all definitions referenced in the first returned
  2127. element, along with the optional title and description keys.
  2128. """
  2129. for cls, _ in models:
  2130. if isinstance(cls.__pydantic_core_schema__, _mock_val_ser.MockCoreSchema):
  2131. cls.__pydantic_core_schema__.rebuild()
  2132. instance = schema_generator(by_alias=by_alias, ref_template=ref_template, union_format=union_format)
  2133. inputs: list[tuple[type[BaseModel] | type[PydanticDataclass], JsonSchemaMode, CoreSchema]] = [
  2134. (m, mode, m.__pydantic_core_schema__) for m, mode in models
  2135. ]
  2136. json_schemas_map, definitions = instance.generate_definitions(inputs)
  2137. json_schema: dict[str, Any] = {}
  2138. if definitions:
  2139. json_schema['$defs'] = definitions
  2140. if title:
  2141. json_schema['title'] = title
  2142. if description:
  2143. json_schema['description'] = description
  2144. return json_schemas_map, json_schema
  2145. # ##### End JSON Schema Generation Functions #####
  2146. _HashableJsonValue: TypeAlias = Union[
  2147. int, float, str, bool, None, tuple['_HashableJsonValue', ...], tuple[tuple[str, '_HashableJsonValue'], ...]
  2148. ]
  2149. def _deduplicate_schemas(schemas: Iterable[JsonDict]) -> list[JsonDict]:
  2150. return list({_make_json_hashable(schema): schema for schema in schemas}.values())
  2151. def _make_json_hashable(value: JsonValue) -> _HashableJsonValue:
  2152. if isinstance(value, dict):
  2153. return tuple(sorted((k, _make_json_hashable(v)) for k, v in value.items()))
  2154. elif isinstance(value, list):
  2155. return tuple(_make_json_hashable(v) for v in value)
  2156. else:
  2157. return value
  2158. @dataclasses.dataclass(**_internal_dataclass.slots_true)
  2159. class WithJsonSchema:
  2160. """!!! abstract "Usage Documentation"
  2161. [`WithJsonSchema` Annotation](../concepts/json_schema.md#withjsonschema-annotation)
  2162. An annotation used to override the JSON Schema for a type.
  2163. This is useful when you want to set a JSON Schema for a type that don't produce any JSON Schemas by default
  2164. (e.g. [`Callable`][collections.abc.Callable]).
  2165. If `mode` is set this will only apply to that schema generation mode, allowing you to set different JSON Schemas for validation and serialization.
  2166. !!! note
  2167. If the `WithJsonSchema` annotation is coupled with the [`Field()`][pydantic.Field] function, the behavior overriding will vary depending on the location:
  2168. * If the [`Annotated`][typing.Annotated] metadata is specified at the "top-level" field, `Field()` metadata arguments
  2169. (excluding [constraints](../concepts/fields.md#field-constraints)) such as `title` and `description` will be applied on
  2170. top of the `WithJsonSchema`, no matter the order:
  2171. ```python
  2172. from typing import Annotated
  2173. from pydantic import BaseModel, Field, WithJsonSchema
  2174. class Model(BaseModel):
  2175. field: Annotated[
  2176. int,
  2177. Field(title='My Field'),
  2178. WithJsonSchema({'type': 'integer', 'extra': 'data'}),
  2179. ]
  2180. Model.model_json_schema()['properties']['field']
  2181. #> {'type': 'integer', 'extra': 'data', 'title': 'My Field'}
  2182. ```
  2183. * If the [`Annotated`][typing.Annotated] metadata is specified on a specific inner type, `WithJsonSchema` will unconditionally
  2184. override the JSON Schema:
  2185. ```python
  2186. from typing import Annotated
  2187. from pydantic import BaseModel, Field, WithJsonSchema
  2188. class Model(BaseModel):
  2189. field: list[
  2190. Annotated[
  2191. int,
  2192. Field(title='My Field'),
  2193. WithJsonSchema({'type': 'integer', 'extra': 'data'}),
  2194. ]
  2195. ]
  2196. Model.model_json_schema()['properties']['field']
  2197. #> {'items': {'extra': 'data', 'type': 'integer'}, 'title': 'Field', 'type': 'array'}
  2198. ```
  2199. See also the documentation about [the annotated pattern](../concepts/fields.md#the-annotated-pattern).
  2200. """
  2201. json_schema: JsonSchemaValue | None
  2202. mode: Literal['validation', 'serialization'] | None = None
  2203. def __get_pydantic_json_schema__(
  2204. self, core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler
  2205. ) -> JsonSchemaValue:
  2206. if self.mode is not None and self.mode != handler.mode:
  2207. return handler(core_schema)
  2208. if self.json_schema is None:
  2209. # This exception is handled in pydantic.json_schema.GenerateJsonSchema._named_required_fields_schema
  2210. raise PydanticOmit
  2211. else:
  2212. return self.json_schema.copy()
  2213. def __hash__(self) -> int:
  2214. return hash(type(self.mode))
  2215. class Examples:
  2216. """Add examples to a JSON schema.
  2217. If the JSON Schema already contains examples, the provided examples
  2218. will be appended.
  2219. If `mode` is set this will only apply to that schema generation mode,
  2220. allowing you to add different examples for validation and serialization.
  2221. """
  2222. @overload
  2223. @deprecated('Using a dict for `examples` is deprecated since v2.9 and will be removed in v3.0. Use a list instead.')
  2224. def __init__(
  2225. self, examples: dict[str, Any], mode: Literal['validation', 'serialization'] | None = None
  2226. ) -> None: ...
  2227. @overload
  2228. def __init__(self, examples: list[Any], mode: Literal['validation', 'serialization'] | None = None) -> None: ...
  2229. def __init__(
  2230. self, examples: dict[str, Any] | list[Any], mode: Literal['validation', 'serialization'] | None = None
  2231. ) -> None:
  2232. if isinstance(examples, dict):
  2233. warnings.warn(
  2234. 'Using a dict for `examples` is deprecated, use a list instead.',
  2235. PydanticDeprecatedSince29,
  2236. stacklevel=2,
  2237. )
  2238. self.examples = examples
  2239. self.mode = mode
  2240. def __get_pydantic_json_schema__(
  2241. self, core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler
  2242. ) -> JsonSchemaValue:
  2243. mode = self.mode or handler.mode
  2244. json_schema = handler(core_schema)
  2245. if mode != handler.mode:
  2246. return json_schema
  2247. examples = json_schema.get('examples')
  2248. if examples is None:
  2249. json_schema['examples'] = to_jsonable_python(self.examples)
  2250. if isinstance(examples, dict):
  2251. if isinstance(self.examples, list):
  2252. warnings.warn(
  2253. 'Updating existing JSON Schema examples of type dict with examples of type list. '
  2254. 'Only the existing examples values will be retained. Note that dict support for '
  2255. 'examples is deprecated and will be removed in v3.0.',
  2256. UserWarning,
  2257. )
  2258. json_schema['examples'] = to_jsonable_python(
  2259. [ex for value in examples.values() for ex in value] + self.examples
  2260. )
  2261. else:
  2262. json_schema['examples'] = to_jsonable_python({**examples, **self.examples})
  2263. if isinstance(examples, list):
  2264. if isinstance(self.examples, list):
  2265. json_schema['examples'] = to_jsonable_python(examples + self.examples)
  2266. elif isinstance(self.examples, dict):
  2267. warnings.warn(
  2268. 'Updating existing JSON Schema examples of type list with examples of type dict. '
  2269. 'Only the examples values will be retained. Note that dict support for '
  2270. 'examples is deprecated and will be removed in v3.0.',
  2271. UserWarning,
  2272. )
  2273. json_schema['examples'] = to_jsonable_python(
  2274. examples + [ex for value in self.examples.values() for ex in value]
  2275. )
  2276. return json_schema
  2277. def __hash__(self) -> int:
  2278. return hash(type(self.mode))
  2279. def _get_all_json_refs(item: Any) -> set[JsonRef]:
  2280. """Get all the definitions references from a JSON schema."""
  2281. refs: set[JsonRef] = set()
  2282. stack = [item]
  2283. while stack:
  2284. current = stack.pop()
  2285. if isinstance(current, dict):
  2286. for key, value in current.items():
  2287. if key == 'examples' and isinstance(value, list):
  2288. # Skip examples that may contain arbitrary values and references
  2289. # (e.g. `{"examples": [{"$ref": "..."}]}`). Note: checking for value
  2290. # of type list is necessary to avoid skipping valid portions of the schema,
  2291. # for instance when "examples" is used as a property key. A more robust solution
  2292. # could be found, but would require more advanced JSON Schema parsing logic.
  2293. continue
  2294. if key == '$ref' and isinstance(value, str):
  2295. refs.add(JsonRef(value))
  2296. elif isinstance(value, dict):
  2297. stack.append(value)
  2298. elif isinstance(value, list):
  2299. stack.extend(value)
  2300. elif isinstance(current, list):
  2301. stack.extend(current)
  2302. return refs
  2303. AnyType = TypeVar('AnyType')
  2304. if TYPE_CHECKING:
  2305. SkipJsonSchema = Annotated[AnyType, ...]
  2306. else:
  2307. @dataclasses.dataclass(**_internal_dataclass.slots_true)
  2308. class SkipJsonSchema:
  2309. """!!! abstract "Usage Documentation"
  2310. [`SkipJsonSchema` Annotation](../concepts/json_schema.md#skipjsonschema-annotation)
  2311. Add this as an annotation on a field to skip generating a JSON schema for that field.
  2312. Example:
  2313. ```python
  2314. from pprint import pprint
  2315. from typing import Union
  2316. from pydantic import BaseModel
  2317. from pydantic.json_schema import SkipJsonSchema
  2318. class Model(BaseModel):
  2319. a: Union[int, None] = None # (1)!
  2320. b: Union[int, SkipJsonSchema[None]] = None # (2)!
  2321. c: SkipJsonSchema[Union[int, None]] = None # (3)!
  2322. pprint(Model.model_json_schema())
  2323. '''
  2324. {
  2325. 'properties': {
  2326. 'a': {
  2327. 'anyOf': [
  2328. {'type': 'integer'},
  2329. {'type': 'null'}
  2330. ],
  2331. 'default': None,
  2332. 'title': 'A'
  2333. },
  2334. 'b': {
  2335. 'default': None,
  2336. 'title': 'B',
  2337. 'type': 'integer'
  2338. }
  2339. },
  2340. 'title': 'Model',
  2341. 'type': 'object'
  2342. }
  2343. '''
  2344. ```
  2345. 1. The integer and null types are both included in the schema for `a`.
  2346. 2. The integer type is the only type included in the schema for `b`.
  2347. 3. The entirety of the `c` field is omitted from the schema.
  2348. """
  2349. def __class_getitem__(cls, item: AnyType) -> AnyType:
  2350. return Annotated[item, cls()]
  2351. def __get_pydantic_json_schema__(
  2352. self, core_schema: CoreSchema, handler: GetJsonSchemaHandler
  2353. ) -> JsonSchemaValue:
  2354. raise PydanticOmit
  2355. def __hash__(self) -> int:
  2356. return hash(type(self))
  2357. def _get_typed_dict_config(cls: type[Any] | None) -> ConfigDict:
  2358. if cls is not None:
  2359. try:
  2360. return _decorators.get_attribute_from_bases(cls, '__pydantic_config__')
  2361. except AttributeError:
  2362. pass
  2363. return {}
  2364. def _get_ser_schema_for_default_value(schema: CoreSchema) -> core_schema.PlainSerializerFunctionSerSchema | None:
  2365. """Get a `'function-plain'` serialization schema that can be used to serialize a default value.
  2366. This takes into account having the serialization schema nested under validation schema(s).
  2367. """
  2368. if (
  2369. (ser_schema := schema.get('serialization'))
  2370. and ser_schema['type'] == 'function-plain'
  2371. and not ser_schema.get('info_arg')
  2372. ):
  2373. return ser_schema
  2374. if _core_utils.is_function_with_inner_schema(schema):
  2375. return _get_ser_schema_for_default_value(schema['schema'])