NewYour coding agent can read the release notes before it upgrades.Set up the MCP server →
PyPI
PyPI, #972 most downloaded on PyPI
Datamodel Code Generator
Latest stable
0.92.0
Last release 12 days ago
10 Nov 2026
Ships fairly regularly
a new release about every 2 weeks
Nearly every release is documented
notes for 60 of the last 60 stable releases
1 version withdrawn
withdrawn after publishing
7 years old
296 releases · first in 2019
Drag across the ruler to compare, or tap a release to open it.
Client generation skips unsupported operations with a warning instead of failing - When generating a Python HTTP client, an operation that is refused
Error: and exit code 2, and no longer makes the Python API raise datamodel_code_generator.Error. This covers a path placeholder with no path parameter, security the client cannot send (an unavailable scheme, or two schemes that own the same header in one requirement), a media key that is not a media type, a binary string that would be sent as text, a body, form member or parameter that no builtin encoding writes, and colliding expanded form member names. The operation is now left out of the generated client with no method, type or documentation, and each skipped operation gets one UserWarning that names its method, path, operationId and the reasons. All other operations are still generated. Generation still fails when every operation would be skipped, when a protocol helper calls a refused operation, and for any document-level or setting-level refusal such as an unresolvable server URL. Workflows that relied on the failure to catch unsupported operations now succeed with a partial client, so they should check for these warnings instead (#6595)<!-- Release notes generated using configuration in .github/release.yml at main -->
Full Changelog: https://github.com/datamodel-code-generator/datamodel-code-generator/compare/0.91.0...0.92.0
Your coding agent can read these notes before it upgrades. Set up the MCP server →
Empty unused classes for x-python-import schemas referenced outside $defs are no longer generated - Some schemas carry x-python-import, are reached th
$defs are no longer generated - Some schemas carry x-python-import, are reached through a JSON pointer outside $defs or definitions (for example /components/Options in the same file or other.json plus /components/Options), and are named only by fields. Previously such a schema was also written as an empty class that nothing used, such as class Options(BaseModel): pass, next to the import that types those fields. That class is now left out, which matches how these schemas are already handled in $defs. Fields that reference the schema still use the imported class, such as OrderedDict. A schema that another model uses as a base, including the subclasses made by --reuse-model, keeps its model. Code that imported or referenced the removed empty class from the generated module must be updated. (#6415)--naming-strategy enclosing-model now follow the restored owner name in modular output - When several input files each define a model with the same name (for example Parent), the naming plan numbers the later one across the input and its own module then gives it back its base name. Models whose names were composed from that numbered owner (inline children, grandchildren, ordinal, tagged or composed models) now also take the name composed from the restored name, e.g. ParentChild and ParentChildGrand instead of names built from the numbered owner such as Parent1Child, wherever the module leaves those names free. Code that imports or references the previously generated nested class names must be updated. Default naming is unaffected (#6417)items or prefixItems but no array type are no longer typed as lists - JsonSchemaObject.is_array now treats a schema as an array only when its type is array, when array is in its type list and items are given, or when it has items but no declared type. Before, any items or prefixItems made the schema an array. A schema like {"type": ["string", "null"], "items": {...}} used to produce list[int] | None and now produces str | None. {"type": "string", "items": ...} now produces str. {"type": ["object", "null"], "items": ..., "properties": ...} now produces Object | None instead of a union that also included list[int]. {"type": ["integer", "boolean"], "prefixItems": ...} now produces int | bool instead of list[Any]. The old output rejected every valid value, but the field types in generated models, root models and type aliases change, so code that relied on the old list types may need updating (#6419)Any, those constraints go on a new type alias named after the parent model with a PatternProperty suffix, for example PArrPatternProperty = TypeAliasType("PArrPatternProperty", Annotated[list[str], Field(min_length=2)]). In every mode, including the default options, this applies to the minItems/maxItems of an array value. Under --field-constraints and --use-annotated (as in the presets), it also applies to bounds, lengths and pattern. As a result, dict value hints change from dict[constr(pattern=r'^a'), list[str]] to dict[constr(pattern=r'^a'), PArrPatternProperty], modules gain the new alias names plus TypeAliasType/Annotated imports, a Pydantic dataclass can switch to @dataclass(config=ConfigDict(regex_engine="python-re")) when the alias holds a lookahead pattern, and data that breaks the value's schema constraints but validated before is now rejected (#6424)--field-constraints or --use-annotated, a map whose patterns share a value type but carry different constraints used to collapse into one value type. It is now written as a union of aliases, for example dict[constr(pattern=r'^a|b$'), int] becomes dict[constr(pattern=r'^a|b$'), OverlapPatternProperty | OverlapPatternProperty1]. This also applies to root models, list items and nested maps (#6424)--generate-schema-validators, the value type in each __json_schema_pattern_properties__ rule now refers to the alias that holds the value's constraints. For example ('^x', str) becomes ('^x', RootItemPatternProperty), where RootItemPatternProperty is Annotated[str, Field(max_length=3, min_length=2)], so the runtime validator now rejects values that break minLength, maxLength, minItems and similar constraints it used to accept (#6424)--use-msgspec-meta-for-map-keys, msgspec checks the key patterns. A pattern map with one value type therefore now writes that value as an alias such as PIntPatternProperty: TypeAlias = Annotated[int, Meta(ge=0)] instead of the plain type, so msgspec now enforces the value's constraints. Maps with several value types keep their plain types (#6424)allOf member beside a $ref declares the same property, for example {type: string} in one member and {maxLength: 3} in another, the generated field used to take its constraints from the first declaration only. Request and response models under --read-only-write-only-model-type took them from the last one. Now each declaration gets the bounds, multipleOf and pattern of all of them, so a field that was str becomes constr(max_length=3), Annotated[str, Meta(max_length=3)] or Field(None, max_length=3). A subclass that overrides the property also gets the combined constraints, for example min_length=1 plus max_length=3, where it used to have only its own. The field keeps the type, default and description it had before. Positional tuple declarations do not get item counts, and $ref declarations neither receive nor pass on constraints. A new warning is emitted when the declarations have no common value for a keyword. This happens by default in every dialect and output model type, with or without --intersect-allof-keywords and --intersect-combined-schema-keywords, so generated models can now reject payloads they used to accept (#6425)anyOf or oneOf and the branch and the other allOf members declare the same property with different bounds, multipleOf or pattern, the generated class for each union member now declares that property itself with all the check keywords combined. Previously the class inherited the field from its first base (Pydantic, dataclasses, TypedDict) or its last base (msgspec), so some constraints were lost. For example, Inline4(Inline1, Inline3) now declares x: conint(ge=0, le=10) | None = None, where it used to inherit only conint(ge=0). Generated models now reject values they used to accept (#6426)TypedDict with no bases. For example, class Refs3(TypedDict) replaces class Refs3(Dog, Refs1). Code that relies on the previous class hierarchy or on static assignability to the base types may need updating (#6426)Literal now keep their schema pattern - When an object property declares both enum and pattern and the enum is written as a Literal with its constraints on the field (for example --enum-field-as-literal together with --field-constraints), the generated field now includes the pattern, e.g. inline: Literal['aa', 'b'] | None = Field(None, pattern=...). Before, the pattern was silently dropped at object properties, while root models and const fields already kept it. This affects BaseModel, Annotated and Pydantic dataclass output. Enum values that fail the pattern used to be accepted and are now rejected at validation time. If the Rust regex engine refuses the pattern, it can now also add regex_engine="python-re" to the model config. With --ignore-enum-constraints the output is unchanged, and with default options (enums written as classes) nothing changes (#6428)Literal under --field-constraints - When a oneOf or anyOf of const values is rendered as a Literal and its schema declares the single type of those consts (for example "type": "integer" beside anyOf: [{"const": 1}, {"const": 5}] with maximum: 3), the generator now carries the sibling constraint keywords onto the generated field and onto a Literal root model. Before this change they were silently dropped. For example, consts: Literal['a', 'bb', 'ccc'] | None = None becomes consts: Literal['a', 'bb', 'ccc'] | None = Field(None, min_length=2), consts: Literal[1, 5] | None = Field(None, le=3) is now emitted, and a RootModel[Literal['a', 'bb']] gains root: Literal['a', 'bb'] = Field(..., max_length=1). Regenerated models now reject values that earlier generated models accepted. Untyped oneOf or anyOf schemas get no constraints, --filter-literal-values still drops field constraints when it has already removed the rejected values, and default output is unchanged (#6429)dict or dict[str, str] written by --type-overrides with --type-overrides-replace-whole-type, the schema's minProperties/maxProperties are now emitted as Meta(min_length=...)/Meta(max_length=...), for example sized: Annotated[dict, Meta(min_length=1)] | UnsetType. Before, they were dropped with a "msgspec.Meta does not take min_length on dict" warning. Generated Structs now reject payloads with too few or too many keys that used to decode, and those warnings no longer appear. OrderedDict and Counter classes still get no lengths, because msgspec refuses them there (#6431)--use-unique-items-as-set-by-value are now written as the sets their types write - Array defaults that sit where the final types write a set (the field's own list, or a set type alias inside a list, union, map or tuple position) are now generated as set literals, or as frozenset(...) under --use-generic-container-types, instead of nested lists or mutable sets; for example frozen dataclasses now emit levels: frozenset[int] | None = frozenset({1}) instead of field(default_factory=lambda: {1}), and pydantic emits rows: list[Row] | None = [{1, 2}] where the nested items used to stay lists, so the runtime type of these default values changes (#6440)frozenset and not a mutable set, frozen dataclasses whose fields carry such defaults now count as hashing by value under --use-unique-items-as-set-by-value, so uniqueItems arrays of them change type, for example limits: Sequence[Limits] | None becomes limits: frozenset[Limits] | None, which breaks code that indexes into or relies on the order of those fields (#6440)extra_items now writes uniqueItems arrays as sets under --use-unique-items-as-set - When generating typing.TypedDict models with --use-unique-items-as-set (and also --use-unique-items-as-set-by-value), the extra_items type built from an additionalProperties schema now goes through the same uniqueItems-to-set conversion as regular fields. Arrays that declare uniqueItems: true are now written as set[...], or frozenset[...] with --use-generic-container-types, where they used to be list[...] or Sequence[...]. This covers the array itself, anyOf/oneOf members, map values and the inner arrays of nested arrays. For example, extra_items=list[int] becomes extra_items=set[int] and extra_items=dict[str, list[int]] becomes extra_items=dict[str, set[int]]. Arrays whose items cannot be hashed, such as TypedDict items, stay lists. With --reuse-model, an array stays a list when a model merged into it does not declare uniqueItems. Code that treats these extra values as lists (indexing, ordering, keeping duplicates) or type-checks them against list may need updating (#6441)extra_items from array type lists now includes the other type list members - When an additionalProperties schema (or another schema read as a lightweight type) declares a type list containing array alongside other types, such as ["array", "string"] or ["array", "integer", "null"], the generated type is now a union like str | list[int] or int | list[int] | None instead of only list[int], matching the type generated for a property with the same schema; regenerated typing.TypedDict output accepts the strings, integers and nulls the schema allows, and code that assumed these values were always lists may need type narrowing to satisfy type checkers (#6442)extra_items now written unquoted when the classes it names already exist - When generating typing.TypedDict output, the extra_items= class keyword used to be a string whenever it named a generated class, for example extra_items='list[Item]', extra_items='FlaggedRequest' or extra_items='b.Bar | c.Baz | Near'. It is now written as a plain type expression, for example extra_items=list[Item] or extra_items=b.Bar, whenever every class it names is defined by the time the class statement runs: either declared earlier in the same module or imported from another module. It stays a string only when it names the class itself or a class declared later in the same module. As a result, the runtime __extra_items__ value is the real type instead of a forward reference, which lets Pydantic TypeAdapter resolve these TypedDicts where it used to fail with class-not-fully-defined. Generated files change wherever this applies. Because these unquoted names are now evaluated when the class is defined, the import-cycle check also counts them, so modular TypedDict output with cross-module extra_items in an import cycle may now merge modules into a shared _internal.py (#6443)--output-model-type msgspec.Struct, a union of members of one type that carry different constraints, where no member carries only the constraints they all share, used to be generated with no Meta(...) at all. It is now generated with the constraints every member implies, written once. For example, anyOf: [{type: string, minLength: 2, maxLength: 3}, {type: string, maxLength: 3, pattern: '^a'}] changes from str to Annotated[str, Meta(max_length=3)], anyOf: [{type: integer, minimum: 1, maximum: 5}, {type: integer, minimum: 7}] changes from int to Annotated[int, Meta(ge=1)], and aliases such as TwoBases: TypeAlias = int become TwoBases: TypeAlias = Annotated[int, Meta(le=100)] (list items too, e.g. list[Annotated[int, Meta(le=100)]]). Float members also take into account the int and Decimal members that msgspec decodes as floats. The generated type annotations and aliases are different, and the models now reject payloads they used to accept that every branch of the schema rejects (e.g. "abcd", 0, 101). The dropped-constraint warning for these fields now ends with , and it keeps max_length=3, which every member implies (or whichever constraints are kept). This is on by default and has no opt-out flag (#6450)$ref of a lone allOf member now produce a site subclass under --intersect-combined-schema-keywords - With --intersect-combined-schema-keywords, a field, array item or union branch like allOf: [{$ref: A, required: [id]}] was generated as the referenced model A. Here the required names sit next to the $ref inside the single allOf member, and A accepted objects that were missing them. The required names are now read from inline allOf members as well, so the site is generated as a subclass of A (for example RefSibling(A)) that requires them. The field annotation now names a new class, and payloads such as {} or {"name": "a"} that used to validate are now rejected (#6472)--intersect-combined-schema-keywords - With --intersect-combined-schema-keywords, take a site subclass built from an allOf that references a nullable model plus an inline member whose type excludes null, such as allOf: [{$ref: Nullable}, {type: object, required: [id]}]. It used to be written as nullable (for example ObjectMember | None) because only the outer schema's own type was checked for null. Inline allOf members are now checked too, so the field is annotated ObjectMember and a null payload is rejected (#6472)$ref points to a whole external document whose root schema declares x-python-import and would generate an empty class (no fields and no root type), that empty class is no longer written next to the import; fields that reference the document keep the imported class. A root that generates a model with fields or a root type, such as a RootModel of a map, is written as in 0.90.0, as is a root used as a base class and the root of the input document. (#6480, #6554)x-python-import reached through a pointer no longer generate an unused empty class - When a $ref reaches a file's root through a definition that refers back to it, and the root has x-python-import and would generate an empty class, that empty class is no longer written; fields keep the imported type. A root that generates a model with fields or a root type is written as in 0.90.0. (#6484, #6554)--use-enum-values-in-discriminator - When --use-enum-values-in-discriminator is used and a variant is tagged by a member of a plain Enum (one with no value base, so not StrEnum, IntEnum or the (str, Enum) that --use-subclass-enum writes), the tag field is now written as Literal[PetType.cat, 'cat'] instead of Literal[PetType.cat]. Before, the discriminated union rejected every JSON payload. It now accepts them, but a field parsed from JSON holds the plain value (for example 'cat') instead of the Enum member, and code that type-checks against the old annotation may need updating. Python callers that pass PetType.cat keep working. Enums with a value base keep Literal[PetType.cat], and msgspec output is unchanged (#6495)--use-enum-values-in-discriminator, a plain Enum member tag now carries its value too. So when one variant is tagged by a plain Enum member (for example Plain.int_1) and another variant's tag is a literal with the same value (Literal[1]), the union no longer gets Field(None, discriminator='k') and becomes a plain union. The Enum-tagged variant's field is typed as the Enum class (k: Plain) instead of Literal[Plain.int_1] (#6495)$ref branches now take the allOf members under --distribute-allof-over-unions - With --distribute-allof-over-unions (and the 20261104 presets that enable it), a $ref branch of an anyOf or oneOf whose target has an OpenAPI discriminator is now expanded into one generated class per subtype, each inheriting from the subtype and carrying the allOf members beside or around the union (for example Owned1(Cat), Owned2(Dog)). Those variants now require the members' properties, such as owner, instead of accepting payloads without them. Classes for later branches are renumbered in union order, so the class previously generated as Owned1(Fish) is now Owned3(Fish). In an allOf that holds such a union, the discriminated subtypes are no longer dropped, which also changes the numbered class names there. Code that imports or references the old numbered class names, or relies on the looser validation, must be updated. Output without the option is unchanged (#6497)$ref branch classes beside an allOf are tagged by the schema they name under --distribute-allof-over-unions - With --distribute-allof-over-unions (and the 20261104 presets), the class generated for each $ref branch of a discriminated oneOf that sits beside an allOf used to take the branch's position as its discriminator tag (for example Literal['0'] and Literal['1'], or msgspec tag='0') when the discriminator had no mapping. Tagged msgspec Structs also lost their mapping key, so the union rejected every payload. These classes now take the tag of the schema the branch names: Literal['Cat'] or the mapping key such as Literal['c'], and tag='Cat' or tag='c' for tagged msgspec Structs. Regenerated code therefore has different tag values, and code that builds or matches the old positional tags must be updated. Output without the option is unchanged (#6498)$ref branch classes with sibling properties now use the referenced schema name - When a oneOf of $ref branches has properties or required beside it and a discriminator without a mapping, each branch's generated class (for example Owned1(Cat) and Owned2(Dog)) now types the discriminator field with the name of the schema the branch references (Literal['Cat'], Literal['Dog']) instead of the branch's position in the union (Literal['0'], Literal['1']). This affects the default output for pydantic, dataclass and msgspec models. The old output rejected every payload, so this is a fix, but any code that built or matched these models using the positional literal values has to be updated (#6499)$ref are now enforced in default msgspec and Pydantic dataclass output - When a property is an allOf of one $ref plus extra keywords (maxLength beside the allOf, minItems or pattern in a second member, or a bound beside a $ref that points to an allOf of one $ref), the default msgspec.Struct and pydantic_v2.dataclass output used to type the field by the target alone and drop the extra keywords. The field now writes them, e.g. name: Annotated[Str, Meta(max_length=5)] | UnsetType = UNSET instead of name: Str | UnsetType = UNSET. Type aliases built from such a site now carry them too, e.g. Wd: TypeAlias = Annotated[Q, Meta(le=10)] instead of Wd: TypeAlias = Q, and Score = TypeAliasType("Score", Annotated[Count, Field(..., le=100)]) instead of TypeAliasType("Score", Count). As with other $ref siblings, these keywords are also read in draft-07 and OpenAPI 3.0 schemas unless --ignore-ref-siblings-by-schema-version is set. Generated models now reject payloads they used to accept, such as an 11 where the site adds maximum: 10. Default Pydantic BaseModel output, whose field names a root model class, is unchanged, and TypedDict output writes no constraints (#6510)--collapse-root-models and --use-type-alias - When root-model collapse inlines the target type, or the field names a type alias, the field now gets the constraints its allOf site adds. For Pydantic this looks like count: int | None = Field(None, ge=5) instead of count: int | None = None and q_allof: conint(ge=1) | None = Field(None, le=10) instead of q_allof: conint(ge=1) | None = None. For msgspec it looks like wd_prop: Annotated[int, Meta(ge=1, le=10)] | UnsetType = UNSET instead of Annotated[int, Meta(ge=1)]. Validation is stricter: values the schema rejects are no longer accepted (#6510)Annotated to carry site constraints - A pydantic_v2.dataclass field that writes no Field() call now takes the site constraints as Annotated metadata, e.g. count: Annotated[Count | None, Field(ge=5)] = None instead of count: Count | None = None, and id: Annotated[Id, Field(max_length=5)] instead of id: Id. A field that already writes a Field(...) call gets the constraints added to that call. The field keeps its default and its place in the constructor, but code that inspects annotations sees a different shape (#6510)--collapse-root-models with --field-constraints or --use-annotated (as in the presets), a length keyword such as maxLength beside a union of a model and a plain string type used to be written on the whole field (text: Item | str | None = Field(None, max_length=3)), which made Pydantic raise TypeError for every object value. It is now written on the string member instead: Item | constr(max_length=3) | None = None with --field-constraints, or O | Annotated[str, StringConstraints(max_length=3)] | None = None with --use-annotated. The generated code gains a constr or StringConstraints import and loses the keyword from Field(). Object values now validate, and strings are checked the same way as before. Field metadata and the JSON schema Pydantic produces for these fields also change (#6519)constrained_value_type used to treat only TypeAliasBase subclasses as aliases. It now treats any DataModel whose form is "alias" as one. With msgspec.Struct output, root types are written as plain assignments like Level = Annotated[int, Meta(ge=1)]. A reference to one of these is now followed to its underlying value type, where before it was treated like an opaque class reference. As a result, constraints declared where the type is used, such as sibling keywords next to the single $ref of an allOf, are now written on the field. For example, Annotated[int, Meta(ge=1)] becomes Annotated[Annotated[int, Meta(ge=1)], Meta(le=10)], and a plain str field can become Annotated[str, Meta(max_length=5)]. Generated models now enforce constraints that used to be silently dropped, so data that passed validation before may now be rejected (#6543)Pydantic does not take max_length on AwareDatetime; Model.stamp_len_prop is generated without this constraint.. The msgspec 64-bit integer-limit warning now also covers fields typed by such a site. Workflows that treat these warnings as failures may be affected (#6510)--omit-incomplete-model-defaults is not set and a property's object default lacks required fields of its model (its own or a base's), generation for Pydantic v2 BaseModel, Pydantic v2 dataclass and msgspec Struct output now emits one UserWarning listing every such field. It starts with The default of Model.field or The defaults of ..., says the generated models will reject input that leaves the property out, and suggests --omit-incomplete-model-defaults. Generated code does not change, and dataclass and TypedDict outputs do not warn. Builds or tests that turn warnings into errors, such as -W error or pytest filterwarnings = error, or that expect empty stderr, can now fail or see new output for these schemas (#6518)standard-py3XX-20261106 and practical-py3XX-20261106Every new option is off by default and has a --no- form.
--read-allof-parents-in-mro-order - Read the allOf parents of every inherited schema in the order of the class bases, so a property that several bases declare takes the nearer base's constraints and description, also where an allOf lists a base before its own descendant. Set by the 20261106 presets.--keep-shared-members-on-collapsed-root-models - Under --collapse-root-models, keep each member of a root type that collapse inlined at several sites at every site when a root model that member names is collapsed later. Set by the 20261106 presets.--collapse-constrained-root-models-as-annotated - Under --collapse-root-models with --use-annotated, inline a root model of a string with constraints into its holder's container as Annotated[str, Field(...)], which keeps the constraints. Set by the 20261106 presets.--remove-unused-models-beside-type-overrides - Remove the models that nothing uses also from a module a model-level --type-overrides key takes a model out of. Set by the 20261106 presets.--keep-self-referencing-array-items - Keep the items of an array whose items name the array itself (RootModel[list[Node | Leaf]]) instead of writing a bare list. Set by the 20261106 presets.--use-enum-field-as-literal-in-operations - Write the enum of an operation's request body or response as a root model of a Literal where the enum-as-literal options would write a definition's enum so. Set by the 20261106 presets.--dedupe-numbered-request-response-variants - Merge a Request or Response variant of a numbered model into the variant of the model it was numbered from where they render the same. Set by the 20261106 presets.--use-bytes-for-content-media-type - Type a string of an OpenAPI document that has a contentMediaType and no contentEncoding as bytes, as a format: binary string is. Set by the 20261106 presets.--use-x-python-type-as-written - Write a field's x-python-type as given: a union spelled Optional[...] or Union[...] types the field as one, and a compatible container class such as tuple or MutableSequence is written around the schema's types. Set by the 20261106 presets.--apply-field-options-to-every-field - Apply the field options to every kind of field (GraphQL fields, true/false property schemas, required names without a property, discriminator tag fields). Set by the 20261106 presets.--merge-message-trait-headers - AsyncAPI only: give a message the headers of all its traits, merged in order, and then its own headers, which win. Set by the 20261106 presets.--keep-defaults-of-inherited-required-fields - With --use-default, keep the default a schema gives a property that only a schema it inherits from lists as required. Set by the 20261106 presets.--omit-incomplete-model-defaults - Write a property whose object default lacks required fields of its model (default: {}) without that default, so input that leaves the property out is valid. Set by the 20261106 presets; without it dcg now warns (see New warnings).--keep-false-dataclass-arguments - Write every dataclass decorator argument set to false, such as eq=False, instead of leaving it out. Set by the 20261106 presets.--keep-content-parameter-refs - Type a parameter whose content media schema is a $ref by the model the $ref names, as a schema parameter is. Set by the 20261106 presets.--skip-path-extension-keys - In the paths scope, skip a key of paths that begins with x-, as the api scope does. Set by the 20261106 presets.--reuse-every-reached-input-model-type - With --input-model-ref-strategy reuse-all or reuse-foreign, reach the types to reuse through every model kind and write no copy of an imported type. Set by the 20261106 presets.--use-msgspec-forbid-unknown-fields - msgspec.Struct output only: write forbid_unknown_fields=True on a Struct whose schema admits no property but its own. Set by the 20261106 presets.--keep-reference-null-on-collapsed-root-models - Under --collapse-root-models, keep the null of a root model that admits null where a field, item or map value that names it takes its type. Set by the 20261106 presets.--use-strict-str-for-base64 - Under --strict-types str, write a format: byte string as Annotated[StrictStr, EncodedStr(encoder=Base64Encoder)], so Pydantic 2.10 or later refuses bytes for it; --strict-types str alone keeps Base64Str (#6240, Pydantic v2 only). Set by the 20261106 presets.--use-typed-nullable-map-values (#6434).--no- form of each new boolean option above is also available.properties with a discriminator but no mapping is tagged by the schema names instead of '0' / '1', which rejected every payload (#6459).unevaluatedProperties: false in an inline allOf member now closes the model (extra='forbid', TypedDict closed=True) (#4742).Field as Field_aliased) now writes the alias in every model, so it imports (#6488).--use-enum-values-in-discriminator now writes the value beside the member, so the union accepts its payloads (#6390).$ref are now checked where the field's type is no class (#6024, #6234): The keywords an allOf site adds to its one $ref (maxLength beside allOf: [$ref], the minItems or pattern of another member, a bound beside a $ref to an allOf of one $ref) are checked where the field's type is no class: in the default msgspec and Pydantic dataclass output, which write such types as type aliases, and under --use-type-alias and --collapse-root-models; the default Pydantic BaseModel output, whose field names a root model class, is unchanged. A Pydantic dataclass field writes them in the Field() call it already writes, and otherwise in Annotated metadata (id: Annotated[Id, Field(max_length=5)]), so every field keeps its place, its default and its positional use in the constructor. As a $ref beside the same keyword already does, the $ref siblings are read in every dialect, also draft-07 and OpenAPI 3.0; --ignore-ref-siblings-by-schema-version reads them as those specifications do.--intersect-allof-keywords are written with the integer bounds they admit (ge=0.5 becomes ge=1); 0.90.0 raised TypeError on every decode (#6024).Literal of integers beside a float branch (#4740).prefixItems positions after an items: false are not checked by the generated model (#4849).additionalProperties: false) with patternProperties (#6388).--omit-incomplete-model-defaults leaves out (#4828).<!-- Release notes generated using configuration in .github/release.yml at main -->
Full Changelog: https://github.com/datamodel-code-generator/datamodel-code-generator/compare/0.90.0...0.91.0
Default remote lockfile of generate() now lives beside the loaded pyproject.toml - When generate() is given a config returned by load_pyproject_config
generate() now lives beside the loaded pyproject.toml - When generate() is given a config returned by load_pyproject_config() and no explicit lockfile, its default datamodel-codegen.lock is now read, verified and updated beside the pyproject.toml that was loaded, the same place the CLI uses. Previously it was always in the caller's working directory. Projects that run generate() from a subdirectory and rely on a lock there must move the lock to the project root or pass lockfile explicitly. Remote lock support is experimental (#6201)anyOf or oneOf array member, an inner list, or a map value that breaks its maxItems or minItems now fails validation with a too_long or too_short error. This fixes a mismatch with the schema, but consumers that relied on the old, looser validation will see new validation errors (#6292)Literal or enum value, a msgspec field name) now stops generation with an error that names the schema location; before, the generated module failed at import (#6365).Error before generation - If the deepest existing parent of output, emit_model_metadata or the remote lockfile is a regular file, generate() now raises datamodel_code_generator.Error with a message such as Output path cannot be created: Not a directory: path. Previously the write failed later with a raw NotADirectoryError. The same applies to a root that does not exist, such as a missing Windows drive, which previously kept the walk testing that root. The CLI now prints a clean error instead of a traceback, and staged and job runs now name the blocking file instead of a random private staging directory. Code that catches OSError for these cases must also catch Error (#6201)Error - generate() and the CLI now report a missing input as the normal File not found Error even when the output path already exists. Previously the check that an output does not overwrite its input raised a FileNotFoundError (#6201)application/x-www-form-urlencoded or multipart/form-data request body is now checked against the schema's properties in the shared wire plan, for both the client and the FastAPI server targets and whatever style or contentType the encoding gives. A key that names no property fails generation with the MC_PARAMETER_ENCODING diagnostic, whose message reads like The other encoding of the multipart/form-data media of POST /upload names no property of its schema. This replaces the old messages An encoding names no member of its form and names no member. Documents with such stray keys that a target used to generate can now fail; for example, a FastAPI server whose multipart encoding only gives a contentType was not checked before. An encoding for a property the request model leaves out, such as a readOnly one, is no longer an error and is ignored. (#6210)__init__.py would define a model class with the same name as a module or subpackage below it (for example the class Warn in pkg/__init__.py next to pkg/Warn.py or pkg/Warn/__init__.py, or a root-level Warn class next to Warn.py), the new reject_class_named_like_submodule check now raises an error that names the class and the module, and no output is written. Earlier versions wrote these modules even though importing the submodule replaces the class name in the package. Packages whose __init__.py already loads that module before defining its classes (by importing from it, or through --all-exports-scope re-exports) are still written as before. In every other case, rename the class or the module in the input schema. (#6209) The opt-in --rename-submodules-hidden-by-classes (in the 20261104 presets) renames such a submodule instead (pkg/Warn_.py).Literal annotations that mix bytes and str values - With --output-model-type msgspec.Struct, a field or type alias may have an annotation from x-python-type or --type-overrides that holds a Literal, or a union of Literal members, with both bytes and str values, such as Literal[b'ab', 'a'] or Literal[b'ab'] | Literal['a']. Before, generation succeeded with a warning and wrote it as Literal['a'] | bytes, which msgspec cannot build a decoder for. Now generation stops with an error that names the Literal and the field or type alias. The error suggests rewriting the values as one kind, such as Literal['ab', 'a'] or bytes, or using another output model type. Users must change these annotations before they can regenerate. Other output model types are unaffected, and such a Literal inside the metadata of Annotated is still written as before (#6237)Literal (float, list or object values, and bool values for msgspec output, which writes no bool literals unless both True and False are listed), the generator writes the value's type instead and now emits a UserWarning such as a Literal of the output model cannot hold the value 1.5, so it is written as its type, which admits other values; Model.const_float is generated without this constraint. The generated code does not change. The warning does fire under default options, though: for example a const: 1.5 property in Pydantic or dataclass output, a const: true property in msgspec output, or float enums in TypedDict output, which writes enums as literals. Runs that treat warnings as errors or assert on captured warnings may now fail. When a field already has a dropped-constraints warning, the new text is added to that same warning message, so that message changes too (#6344)--schema-version - Client and FastAPI generation now raise "lists scopes for scheme ..., whose type takes none in OpenAPI 3.0" whenever the parser reads the document as 3.0, so a 3.1 or 3.2 document whose security requirements list role scopes for apiKey or http schemes now fails when generated with --schema-version 3.0, while a 3.0 document generated with --schema-version 3.1 is now accepted; likewise "Cookie style requires OpenAPI 3.2" is now decided by the version the parser reads rather than by the openapi text (#6346)BaseModel from pydantic and a submodule BaseModel), the model is now imported from its module, so the output imports and decodes (#6105).$id - Such a reference used to fall back to Any; it now resolves to the referenced schema (for example str) (#5126).pattern holding a lone surrogate now selects Python's regex engine - The model gets regex_engine="python-re" where every other pattern under the same config allows it; otherwise it keeps the default engine and warns (#6320).UnicodeEncodeError (#5983).pattern under --field-constraints and --use-annotated - The pattern beside a Literal tag made the module fail to import; it is now left out, with a warning where it rejects the tag (#6238).--model-name-map now name models as they appear in the output without the map - A key that is not a schema path is now resolved against the class names a run without the map's class-name keys generates, and every other model keeps the name it has in that output instead of moving into the name the renamed model freed. Generated class names change for some users of class-name keys: for example with {"Pet": "Cat"} and three same-named Pet schemas the output was previously Cat, Pet, PetModel and is now Cat, PetModel, PetModel1; similar shifts occur for typed nullable map value models (Tags is now Tags1) and numbered names (Tag1 is now Tag2, Pet is now Pet1). Code that imports the affected classes by name must be updated; schema-path keys are unaffected (#6202)--type-overrides now apply to root models under --collapse-root-models - A root model named by a model-level --type-overrides key is no longer inlined by --collapse-root-models; its holders now take the override type, as they already did without collapse, instead of the inlined root type. For Avro, fixed types with a logical type that a model-level override replaces now take the override type under --collapse-root-models instead of the logical type, so fields previously generated as timedelta with logical defaults now become the override type (for example bytes) with physical byte defaults (#6202)--enum-field-as-literal (for example all), a one-value enum that a union variant's tag property references is generated as a RootModel[Literal[...]], or as a TypeAliasType of the Literal for Pydantic dataclasses. The variant's tag now comes from that value instead of falling back to the schema name. When you regenerate, the variant models' tag field types change, for example type: Literal['FunctionToolCall'] becomes type: Literal['function']. Code that built or matched the old schema-name tags must be updated. The old output rejected valid payloads. Variants reached through nested choices, and inline variants, keep the previous behaviour. (#6205)_internal.py by an import cycle now use the mapping values - In modular output, models that an import cycle moves into _internal.py now have their discriminator mapping values resolved from the original schema paths, not the moved paths. Tag literals such as Literal['_internal.Cat_1'] become the mapped values, such as Literal['c']. The old output rejected every payload. (#6205)$ref now merge in the referenced schema in generated clients and FastAPI servers - In an OpenAPI 3.1 document, a parameter schema with keywords such as description or default next to its $ref used to stop at that reference. The target bindings read only the keywords beside the $ref and dropped the referenced schema's default, title and other documentation keywords. They now follow the reference chain and merge both sets, with the keywords beside the $ref winning, which is what the model parser already does. As a result, generated FastAPI routers can gain annotations such as Query(alias='least', title='Size'). A parameter whose $ref only carries a description now gets the referenced schema's default, so the generated client sends that default and the generated server fills it in when a request leaves the parameter out. Whether these keywords count is now decided by the version the parser uses, for example --schema-version 3.0, instead of the entry document's openapi text. OpenAPI 3.0 still ignores them. (#6210)multipart/form-data request member whose schema accepts any value, such as {}, was decoded as JSON by the generated server whenever the part parsed as JSON. So 1 arrived as the integer 1 and null as None, even when the member's encoding named text/plain or a style, which tells the client to write it as text. Such members are now read as strings, so handlers receive '1' and 'null'. Members with no encoding media type or style are still decoded as JSON. (#6210)allOf whose anyOf or oneOf members admit only values and no objects, for example an anyOf of string and integer combined with minLength: 2, used to be generated as a model class without fields that rejected every value. It is now generated as the union of the intersections of one branch from each anyOf or oneOf with the other parts, such as RootModel[constr(min_length=2) | int] for Pydantic v2, or a TypeAlias like str | int for dataclasses, TypedDict and msgspec. This happens by default, without --intersect-allof-keywords or --intersect-combined-schema-keywords. For these sites, the generated kind (class vs root model or alias), field annotations, constraints, defaults and base classes change. Numbered classes these sites used to produce, such as Beside3 and Beside4, are no longer written. --reuse-model no longer merges other models into the empty class, and --collapse-root-models now inlines the union into fields. Code that imports, instantiates or subclasses the old empty classes or their numbered siblings must be updated. Sites that have their own anyOf or oneOf, that admit an object, that have no satisfiable combination, or that exceed 128 branch combinations keep the previous output (#6258)--use-unique-items-as-set - With --use-unique-items-as-set (and any preset that turns it on), a uniqueItems array whose items can never be set members is now generated as a list instead of a set. This covers plain objects or dicts, arrays, sequences, mappings, and tuples that hold such a value, including when the tuple is reached through a type alias. For example, set[dict[str, Any]] becomes list[dict[str, Any]], set[tuple[int, list[int]] | dict[str, Any]] becomes a list, and a root model RootModel[set[list[int]]] becomes RootModel[list[list[int]]]. The old set types rejected every non-empty array in Pydantic and failed msgspec decoding. Also, when a field's list default cannot be turned into a set, the whole field now stays a list, so Optional[Set[Dict[str, Any]]] = [{'a': 1}] becomes Optional[List[Dict[str, Any]]] = [{'a': 1}]. Before, the list members of the field's union were turned into sets even though the list default was kept, which could leave fields such as Optional[Set[Any]] with a list default. Those fields now validate to lists instead of sets, and their imports change from Set to List. Arrays of hashable items, unions with at least one hashable member, nullable items and untyped items still become sets (#6290)--use-unique-items-as-set - With --use-unique-items-as-set, any array whose own schema declares uniqueItems: true is now written as a set wherever it appears. Before, this only happened for a property or root model. It now also covers an anyOf or oneOf member, the items of an array, the values of a map or of patternProperties, and a lone allOf member. For example, a map of unique integer arrays changes from dict[str, list[int]] to dict[str, set[int]], and an array of unique arrays changes from list[list[int]] to list[set[int]]. Code that indexes or appends to these nested values, or that relies on their order or duplicates, must be updated. A nested array stays a list in three cases: its items cannot be hashed; a model that --reuse-model or deduplication merged into it does not declare uniqueItems at the same position; or it sits in a union beside another array or map member that keeps its lists. Output without the option is unchanged (#6291)--use-unique-items-as-set - With --use-unique-items-as-set, a uniqueItems array whose items are models that can never be hashed now generates list[Model] instead of set[Model]. This covers typing.TypedDict models, non-frozen dataclasses.dataclass and pydantic_v2.dataclass models without unsafe_hash, non-frozen msgspec.Struct models (including the struct chain and the generic base class config), and RootModel aliases written as Name = RootModel[...] under --use-root-model-type-alias. The old set annotation rejected every non-empty array, and msgspec could not decode it at all. Code or type checks that expected the field to be a set will now see a list. Frozen classes, and classes with a custom base class, class code or custom templates, still get a set (#6294)--use-unique-items-as-set, a Pydantic model named in the value of a type alias that a set holds now gets __hash__ = object.__hash__ in its class body. For example, Circle gets it when a field is set[Shape] with Shape = TypeAliasType("Shape", Circle | str). Models named directly by a set already got this line. Instances of these models used to be unhashable and now hash by identity (#6294)--intersect-allof-keywords), the generated root model, type alias or field now gets the constraints its parts declare (minLength, maxLength, pattern, minItems, maxItems, minimum, maximum, multipleOf). Before, it took its constraints from the allOf site itself, which declares none. As a result, array lengths were silently dropped in default Pydantic output, and every keyword was dropped under --field-constraints, --use-annotated and in msgspec output. For example, a lone allOf array member with minItems: 2 now generates root: list[int] = Field(..., min_length=2), the msgspec alias Nickname1: TypeAlias = str becomes Annotated[str, Meta(max_length=8)], and level_prop: int becomes Annotated[int, Meta(ge=0, le=10)]. The allOf of a propertyNames schema now also constrains map keys, so dict[str, int] becomes dict[Annotated[str, Meta(min_length=2, pattern='^a')], int]. Generated models are stricter and reject data they used to accept. In msgspec output with --collapse-root-models, new type aliases such as MultipleItem and LevelItem can also appear (#6293)--collapse-root-models - When --collapse-root-models and --use-unique-items-as-set are both on (including the presets that turn them on), a root model whose root type has no hashable value, such as a list, a dict or a closed prefixItems array, is no longer inlined when it is the item of a set or frozenset. Instead, the root model stays named, as it does without collapse. Fields that were generated as set[list[str]], set[dict[str, int]] or frozenset[list[int]] are now typed as set[Tags], set[Object] or frozenset[Group], and the root model class is written to the output with __hash__ = object.__hash__. The old inlined types rejected every non-empty array. Still, regenerated code now has extra root model classes, and set items are now model instances instead of plain lists or dicts. Root models written as aliases, such as msgspec output, are not affected and keep a list. (#6295)--schema-version when given, otherwise the version the root document declares as the parser reads it) instead of reading the root document's openapi text with their own legacy rules (the first three characters, or the digits around the first dot). A run whose --schema-version differs from the declared version, or a document whose openapi text is missing or not recognized by the parser, can now generate different code: path parameters with allowReserved: true are written with allow_reserved=True only when the document is read as 3.2 (otherwise the client percent-encodes reserved characters in them), multipart encoding styles are ignored only when read as 3.0, the server's handling of repeated path templates depends on whether the document is read as 3.2, and the served source document decides $id resources and the inlining of pathItems and mediaTypes components by the same version (#6346)$ref in OpenAPI 3.0 documents - Generated API clients and FastAPI servers used to ignore the default and documentation keywords written beside a $ref in a parameter schema when the document was OpenAPI 3.0, including under --schema-version 3.0. They now apply them in every version, which matches the models. For example, a query parameter whose schema is a $ref with a sibling default: 7 used to have no default. It now gets that default on both sides: the generated client sends page=7 when the caller leaves it out, and the server uses 7 when the request leaves it out. Regenerated clients and servers may therefore send or accept different parameter defaults. Pass --ignore-ref-siblings-by-schema-version to keep ignoring these sibling keywords where the schema version says so (#6347)UInt64Value and UInt32Value wrapper fields now include an upper bound - Fields typed as google.protobuf.UInt64Value or google.protobuf.UInt32Value are now built from the same scalar schema as plain uint64 and uint32 fields. Before, they only got a lower bound. Generated code changes from conint(ge=0) to conint(ge=0, le=18446744073709551615) for UInt64Value and conint(ge=0, le=4294967295) for UInt32Value. The msgspec output also gains the matching le bound, for example Meta(ge=0,le=4294967295). Models that used to accept integers above the wire range now reject them. Class names, field names and types stay the same. (#6349)--input-model - When a child input model has a field that matches an inherited parent field by wire name, with the same schema and the same required status, _partition_inherited_fields now always treats it as inherited. Before, it only did this when the name was found in the parent's field set. So generated child classes such as AliasSameChild, AliasPairParent and InheritedWins no longer redeclare these fields (for example old: int = Field(1, title='Old') or shared: list[int] = Field(..., title='Shared')) and now get them only from the parent class. The child's generated JSON schema also no longer repeats these properties or lists them twice in required (previously required could contain shared twice). Code that relied on the child declaring the field itself, or on the child-level attribute name when it differed from the parent's, may need updating (#6350)--output-model-type typing.TypedDict, a generated TypedDict whose key redeclares a key of a generated base with a different type, requiredness or ReadOnly (for example an allOf member that drops the null of an inherited property, narrows its type to a model or literal, or makes it required) is now written as a subclass of TypedDict (or of the configured base class from --base-class) that declares every key of its bases itself, with the bases' keys first, instead of subclassing the generated base. Type checkers now accept the generated file, which they previously rejected with incompatible-override errors. Class names, key names, key types and requiredness stay the same, but the class hierarchy and key order in the generated source change. In modular output, the module of such a class now imports the models its copied keys reference and no longer imports the base class. Code that relies on the generated subclass relationship, or that imports the base through the child module, needs updating. Subclasses that redeclare a key exactly as the base does, and classes whose bases include a stand-in, a type override or another configured class, keep their bases (#6356)--reuse-model --reuse-scope tree, when duplicates from different modules produce canonical models with the same class name in the shared module, the earlier ones now get a numeric suffix (e.g. Item_1, Rank_1) and only the one written last keeps the original name. Before this, the shared module defined the class twice, so the later definition silently shadowed the earlier one and the earlier one's users validated against the wrong schema. Users of the earlier canonical now import, alias or subclass the suffixed name (e.g. from .shared import Item_1), and the re-exporting shared.py lists both names in __all__. In _internal modules created for import cycles, the Item and Item_1 names can swap, so _internal.Item may now point to a different model than before. Code that imports these shared or _internal names directly, or relied on the old, incorrect validation, may need updating (#6357)minContains and maxContains now produce array length constraints - Values such as 2.0 and 3.0 for minContains and maxContains used to be dropped, so the generated models accepted arrays with fewer or more items than the schema allows. They are now read as the integers they spell, the same way minItems is, so generated fields get min_length and max_length constraints (for example Field(None, max_length=3, min_length=2) for Pydantic or Meta(max_length=3, min_length=2) for msgspec). Also, contains: false with an integral float minContains such as 1.0 now produces a model that rejects every array. Data that used to validate may now be rejected (#6363)<!-- Release notes generated using configuration in .github/release.yml at main -->
standard-py3XX-20261104 and practical-py3XX-20261104--intersect-combined-schema-keywords, --distribute-allof-over-unions, --read-length-keywords-by-type, --read-schema-version-per-document, --merge-shared-variant-tags, --use-one-model-per-ref-site, --keep-reference-null-on-merged-models, --use-unique-items-as-set-by-value, --type-overrides-replace-whole-type); the practical presets also use --naming-strategy definitions-first. Default output (no preset) does not change. See the presets documentation for the full list per preset.Every new option is off by default and has a --no- form.
--capitalise-numbered-enum-members - Under --capitalise-enum-members, capitalize also the number a member takes when its capitalized name is taken (A_1 instead of a_1 for the members 'a' and 'A').--distribute-allof-over-unions - Read an allOf with the anyOf and oneOf it holds or sits beside as JSON Schema validates them.--ignore-ref-siblings-by-schema-version - Read a $ref as its target alone where the schema version ignores the keywords beside it (JSON Schema draft 4, 6 and 7, OpenAPI 3.0, AsyncAPI 2).--intersect-combined-schema-keywords - Combine the keywords of every part of a combined schema as JSON Schema validates them, as --intersect-allof-keywords does (this option turns it on), and also.--keep-constrained-root-models-in-every-container - Under --collapse-root-models with --field-constraints, keep a root model whose root field has constraints named inside any container of its holder, a set, frozen set, Sequence or Mapping as well as a list, dict or union, as….--keep-enum-literal-aliases - Under --collapse-root-models, keep a named enum that the output writes as a Literal type alias named at its uses (Status = Literal['open', 'resolved'], a: Status).--keep-first-character-of-path-keys - Strip only a leading slash from a paths key when naming its operation models, as webhook names are, so the key pets gives PetsGetResponse.--keep-reference-null-on-merged-models - Keep the null that the schema of a field, item or member admits where the model it references is merged into an equal model that rejects null (deduplication of equal models, --reuse-model, --collapse-reuse-models,….--merge-shared-variant-tags - Give a variant that several discriminated unions tag differently every tag they give it, so each union decodes the documents its discriminator selects.--name-allof-union-members-after-branches - Name the classes an allOf gives the branches of a oneOf or anyOf it holds after the holder and the branch.--name-converted-payloads-by-message - AsyncAPI: name a payload that an Avro or XML Schema converter gives no name of its own after its message, as a JSON Schema payload is.--read-dynamic-anchors-in-document-order - Resolve a plain-name $dynamicRef that its dynamic scope does not bind from the $dynamicAnchors its document declares, the first in document order when several declare the name, and a $ref or $dynamicRef to a plain name several….--read-escaped-ref-pointers - Read the ~0 and ~1 escapes and the percent-encoded octets of a $ref JSON pointer as the characters they encode, as JSON Pointer and URI fragments do, so #/$defs/a~1b, and #/$defs/Foo Bar written with its space percent-encoded,….--read-input-model-dataclass-fields-by-alias - With --input-model, read the fields of a Pydantic dataclass by their aliases, as those of a model, so a field with an alias keeps its Python type (deque[int], frozenset[str], ...) like one without.--read-length-keywords-by-type - Read minLength, maxLength and pattern for strings only and minItems, maxItems and uniqueItems for arrays only, as JSON Schema does, so a maxLength beside an array leaves the list unbounded and a maxItems beside a string leaves….--read-msgspec-union-bounds-exactly - msgspec: decide exactly, from the bounds the schema writes, whether the int member of a union with a number member drops its Meta bounds.--read-schema-version-per-document - Read each document by the schema version it declares ($schema, or the openapi / asyncapi field).--rename-submodules-hidden-by-classes - Rename a submodule named like a class of its package, such as pkg/Warn.py beside the class Warn of pkg/init.py, to the first free name with trailing underscores (pkg/Warn_.py), with the modules below it.--singularize-last-word-of-item-names - Name the item model of an array by singularizing only the last word of its name (actions_caches gives ActionsCache, payment_status gives PaymentStatusItem).--type-overrides-replace-whole-type - Make every --type-overrides value replace the field's whole type (dict for builtins.dict, not dict[str, dict]), keeping only the item or key counts the new type takes.--use-duplicate-name-suffix-for-every-collision - Give the --duplicate-name-suffix suffix also to a model renamed because its name is taken in its module, by another model or by a name the module imports (an inline Item beside a definition Item, a definition AnyUrl beside a….--use-encoded-str-for-constrained-base64 - Write a constrained format: byte string in the field forms as Annotated[str, Field(...), EncodedStr(encoder=Base64Encoder)], so the constraints apply to the encoded text.--use-msgspec-meta-for-map-keys - msgspec: write map keys that propertyNames or patternProperties constrain as Annotated[str, Meta(...)], so msgspec checks them.--use-one-model-per-ref-site - Give an object $ref with sibling keywords one model per place it is written, which every unchanged copy of that place shares, and parse such chains without nesting.--use-plain-alias-for-recursive-models - Pydantic: write a type alias whose whole value is a model that names itself as Alias: TypeAlias = Node, which Pydantic builds for every model that uses it.--use-serialize-as-any-for-every-subclass - Under --use-serialize-as-any, wrap a field in SerializeAsAny when any subclass of its model in the generated output adds fields.--use-unique-items-as-set-by-value - Under --use-unique-items-as-set, decide each set once the item types are final (after --collapse-root-models, --type-overrides and every module) and write a set only where every value of its items hashes by value (scalars,….--naming-strategy takes two new values: definitions-first (named definitions keep their names; inline models take the name of the definition or property they belong to) and enclosing-model (every nested model is prefixed with the final name of the model it is built for, once).--no- forms for boolean options--no-<option> form, so a value set by a preset or pyproject.toml can be turned off on the command line.if property by the values its const and enum both admit by @koxudaxi in https://github.com/datamodel-code-generator/datamodel-code-generator/pull/6361Full Changelog: https://github.com/datamodel-code-generator/datamodel-code-generator/compare/0.89.0...0.90.0
Large integer constraints are now written as the exact integers from the schema - For integer fields, a multipleOf, exclusiveMinimum or exclusiveMaxim
integer fields, a multipleOf, exclusiveMinimum or exclusiveMaximum past 2**53 that a float holds exactly but prints as a different decimal (for example 2**62 or 2**64) used to be written as the rounded float decimal, such as multiple_of=4611686018427388000 or gt=4611686018427388000. It is now written as the exact integer, such as multiple_of=4611686018427387904. This applies to Pydantic and msgspec output with default options, to the least common multiple of merged allOf divisors, and to the values --filter-literal-values keeps. Regenerated models may accept or reject different values than before. The msgspec warnings for constraints outside the 64-bit range now show the exact integer too, for example multiple_of=9223372036854775808 instead of multiple_of=9223372036854776000 (#5989)--treat-dot-as-module is set (so in the default mode and with --no-treat-dot-as-module), every dot in an input directory's name now becomes _ in the written package, as already happened for file names. For example, api.v2/ is now written as api_v2/ and complex.directory/ as complex_directory/, and imports of their modules use the new name, such as from .api_v2 import b. Before, the output directory kept its dots, so in the default mode the generated imports pointed at .api.v2, a package that did not exist, and failed. Anyone who commits generated code, or whose scripts, sys.path entries or tooling point at the old dotted directory paths, must update them and remove the stale dotted directories. With --treat-dot-as-module, each dot still becomes a nested package as before. (#6000)application/json;profile=v1 and application/json, and the actual Content-Type matches none of them exactly, the generated client runtime now selects the declaration without parameters (as the generated FastAPI server already does) instead of the first one in declared order, so such a response may now be decoded with a different model than before (#6001)responses now declares a response only when it is default, a three-ASCII-digit status from 100 to 599, or a range 1XX to 5XX written with either case of X; other keys such as extension keys like x-note, an empty key, 0204, 099, 1000 or a status with a non-ASCII digit are now ignored by the generated client, the FastAPI server contract, the cache and polling helpers and the wire plan instead of being planned as responses (#6001)1XX status or the 1XX range as bodyless, as the server plan already did, so content declared under an informational response is no longer decoded by any model in the generated client (#6001)_runtime package copied into every generated client and server, _runtime/model_codecs/media.py no longer exports the MediaOrder alias, most_specific no longer accepts the order keyword, bodyless no longer accepts the informational keyword, and _runtime/client/media.py no longer defines most_specific; code that imported these helpers from a generated package must be updated (#6001)ConfigurationError before sending when a call's extra_query, or a client's or view's default_query, names a field the helper writes. That covers a property owned by an exploded form or deepObject object parameter the helper writes (any name when the parameter accepts additional properties) and a member of a form querystring the helper writes. Before, these helpers refused only exact header or query parameter names, so such calls were sent and could override the values the helper wrote (#6008)040 or 4e1, which were previously accepted as the integer 40, now raise ProtocolDataError (#6008)class Pair(RootModel[list[str]])) now writes the item's minItems/maxItems even without --field-constraints. It also writes the maxItems that items: false beside prefixItems implies, e.g. root: list[str] = Field(..., min_length=2) for Pydantic or Annotated[list[str], Meta(max_length=1,min_length=1)] for msgspec. Generated models now reject arrays that are shorter or longer than the schema allows, which they accepted before (#6032)type list combines object with array (e.g. ["object", "array", "null"]) and declares minProperties/maxProperties now writes them on the dict field as Field(..., min_length=..., max_length=...), so objects with too few or too many properties are rejected. For pydantic dataclasses the field also moves after the plain required fields, which changes the positional constructor argument order (#6032)--field-constraints now carry their declared constraints - With --field-constraints, an object property whose enum is written as a Literal (e.g. with --enum-field-as-literal all) now writes the length, bound and multipleOf keywords declared beside the enum, as a root model already did. For example kind: Literal[1, 2, 3] | None = None becomes kind: Literal[1, 2, 3] | None = Field(None, ge=2). Values that break those keywords are now rejected, unless --filter-literal-values has already narrowed the literal values (#6032)contains or boolean items no longer apply to fields that cannot hold an array - A property whose type is not an array, such as a string or a mapping, that sits beside contains/minContains or items: false used to receive the implied minItems/maxItems as a length constraint (for example Annotated[str | None, MinLen(min_length=2)] for Pydantic or Annotated[str, Meta(min_length=2)] for msgspec), which rejected values the schema accepts. Such fields are now generated without that length constraint (for example tag: str | None = None). For pydantic_v2.dataclass output the field no longer carries a Field(...) default with the constraint, which can also change the field order of the generated dataclass constructor and affect positional construction (#6037)my dir becomes my_dir, a+b becomes a_b, 3d becomes _3d and 1.0 becomes _1_0, where the old output kept the name (or only turned dots into underscores, giving 1_0). Imports that reach into these directories change to match, e.g. from ._1_0 import version. Directories whose parts are all valid identifiers, including Unicode names such as данные, keep their names. Imports into these directories were syntax errors before, so those cases are now fixed. But a directory that was never imported from outside, or only by its own sibling files, used to produce working modules at the old path, and those modules are now written to a new path. Scripts or importlib calls that use the old output paths must be updated. (#6039)type without array (for example type: object with array-valued additionalProperties, or type: string retyped with x-python-type: datetime.date) no longer gets the minItems/maxItems that contains, minContains or items: false imply as a length constraint. A map field that used to be generated as Annotated[dict[str, list[str]], Meta(min_length=2)] (msgspec) or with Field(None, min_length=2) (Pydantic) is now a plain dict[str, list[str]], so generated models now accept maps with fewer entries, which the schema also accepts. A string retyped as a date no longer gets a length constraint that failed when the model was imported (#6043)--additional-imports, a model whose name matches an imported name is no longer renamed when the module's types write that name only through its module path (for example a type written as ipaddress.IPv4Address alongside --additional-imports ipaddress.IPv4Address and a model titled IPv4Address). The model cannot shadow the import in that case, so it now keeps its schema name instead of the suffixed name it got before. Code that referenced the previously renamed class must switch to the original name (#6043)legacy-all-of-items-not-in-frozen-sets was removed, so an allOf root that holds an array whose Python type is a frozenset (for example through x-python-type: frozenset[str]) with enum items now has its items typed with the generated enum item model, the same way set and list arrays already were. Generated code for such schemas changes from keeping the original item type to something like frozenset[FrozenTagsItem] with an extra item model class. Code that reads the frozen set's elements gets item model instances instead of plain values, and values outside the enum that used to be accepted are now rejected (#6060)--generate-client or --generate-server, the wire plans for parameter objects, header values, URL-encoded forms and multipart parts are now built from the types and members of the generated models instead of the JSON types written in the schema. Members that come from allOf branches and referenced schemas are now encoded with their own types rather than as untyped extra string members, and schemas with properties but no type are treated as objects. A parameter whose model binds Any is now written as one scalar value instead of an object of string members (for example a header plan loses shape='object'). A multipart body whose type holds a model through a root model, alias or nullable union now takes its part plans from that model (for example a string member now gets an explicit PartPlan('name', 'string')). Regenerated clients and servers may therefore send and parse these values differently than before. Some schemas that were refused before are now accepted, and some refusal messages point to a different schema location, such as the parameter schema instead of schema/items (#6062)legacy-target-binary-format-part, legacy-target-last-branch-member, legacy-target-own-other-properties, legacy-target-located-kinds and legacy-target-type-items-as-text behaviours). A member is a file part only when the models hold its values as raw octets. So a format: binary string with an enum or const is now sent as a text field part, while a format that --type-mappings maps to binary and a nullable binary member (a type list of string and null) are now file parts. A property that several allOf branches declare now follows the parser's merged field instead of the last branch. The other properties of a multipart body are now read through allOf branches and references, so a form closed by a referenced schema with additionalProperties: false no longer takes extra parts. Non-file parts of multipart responses are decoded with the type the response gives the member, such as its response variant. Regenerated clients may need field parts where they passed file parts before, or the reverse (#6064)format: binary. This adds codecs to the generated _generated/model_bindings.py and renumbers the codec_N constants after them (#6064)__init__.py binds a submodule's name itself, other generated modules now import that submodule's models by name (from .annotations import Item, from .Warn import Detail) and write Item or Detail in annotations. Before, they imported the module (from . import annotations) and wrote annotations.Item. This applies in two cases: a submodule named annotations hidden by the package's from __future__ import annotations, and a submodule hidden by a class of the same name that the __init__.py defines while also importing from that submodule. The submodule name is no longer bound in those modules, so code that reached it through them, for example api.annotations or pkg.api.Warn, breaks. In most cases the old binding pointed at the __future__ feature or the package's class rather than the submodule, so the old output crashed on import (Pydantic, dataclasses) or left msgspec annotations that could not be resolved. Modules that refer to an enum of the submodule through an enum member literal still import the module. (#6081)--use-field-description or --use-inline-field-description is used with GraphQL input, every enum value that has a description now gets that description written beside its enum member (a multi-line docstring under --use-field-description, an inline docstring under --use-inline-field-description). Previously GraphQL enum members were built as a separate graphql-enum-member field kind that ignored these options, so value descriptions were never written; regenerating with either option now adds member docstrings to GraphQL enum classes. Output without these options is unchanged (#6082)Literal[1], Literal[-2] or Literal[True] instead of Literal['1'] or Literal['true'], and msgspec writes tag=1 instead of tag='1'. Under --enum-field-as-literal all, an integer enum tag is now Literal[2, 3] instead of Literal['2', '3']. Code that builds or compares these variants using the string tags needs to use the typed values (#6083)'1.5' or '0.5'), the union is now written without discriminator=. Its variants keep their Enum or float tag field type instead of Literal['1.5']. With msgspec and --use-msgspec-tagged-unions, unions whose mapping keys name booleans or floats are now left untagged, with no tag_field or tag class options, and the generator emits a "msgspec cannot decode the union" warning (#6083)const) is now tagged with that value, such as Literal['function'] or Literal['custom'], instead of its schema name (Literal['FunctionCall']). The tag fixed by the nearest ancestor's schema now takes precedence over the mapping keys for such variants (#6083)./.defs/cat.json, ../.defs/bird.json or ./sub/../.defs/dog.json are now resolved segment by segment, removing dot segments as RFC 3986 describes. The variant is now tagged with its mapping key (for example Literal['c'] or msgspec tag='c') instead of a tag built from its file name such as cat.json (#6083)'1' names an integer that another variant's const also holds, both variants now share the tag and the union is written without discriminator=. Before, Pydantic output failed at first use with "mapped to multiple choices". For msgspec, the affected Struct loses its tag_field and tag options and declares the tag field as a required field, and the other variant's tag field keeps its Enum type instead of a Literal (#6083)--use-enum-values-in-discriminator - Some variants of a discriminated union inherit their tag field from an ancestor two or more levels up, for example NamedCall below FunctionCall below a base whose type field is typed by the Enum FunctionType. The generator used to check only a variant's direct bases for the Enum. It now looks through all ancestors and takes the Enum from the nearest one that declares the field. Such a variant now gets type: Literal[FunctionType.function] instead of a plain string literal like Literal['function'], which matches how direct subclasses were already written. With a plain (non-str) Enum, the variant now accepts the Enum member passed from Python but rejects the raw JSON string "function". Code that builds or validates these variants with the raw string may need updating (#6085)$ref whose JSON pointer passes through a YAML mapping with unquoted integer keys (for example a pointer like /x-shared/responses/200/content/application~1json/schema, where 200: is loaded by YAML as the integer 200) previously failed to match the key, emitted an unresolved $ref warning and generated Any; the pointer token now matches the integer key, so the generated field or root model uses the actual referenced type (for example Any becomes a constrained str, or a root model now wraps a newly generated BaseModel), which adds new model classes to the output and enforces validation on values that were previously accepted unconditionally (#6100)mapping values use a relative path that leaves the directory of the document that writes them and comes back, for example ../../r/defs/cat.json written in r/sub/main.json or ../r/defs/fish.json written in r/owner.json. These paths are now resolved against that document's directory before they are compared with the variants' schema paths. Before, such a path matched no variant, so the variant's tag was its file name plus a trailing fragment marker, both in the Pydantic Literal tag field and in the msgspec tag= struct argument. Now the variant gets the mapping key, for example pet_type: Literal['c'] or tag='c'. A mapping path whose location is resolved is now matched by that location alone, so it no longer also selects other variants that happen to share its file name or document-relative path. The generated output also changes in the same way when the mapping is declared in a different document than the one that holds the union, for example ./sub/../cat.yaml in b/base.yaml used from a/openapi.yaml. Code that builds, serializes or compares models using the old file-name tag values has to switch to the mapping keys (#6102)__init__.py binds a submodule's name itself, either through from __future__ import annotations for a submodule named annotations or by defining a class with the same name as the submodule. Sibling modules that refer to an enum of such a submodule through an enum member literal (for example with --read-const-beside-enum, --set-default-enum-member or --use-enum-values-in-discriminator) used to keep from . import annotations and write annotations.Item and Literal[annotations.Kind.book]. They now import the models directly with from .annotations import Item, Kind and write Item and Literal[Kind.book], and enum defaults change the same way. The generated module no longer binds the submodule name, so code that reached the submodule through it (for example from pkg.api import annotations) or that depends on the old annotation text must be updated. Depending on import order, the old output could also fail to import. (#6113)--generate-client and --generate-server, the snake_case and PascalCase names derived from tags and operations (methods, handlers, resources, modules, routers, services and classes) are now normalized to NFKC, the form Python reads identifiers in, so names spelled with non-NFKC characters (for example a Greek letter written with an oxia) are written differently, and a second tag that Python reads as the same name as an earlier one now takes a duplicate suffix such as _1; client resource namespaces and server router name scopes also compare names after NFC normalization, so names that differ only by normalization take a duplicate suffix instead of failing with "Two generated files resolve to the same path" (#6118)straße and strasse) the second operation's constant becomes _STRASSE_HEADERS_1 and each typed header accessor decodes with its own operation's decoders instead of sharing one redefined constant (#6118)required values are read as the parser reads them - Client and server generation now coerce the required of a parameter, header or request body the way the model parser's Pydantic objects do, so values such as 'yes', 'true' or 1 mark it required and 'off', 'no' or 0 mark it optional, which can change whether generated client arguments are required and whether the generated server rejects requests that omit them (#6118)in - A response Header Object no longer records name or in facts, so a response header that declares a location such as in: query is now decoded as a simple-style header rather than with that location's style (#6118)--field-constraints, and the msgspec union hints for --enum-field-as-literal all. As a result, a custom parser that replaces a field type with a deep copy now gets the same output as for the original type. For example, a field that names a nullable root model is written as NullableString instead of Optional[NullableString], and keywords that the union members already hold are left out of the field. Default CLI output is unaffected; only Python API users whose custom parsers deep-copy data types see different output (#6130)prefixItems with items: false) whose positions include a nullable one, and msgspec's single dict for an object map whose pattern values include a nullable one, now put the None inside the container (list[str | None], dict[str, str | int | None]) instead of on the field (list[str] | None, dict[str, str | int] | None). The generated models now accept null items and reject a null array or map, as the schema does. A required field such as nullable_first: list[str | None] no longer accepts None, and msgspec fields lose the outer | None (for example Annotated[list[str] | None, Meta(max_length=2, min_length=2)] | UnsetType becomes Annotated[list[str | None], Meta(max_length=2, min_length=2)] | UnsetType). Code that relies on the old annotations or passes None for these fields may need updating (#6134)prefixItems, items: false and an unevaluatedItems schema used to add the unevaluatedItems type to its item union (for example list[int | str]). Because items evaluates every position after the prefix, unevaluatedItems never applies there, so the item type now holds only the prefix types (list[int]). Payloads such as ["x"], which the schema rejects, are now rejected by the generated model (#6134)ConfigDict and msgspec Struct options given through --extra-template-data, the TypedDict extra_items type name from additionalPropertiesType, the GraphQL scalar py_type and the template-data schema validator base class name are now written as names only when the target Python binds them, instead of when the running interpreter does; otherwise an option key is left out, a type name is written as a quoted string, and the schema validator base class name falls back to the default. Output therefore changes when such names use newer Unicode identifier characters and the target differs from the running interpreter (#6140)--use-unique-items-as-set, a uniqueItems array whose type is another container, such as a Sequence given by x-python-type or a tuple, now keeps its type, its item types and its list default. Previously its list default was still turned into a set (for example sequence: Sequence[int] | None = {1, 2}), and lists nested inside such a container were turned into sets (for example Sequence[set[int]] instead of Sequence[list[int]]). Generated annotations and runtime defaults for these fields therefore change (#6141)$ref whose fragment begins with the percent-encoded slash %2F or %2f (for example other.json with the fragment %2Fdefinitions/Bar) is now read as the JSON Pointer /definitions/Bar, following RFC 6901, instead of as a plain-name anchor. Before this change, a reference of this form into another document generated a model of Any. It now generates the real type of the referenced schema (for example a RootModel[bool]), so the generated classes and field types change and validation gets stricter. References of this form within the same document or an embedded schema resource used to fail with Unresolved $id reference or Embedded schema resource has no anchor, and now they generate models. (#6165)type list with uniqueItems now generated as a set under --use-unique-items-as-set - When a property or root model schema declares a type list that includes array alongside other types (for example "type": ["array", "object"] or "type": ["array", "string", "null"]) and sets uniqueItems: true, the array member of the generated union was previously written as list[T] even with --use-unique-items-as-set. It is now written as set[T], the same way a plain array is written, so dict[str, Any] | list[int] | None becomes dict[str, Any] | set[int] | None, and list defaults on these fields become set literals such as {1, 2}. This applies to Pydantic v2, dataclasses and msgspec output. Code that relies on list behaviour for these fields, such as indexing, ordering or list methods, must be updated. Output without --use-unique-items-as-set does not change (#6166) A type-list array becomes a set only where every model that a duplicate merge (for example --reuse-model or the practical presets) folds into one class declares uniqueItems for it; where a model without uniqueItems is merged in, the field stays list[T] as in 0.88.0, so its duplicates and order are kept (#6197).pattern uses syntax Pydantic's default Rust engine rejects, such as look-around or back-references, is now generated so the module imports: the model sets regex_engine="python-re", and a root model of such a string is written as RootModel[str] with its pattern. In 0.88.0 these modules failed to import. With --use-generic-container-types, a typed extra is written as dict[...], and a Pydantic dataclass carries its own config (#6005)int beside int annotations, now writes from builtins import int as int_aliased and uses the alias. In 0.88.0 the field name hid the builtin and the module failed to import (#5998)Annotated[list[str] | None, Meta(...)] in 0.88.0) raised TypeError on every decode. It is now written so that decoding works (#6134)--formatters builtin no longer splits escape sequences, f-strings, empty literals or call heads in ways that produced code that did not parse or meant something else, and no longer loops forever on such input (#5997)repr(), so a host whose tables lack a character (for example U+1E4D0 on Python 3.10) writes the same output as the newest Python. Output generated on the newest Python is unchanged (#6146)./link/cat.json, where link points to defs), it now matches the variant the union lists as ./defs/cat.json. Before, the path was compared with the variant's schema path as plain text, so no variant matched and the variant was tagged by its file name. Such variants now get the mapping key as their tag: Literal['c'] for Pydantic, or tag='c' for msgspec Structs. Mapping paths are also resolved from the document that declares the mapping, not from the document of the model that holds the union. The old file-name tag never matched the payloads the mapping selects, so this is a fix, but the generated tag literals and msgspec tag values change for affected schemas (#6175)$ref to a schema in another document, the relative paths in the mapping were resolved against the directory of the document that holds the union. They are now resolved against the directory of the document that declares the mapping. This changes the Literal tag values in the generated output. For example, a union in a/openapi.yaml uses Pet from b/base.yaml, whose mapping has c: ./sub/../cat.yaml and e: ../a/cat.yaml. Before, the a/cat.yaml variant was typed Literal['c', 'e'], and the b/cat.yaml variant was tagged with its file name instead of c. Now the a/cat.yaml variant keeps only Literal['e'] and the b/cat.yaml variant gets Literal['c']. The old fallback that re-resolved unlocated mapping paths against the holding document was removed, so only paths the parser resolved from the declaring document are matched to variants. Payloads now decode to the variant the schema selects, but code that relied on the old tags or on the misrouted decoding will see different results (#6176)responses spell one range in two cases, such as 2XX and 2xx, now stops client and server generation with a schema error (response status 2XX is given by two keys, '2XX' and '2xx') instead of being accepted (#6001)--client-protocols cache helper's statuses that carries no content, such as 204 or 205, now reports the configuration error that its response is not one natively decoded JSON body, even when the operation declares a JSON body for it (#6001)default_base_url is now resolved and validated like a declared server URL instead of being used as-is. A value with template variables such as https://default.example.com/{tenant} now fails generation with an E_BASE_URL error saying the server does not resolve to an absolute http or https URL (#6008)SessionLimitError raised while waiting before a polling result fetch now sets operation to the fetch operation instead of the poll operation. A ProtocolDataError about an upload's remote offset now names the probe operation whose response gave the offset instead of the upload helper's own operation (#6008)None for a required request body whose schema rejects null - The client runtime copied into every generated client package now raises DecodeError (reason unencodable, location body) before sending anything when a required body is given None and the selected media does not take null. Before this change the request was sent and the server's rejection came back instead, for example an UnprocessableEntityError for a 422 missing response. Callers that caught the HTTP error, or that relied on a lenient server accepting it, will now get the local DecodeError. Generated _operations.py plans now also render null=True on the JSON media of required bodies whose type admits null, so None is still sent as JSON null for those (#6011)enum or const values are arrays - The target reader now types enum members and const values by their real JSON kind. Before, it read any value of no literal kind as an object. A parameter schema such as enum: [[1, 2], [3]] is now read as an array, and client or FastAPI server generation fails with "A parameter value needs one unambiguous scalar kind". Before this change it was read as an object parameter (#6011)scope_problem check and report an error like lists scopes for scheme 'key', whose type takes none in OpenAPI 3.0 when an OpenAPI 3.0 document lists scopes or role names for an apiKey, http or any other scheme that is not oauth2 or openIdConnect. The client generator used to accept these documents when the entries were valid scope tokens, and the FastAPI generator used to accept them without checking. To fix this, use an empty scope array for these schemes in OpenAPI 3.0 documents, or move the document to OpenAPI 3.1, where role names of any text are allowed (#6016)F_SECURITY_INVALID with requires valid scope tokens for scheme ... when a security requirement lists scopes for an oauth2 or openIdConnect scheme that are not valid RFC 6749 scope tokens, such as a scope containing a space like read write. It used to generate the server without checking these scopes (#6016)$ref with a sibling format: binary that the models type as bytes is now refused with "carries a binary string as text", where generation used to succeed. Members that a read or write variant leaves out are no longer refused, some sites that were refused before are no longer reported, and the reported locations now name where the parser built the type (for example .../schema instead of .../schema/allOf/0) (#6064)--treat-dot-as-module - When --treat-dot-as-module is explicitly enabled (CLI flag or treat_dot_as_module=True in the Python API) and a generated module, an --all-exports-scope export block, or a forwarder module would need a relative import whose path has a part that is not a Python identifier (for example a directory 1.0 written as packages _1 and 0, or a file v2.1.json written as v2/1.py), the run now stops with an error such as Cannot import the module '_1.0' from module 'a_b.symbol': '0' is not a Python identifier and writes no output. Previously the run succeeded and wrote modules with syntax-error imports like from ._1.0 import version, and the rest of the output could still be used. Affected users must switch to --no-treat-dot-as-module (which writes dots as _) or rename the input files or directories. Modules that nothing imports, and imports that a pass such as --collapse-root-models drops, are still written as before (#6088)class/ or file class.json referenced from another schema, which would be written as from .class import k or from . import class) is now refused with or without --treat-dot-as-module. Before this change the check only ran under --treat-dot-as-module, and only for parts that were not identifiers. The run now exits with an error naming the module and the part ("'class' is a Python keyword, so the import is a syntax error. Rename the input.") and writes no output. Previously generation succeeded and wrote every module, with only the importing module holding a syntax error, so a pipeline that used only the other generated modules will now fail until the input is renamed (#6098)--generate-server now reports an error for an apiKey security scheme with in: header or in: cookie whose name is not an HTTP token (for example X Key or a;b) instead of generating a server, and the error for an invalid apiKey scheme now reads "needs a name and a location of header, query, or cookie, and a header or cookie name that is a token" (#6118)required values are now errors - Client and server generation now fail with API_INVALID_OBJECT: required ... is not a boolean for a parameter, header or request body whose required cannot be read as a boolean, such as 'maybe' or 2, where such documents were previously accepted (#6118)--base-class, --base-class-map, --class-decorators and --type-overrides (and the matching GenerateConfig and parser config fields) now raise an error such as base_class must be a Python import path composed of identifiers: 'mypkg.1x' when a path they name is not identifiers joined by dots. Before, these values were written into the generated code as given, which often produced Python that does not parse. Parsers also check the config again when they are constructed, so a config changed after validation, or parser keyword arguments, are refused in the same way. For --class-decorators, the path is the tokens after the decorator sign, up to the first bracket. Calls, subscripts and parenthesized names are still accepted, but a decorator whose leading part is some other expression is now refused: for example a conditional expression such as a.b if c else d, or a decorator continued on an indented line. --type-overrides values that spell an annotation (such as str | None) or contain brackets are not checked, and values that are only whitespace are ignored (#6130)allOf, enum or const parts no value satisfies, patterns that no regular expression joins, and object maps that one dict cannot express. The userinfo and query string are dropped, where the warning used to print the URL exactly as written. The legacy behaviour that kept these locations unredacted has been removed, so tooling that matches these warning texts for remote references may need updating (#6130)--use-operation-id-as-name is set and an operation has no operationId, the error now names the option as --use-operation-id-as-name instead of --use_operation_id_as_name, and adds a space before the following sentence. Tooling that matches the old text must be updated (#6130)~user in generate() output paths now raises Error - A path the run writes (output, emit_model_metadata, client_output, server_output) starting with a ~user that names no existing user now raises datamodel_code_generator.Error with the command line message Invalid path for --output: ~nouser/x: the user after '~' has no home directory (with the matching option name), rather than a RuntimeError (#6131)--generate-prompt or --output-format-json-schema (any schema name) with --skill-scope or --overwrite-skill but without --install-skill now fail with exit code 2 and Error: --skill-scope and --overwrite-skill require --install-skill, where previously the prompt or schema was printed successfully (only recommend-options already refused them) (#6131)--schema-validator-base-class-name, --validators field names and functions, --additional-imports (including those given through template data), the paths named by --base-class, --base-class-map, --class-decorators and --type-overrides, and the schema keywords customBasePath, customTypePath and x-python-import (including its qualname) are now validated with the identifier rules of --target-python-version instead of the running interpreter's Unicode rules. A name using characters that only a newer Python treats as identifier characters (for example U+1E4D0, a Unicode 15 letter, with --target-python-version 3.11 while running on Python 3.12 or later) was previously accepted and written into code the target cannot parse; it is now refused with an error, and generate() raises Error when the parser starts for such names. Names that no supported target accepts still fail config validation as before (#6140)--type-overrides value that names no type, such as an empty or whitespace-only string, now stops generation with a "must be a valid Python type annotation" error. Previously it was accepted and quietly typed the field as None (#6141)--type-overrides entry replaces a model that is used as a base class, the replacement must now be a class path or a bare class name such as Decimal. Other annotations, such as typing.Literal[1.5], str | None, list[int] or None, now stop generation with an error saying the value is no class and cannot replace the model as a base class. Previously the annotation was written as the base class (for example class Child(Literal[1.5]):) and the file was still generated (#6141)CacheEntry now rejects a freshness_seconds or initial_age_seconds integer that no float can hold with ValueError (for example freshness_seconds must be finite and not negative). Before this change it let OverflowError: int too large to convert to float escape. Any code that catches OverflowError when it builds cache entries must now catch ValueError instead (#6167)generate() now expands a leading ~ in output paths - When calling generate() (through GenerateConfig), a leading ~ in output, emit_model_metadata, client_output and server_output is now read as the home directory, as the command line already did; previously such a path was taken literally and resolved against the caller's working directory (for example ./~/models.py), so files are now written to a different location, and the remote lock overlap checks compare the expanded paths, refusing a lockfile placed inside the expanded package directory (#6131)profile = "" and an empty entry in a profile's extends (string or list) now select no profile and use the base tool.datamodel-codegen settings instead of looking up a profiles."" table (which previously was applied if present, or raised a profile-not-found error if absent); option recommendations for a run with --profile "" now target the base table instead of profiles."" (#6131)--no-formatters - Writes the output without running any formatter. formatters = [] in pyproject.toml is now written as --no-formatters by --generate-cli-command, and --no-formatters as formatters = [] by --generate-pyproject-config (#6122)<!-- Release notes generated using configuration in .github/release.yml at main -->
_ in a model's module path without --treat-dot-as-module by @koxudaxi in https://github.com/datamodel-code-generator/datamodel-code-generator/pull/6000schema: null reads the itemSchema in every reader by @koxudaxi in https://github.com/datamodel-code-generator/datamodel-code-generator/pull/6029~ expanded, inline JSON a value by @koxudaxi in https://github.com/datamodel-code-generator/datamodel-code-generator/pull/6033__init__.py as a package by @koxudaxi in https://github.com/datamodel-code-generator/datamodel-code-generator/pull/6040__init__.py binds the submodule's name by @koxudaxi in https://github.com/datamodel-code-generator/datamodel-code-generator/pull/6081__init__.py imports by the name of a submodule that the output loads by @koxudaxi in https://github.com/datamodel-code-generator/datamodel-code-generator/pull/6099$ref beside other members as the Reference Object it is by @koxudaxi in https://github.com/datamodel-code-generator/datamodel-code-generator/pull/6101__init__.py belongs to and whether a module lies within a package, and name what an aliased import must avoid, in one place each by @koxudaxi in https://github.com/datamodel-code-generator/datamodel-code-generator/pull/6144_, tell whether Python imports a module path part and index extra template data by the user-key home in one place each by @koxudaxi in https://github.com/datamodel-code-generator/datamodel-code-generator/pull/6148Class.field key and prefix an inline model with its parent in one place each by @koxudaxi in https://github.com/datamodel-code-generator/datamodel-code-generator/pull/6151Full Changelog: https://github.com/datamodel-code-generator/datamodel-code-generator/compare/0.88.0...0.89.0
Read deprecated options from the registry, the one member of a union besides None, whether an annotation names a class and whether a JSON value is an…
--intersect-allof-keywords, some allOf sites used to be generated as an empty class (class TwoRefsProp(BaseModel): pass, or an empty Struct, dataclass or TypedDict) that rejected every valid value. These are sites whose parts admit no object, for example two integer $refs with a sibling minimum, a $ref to an array schema with minItems, or two string schemas with a pattern each. They are now generated as the intersected value type: a RootModel such as RootModel[conint(ge=3, le=5)] or RootModel[list[str]] for Pydantic v2, and a type alias for dataclasses, msgspec and TypedDict output (for example TwoPatterns: TypeAlias = str). Fields that referenced those classes change with them. Under msgspec or --collapse-root-models, some models are inlined or no longer emitted (for example two_prop: Annotated[int, Meta(ge=4, le=5)]). Merged lookaround patterns add model_config = ConfigDict(regex_engine="python-re") or a from re import compile import, and a nullable site is now typed as a union with None. Code that imports, subclasses or instantiates these former empty classes, or passes dicts to them, must be updated: valid scalar and array values now validate and objects are rejected (#5406)--strip-default-none or --use-default-factory-for-optional-nested-models - A property whose allOf of scalar schemas used to be an empty model now gets the default its value type gets. --use-default-factory-for-optional-nested-models no longer emits a default factory for it, and --strip-default-none keeps the None default only where the type admits null. This can change whether these fields are required and the order of constructor arguments in generated models and dataclasses (#5406)--generate-client or --generate-server combined with --reuse-model --collapse-reuse-models, a schema that does not admit null but is merged into an equal nullable model (for example a non-nullable Work collapsed into a nullable Home) no longer takes on the merged model's null. Operations and fields that name it now type their body or result as Home instead of Home | None. Generated client codecs refuse to send or accept None for them, and generated FastAPI servers reject a null request body and answer a bare None result with a 500. Callers or service implementations that passed or returned None there must be updated (#5480)iterate, page, next_page), polling helpers (start, resume) and upload helpers (start, resume) used to reject only a call's own extra_headers or extra_query naming a header or query parameter the helper writes. They now also raise ConfigurationError before sending when the client's or a view's (with_options) default_headers or default_query names such a parameter, with a field_path of ("default_headers", name) or ("default_query", name). A client or view set up with such defaults, which used to send these requests, now fails; remove the conflicting default or use a client or view without it for helper calls. A count pagination helper's offset or page position is exempt: a client or view default of it is used as the first position, and only the call's own extra is still refused (#5502)<!-- Release notes generated using configuration in .github/release.yml at main -->
Full Changelog: https://github.com/datamodel-code-generator/datamodel-code-generator/compare/0.87.0...0.88.0
DataModel.clear_imports_cache() is deprecated and does nothing: models no longer cache their imports and the generator no longer calls it, so subclass…
standard-*-20261027 / practical-*-20261027 (for example standard-py312-20261027).$anchor references in directory input resolve to the document that declares the anchor (#5088). This is what the specification says; 0.86.0 depended on the order the files were read.propertyNames keys that reference a root model are typed as a constrained str (#5017); the previous output rejected every non-empty map.--strict-nullable --reuse-model --collapse-reuse-models (and the practical presets), a reference to a non-nullable object schema whose model was merged into an equal nullable one rejects null again, as in 0.83.0; 0.84.0 to 0.86.0 wrote | None there (#5407). No class is renamed or removed; where a second merge depended on that None, the model or type alias of the non-nullable schema is written again._internal (#5347, #5374) keep every name importable from its 0.86.0 module path, including the _internal module. A module import named like a builtin is aliased where the module also writes that builtin (partial fix of #5387).--filter-literal-values drops enum and const values that fail the constraints beside them; implied by --omit-redundant-constraints (#5100)--read-const-beside-enum types a value by the const that narrows its enum, and reads an enum that contains its const as that const under --use-single-value-enum-as-const (#5101, #5102)--use-tuple-for-closed-arrays generates closed prefixItems / items arrays (and the length-fixing --use-tuple-for-fixed-items cases) as fixed-length tuples (#5103)--pin-aliases-with-alias-generator decides each field's alias by the alias_generator its model applies, for Pydantic v2 models and dataclasses (#5104)--tag-msgspec-by-payload-name tags msgspec discriminated unions by the property name in the document, not its Python name (#5105)--order-constructor-fields-by final-names orders constructor fields by their final names, so an overriding required field keeps the position of the inherited one instead of becoming kw_only (#5106)--use-site-models-for-constrained-refs gives a $ref that carries more assertions (or an allOf that adds constraints, an enum or a type to a reference) its own model (#5107)--intersect-allof-keywords combines the keywords of every allOf part: constraints intersect, enums narrow, patterns conjoin, null members drop beside a type that excludes null (for example kind: str | None becomes kind: str) (#5108, #4951)--use-single-dict-for-object-maps generates one dict for patternProperties / propertyNames object maps instead of a union of dicts, and counts every key in schema validators (#5113)--read-unevaluated-properties reads a schema-valued unevaluatedProperties like additionalProperties, so extra keys are typed (#5114)--dedupe-request-response-variants (needs --read-only-write-only-model-type request-response or all, which the preset does not set) decides request/response variants from the schema graph: no unreferenced duplicates, stable numbering, allOf parent inline models written once (#5115, #5089)--order-constructor-fields-by written-defaults orders msgspec.Struct and Pydantic dataclass fields by the defaults they write under --strip-default-none (which the preset does not set): a stripped None default counts as a default for the field's place, a subclass after an inherited default is no longer kw_only=True, and a Pydantic dataclass field that redeclares an inherited stripped None default as required gets Field(...). Without it the output keeps 0.86.0's order, kw_only and inherited defaults (#5116, #4946, #5399)--read-nullable-beside-type-list lets the root model admit None for nullable: true beside a type list that holds an object and another type, under --strict-nullable or --use-missing-sentinel (#5117, #5064)--keep-field-defaults-off-branch-roots keeps a nullable field's default: null off the root model of a constrained union branch under --field-constraints / --use-annotated (#5118, #5084, #4987)--omit-redundant-reference-null stops writing | None after a reference to a model that already admits null (list[Name | None] becomes list[Name]) (#5120, #5081)--use-typed-map-values-beside-other-types, together with --use-typed-nullable-map-values (which no preset sets), types the additionalProperties values of the object member of type arrays that list other types, such as [object, string]; the option changes nothing without --use-typed-nullable-map-values (#5127, #5094)--keep-enum-member-values writes an enum whose IntEnum / StrEnum / (T, Enum) base would change a member value as a plain Enum that keeps every value as written (#5133)--omit-redundant-constraints does not write a constraint again beside a type that already enforces it, such as the bound of NonNegativeInt (needs --use-non-positive-negative-number-constrained-types, not set by the preset) and the length and number constraints a const or enum Literal meets by its values; implies --filter-literal-values (#4525, #4875)--use-decimal-in-field-forms writes Decimal for multipleOf in field forms (#5021)--collapse-shared-parent-wrappers: under --collapse-root-models --collapse-root-models-name-strategy parent, later holders of a parent root wrapper follow the first holder's collapse even where --field-type-collision-strategy rename-type renames the wrapper apart from its inner model. By default those holders keep the 0.86.0 wrapper; inputs that crashed in 0.86.0 are fixed either way. Under the parent strategy a pydantic v2 dataclass no longer writes the self-named alias Wrapper = TypeAliasType("Wrapper", Wrapper) beside the class that took the wrapper's name; the class validates the same payloads. (#5398)--openapi-as-definitions paths-bodies gives the request and response bodies of the paths and webhooks scopes the model a schema definition of the same body gets, for example an object body with a type array such as [object, null] (needs --openapi-scopes paths / webhooks, not set by the preset); it also covers object-map bodies of the legacy paths scope, whose default output is as in 0.86.0 except that closed patternProperties maps are fixed by default (#5025, #5024, #5141)--generate-schema-validators, counting every key of pattern maps and checking declared keys against matching patterns now needs --check-pattern-maps-strictly; without it the output is the same as 0.86.0 (#5152)--order-constructor-fields-by written-defaults now also orders dataclass and Pydantic dataclass fields by the nested-model default factories they write (under --use-default-factory-for-optional-nested-models --strip-default-none); without it the output is the same as 0.86.0$ref to a recursive schema their own root model now needs --openapi-as-definitions ref-components (in preset 20261027); without it the output is the same as 0.86.0 (#5176)dict[Key, ...] raised TypeError: unhashable type on every non-empty map (#5017)paths scope get models (#5024)TypedDict extra_items names the final class so the module imports (#5022)StrEnum (#4970)$refs in their own document: inputs that failed with "A Parser can not resolve classes" (#5046), an inherited property narrowed by a child in another directory ($ref file not found, #5068), and several --read-only-write-only-model-type request-response inputs now generate$ref to an $anchor declared inside a oneOf branch resolves instead of failing with Unresolved $id reference (#5056, #5092)ValidationError when an allOf child and its parent both declare a property named like a schema keyword, such as minimum or maximum (#5069)$ref aliases generate the same models whatever the Python recursion limit; long $ref chains and deeply nested objects that 0.86.0 generated give the same output, chains that 0.86.0 silently truncated now stop with a clear error instead of incomplete output (#5076)allOf sites that crashed or failed to import now generate, including the msgspec TagsLenItem decode failure; $ref sibling constraints at item positions no longer stack two ge annotations that raised TypeError on every decode (#5027)kw_only=True on a redeclared inherited field, and cross-module discriminator tags and --type-overrides bases no longer fail at import (a redundant kw_only only; moving an overriding required field to the inherited position is the opt-in --order-constructor-fields-by final-names)--strip-default-none (msgspec.Struct, Pydantic dataclass): modules whose 0.86.0 order failed at class creation (a required field after an optional one) now generate valid code (#4946, #5394)allOf whose parts no value can satisfy (conflicting type, enum or const) generates with a UserWarning instead of stopping with "allOf contains a boolean false schema that makes the schema unsatisfiable" (#5039)format: byte enum with an integer beyond Py_ssize_t under --use-subclass-enum is written as a plain Enum instead of a bytes enum that failed at importminimum beyond float range in patternProperties with --generate-schema-validators no longer crashes generation with OverflowErrortrue among their allOf members no longer crash generation; a false member reports that the schema is unsatisfiable instead of crashing (#4491)--use-default-factory-for-optional-nested-models with --strip-default-none no longer crashes with RecursionError on models that reference each other; fields in the cycle get no default factory (#5151)$ref to a recursive schema is typed by that $ref's target instead of failing with "A Parser can not resolve classes" (#5162)--collapse-root-models no longer writes int | "Name" unions that fail at import or type evaluation; such fields use Union[...] (#4976)$ref to an enum, a Struct or an alias whose type cannot take them are left out with a warning; before, the model raised TypeError when used to decode (#5033)--generate-schema-validators: a module whose patternProperties or additionalProperties value refers to its own model, or to a model later in the same $ref cycle, now imports (#4932)TypeError: Unable to apply constraint (#5001)allOf of an integer enum and an enum that holds null writes the integer enum without the None member that made it fail at import (#5124)allOf of enums that merges into an IntEnum or StrEnum leaves out the inherited members the merged type cannot hold, so the enum imports and validates (#5310)$ref to itself is dropped from the bases of the models whose allOf names it, so those models keep their own fields and import (#5315)TypedDict quotes the models it names before they are defined (self-references, mutual references, inherited fields), also under deferred annotations, so the module imports (#5314)--collapse-root-models, writes None inside Annotated, so the model keeps a valid base type and its description (#5273)type statement named in a class annotation that the runtime evaluates while the class is defined is quoted, so recursive and later-declared types import, also for typed extra fields (#5321)--use-enum-values-in-discriminator: a variant whose tags name no member of its enum is tagged with the enum's members, for models and JSON Schemas of every output type (#5324)--read-only-write-only-model-type request-response splits array models exactly where the item positions that array parsing types name a readOnly model, including tuple items and entries after false schemas (#5325)$ref cycle that deduplication dropped is imported nowhere, so --collapse-root-models output parses with the builtin and black formatters (#5326)Enum tag of a variant that nested choices give a discriminated union is written as its Literal; a union that names one variant alone keeps that variant's model as before and is written without the discriminator (#5335)Literal of its const, when a base declares the tag field; reused variant tags no longer fail at import (#5333)--use-enum-values-in-discriminator, a variant tagged by enum members is tagged by the members' string or integer values, and members whose values cannot be plain literals keep their enum literals (#5334)$ref when that variant has no tag, instead of generating an invalid model (#5340)Any or None instead of a model; it is kept where the variant supports it (#5344)_internal module, so the package imports, for example under --naming-strategy full-path (#4823)--type-overrides value with brackets, such as typing.Literal[1, 2], is written as the annotation it spells, with its names imported, instead of a broken import (#4747, partly)additionalProperties, items, tuple position, patternProperties or propertyNames value that is an allOf holding false is generated as with false (no extra keys or items) instead of stopping generation as unsatisfiable, for models and schema validators (#5296, #5312, #5317)--use-enum-values-in-discriminator, a variant that sits in a second discriminated union keeps its enum-member tag instead of the schema path segment, and a tag that matches no enum member no longer becomes an invented member name, so the module imports (#5099, #5201)allOf schemas extending a component is tagged by the tag each variant inherits instead of an internal path marker no payload carries (#4829)--collapse-root-models writes the items of a list that inline a union with a root model with a default without a discriminator, so the module imports (#5354)--model-name-map class name key that renamed a model no longer matches the next model of the same family, which stopped generation with "that model name is already used" (#4864)$self of an OpenAPI 3.2 document loaded through a reference resolves to that document instead of being fetched again (#4492)TypedDict and msgspec fields naming a TypeAlias of None and also admitting null are written without the extra None, so the annotation evaluates (#5109)allOf holding a $ref to a typed root beside a member whose type is a list, such as ["string", "null"], merges on the types they share instead of stopping with "unhashable type: 'list'" (#5028)--use-root-model-type-alias: the RootModel classes kept for constrained roots are ordered and quoted like other root models, so a cycle through one no longer raises NameError at import (#4498)--reuse-model, a reused variant of a discriminated union keeps its tag as a Struct of its own, so the union decodes (#5353, #4984)--all-exports-scope, modules that a re-exporting package imports back are merged into _internal, so the output no longer fails with a partially initialized module import error (#5349)--recommend-options (experimental) may recommend different options for schemas with dotted names, because the modular --naming-strategy full-path output it scores now imports (#4823)--emit-model-metadata writes source_ref / source_path as JSON Pointers that exist in the document for nested models and request/response variants; 0.86.0 wrote internal parse paths there (#4956)--recommend-options (experimental) recommends the 20261027 presets with the rules dated 2026-10-19parser.base: exact_import, is_ancestor_package_reference and iter_models_field_data_types can no longer be imported from datamodel_code_generator.parser.base; they were internal helpers outside the documented API and now live in a private module (#5048)model_rebuild() call dropped under --reuse-model for a nested model that references no other model; the generated module behaves the same (#5058)DataModel.clear_imports_cache() is deprecated and does nothing: models no longer cache their imports and the generator no longer calls it, so subclass overrides are not calledGenerationStore mutation methods are deprecated (no runtime warning, type checkers report them); call them through GenerationStore.builder(), which forwards to the same methods so store subclasses keep working_process_single_module returns modules before ordering and render preparation, and _finalize_modules no longer runs the generic base class or the decision phase--generate-schema-validators and modular output, a rule naming a model from another module now imports it the way field types do. A module that also defines a class with the same name used to check rule values against its own class; the rule now checks against the referenced model, as the schema says.extra_items naming a class from another module now imports it. A module that also defines a class with the same short name used to point extra_items at its own class; it now points at the referenced one.Any.--collapse-root-models --generate-schema-validators, a root model that a validator rule names is kept, so the module imports.--use-type-alias with --generate-schema-validators no longer fails with "schema_runtime_validation is reserved"; an alias that holds rules is written as the RootModel class.--read-only-write-only-model-type request-response no longer fails with "can not resolve classes" when only map keywords reach a readOnly model, or when an allOf child re-declares an inherited readOnly property.--check "differences found" code).paths operations stop with an Error at schema path ... message instead of a traceback.uint64 fields now decode.--enum-field-as-literal all (#4493).$ref to a whole document mapped by --external-ref-mapping now stops with an error asking for a fragment, instead of "can not resolve classes".--read-only-write-only-model-type request-response shapes generate (patternProperties beside a $ref or under allOf; additionalProperties beside properties on dataclass, msgspec and TypedDict; validator rules name the matching variants).Error at schema path ... message; a warning turned into an error while options are processed exits 2 with the traceback.1e400); a multipleOf that is not finite is left out with a warning, since Pydantic cannot take it.--collapse-root-models (part of the dated presets), a site that holds only a quoted forward reference is written as Optional["X"] instead of "X" | None, which failed when annotations were evaluated (also in 0.86.0). dataclass and msgspec output that imported but raised TypeError on every payload changes the same way.api scope, and a used $ref chain of constrained references that loops back, stop with schema errors instead of crashing.--read-only-write-only-model-type request-response shapes generate (models reaching a readOnly model only through untyped map keywords keep one class; inline objects under a document's root properties split without NotADirectoryError; dedupe variants of an allOf over a root map carry no undeclared field).field_, '', or a SyntaxError before), and sites typed by a customTypePath no longer force variants that are never written.Any | UnsetType where a collapsed union writes no member (it wrote UnsetType alone and rejected every value).--order-constructor-fields-by final-names|written-defaults and --openapi-as-definitions paths-bodies|ref-components. The pyproject keys become order-constructor-fields-by and openapi-as-definitions (lists; an empty list turns off the values a preset sets), the Python API takes order_constructor_fields_by and openapi_as_definitions sequences, and the 20261027 presets set both values of each (#5330).Payload sampling skips strings whose final newline Python's $ accepts but the end of the input rejects, and the watch CLI test retries replacing the watched file on Windows (#4654, #5149)
The test tooling keeps hypothesis below 6.170.10, which breaks the object strategy of hypothesis-jsonschema 0.23.1 (#5362)
--generate-schema-validators (experimental): the TypeAdapter that checks pattern-typed keys and values now gets config={"regex_engine": "python-re"} where a pattern needs Python regex features (#5057).
--use-annotated or --field-constraints, a multipleOf on a field typed datetime.timedelta (x-python-type) is no longer written (since 0.86.0, following the 0.84.0 rule for timedelta). Pydantic 2.13 and earlier ignored it; Pydantic 2.14 enforces it. Writing it for a 2.14 target is tracked in #5408.
Changes you may notice when you move to 0.87.0 from an older release, found by comparing generated output across releases.
These changes shipped in earlier releases and are unchanged in 0.87.0. Each was checked by generating the same schema with the releases before and after it.allOf whose member sets additionalProperties: false is closed (extra='forbid'); 0.83.0 wrote extra='allow', so payloads with unknown keys are now rejected.allOf base keep the base's required, so a redeclared property becomes required and loses the override's default.properties and a schema-valued additionalProperties gets extra='allow', keeping and validating unknown keys instead of dropping them. Pass --extra-fields ignore to drop them again.oneOf/anyOf const branches are named after each branch's title (integer_200 becomes OK); values are unchanged.required and nullable is required again (int | None without a default, as in 0.21.0), so payloads that omit the key are rejected.oneOf lists const branches becomes an Enum instead of RootModel[str]. Pass --enum-field-as-literal all to keep a RootModel (its root is a Literal of the consts).enum becomes an IntEnum; members keep their names and values but now compare equal to ints.Elem becomes Elem_1) and keeps the JSON name as its alias.oneOf/anyOf are named after the property (Animal, Animal1) instead of AnimalItem, AnimalItem1.const property is typed as its Literal; an optional one defaults to None instead of the const value.enable_structured_default_validation, apply_discriminator_tag and unconstrain_union_members now return whether the field should change, and the parser applies the change; overriding them works as before, but code that calls them directly and relies on the hook writing the field must apply the result itself (#5363)Meta call and constructor-ordering classification are built once from its render plan, and a benchmark covers 500 msgspec Structs and dataclasses (#5364, #5365, #5360)These changes alter the default output or the Python API of 0.86.0. Output changes that are opt-in are listed above.
--strict-nullable and --reuse-model --collapse-reuse-models (including the practical presets), --reuse-scope tree or same-name deduplication, a non-nullable object model merged into an equal nullable one made every reference to it accept None since 0.84.0. Those references reject null again, as in 0.83.0 (work: Home | None becomes work: Home). No class is renamed or removed; where a second merge depended on that None (for example WorkVisit), the model or type alias is generated again. Default output is unchanged (#5407, #5410)source_ref and source_path now hold JSON Pointer locations - The --emit-model-metadata output (payload version still 1) now gives each model's source_ref as the document plus the RFC 6901 JSON Pointer of the schema object the model is built from. Pointer tokens are escaped with ~0 and ~1, and source_path holds the decoded tokens. Before, both values came from internal reference paths, which could contain internal special-path markers and left out steps such as properties and items. So nested models get different values (an inline object property now points at .../properties/owner), OpenAPI operation parameter models point at the operation object, and converted AsyncAPI payloads point at the payload they come from. Read and write variants no longer get synthetic paths such as $defs/ReadWriteEmptyRequest and $defs/ReadWriteEmptyResponse; they share the base schema's location ($defs/ReadWriteEmpty). As a result, source_ref is no longer unique per model, and consumers must identify a model by module and class_name. Models with colliding parse paths, GraphQL models, and models that a custom parser builds from copied schema objects keep the old reference-path form. Tools that parse these values, key on them, or reuse them as --model-name-map keys need updating (#4956)Field import no longer emitted for enums with member descriptions - Enum classes whose members have descriptions (from x-enum-descriptions, described const branches in oneOf/anyOf, or protobuf enum value comments) no longer add from pydantic import Field to the generated module, because the enum class never used it. Field drops out of the from pydantic import ... line, and modules that contain only such enums lose the line entirely. Code that imported Field from a generated module, or custom enum templates that relied on it, will break (#4995)--collapse-root-models now keep their original position - When --collapse-root-models is combined with --use-tuple-for-fixed-items or --use-tuple-for-closed-arrays, a tuple item that references a root model is now replaced where it sits in the tuple. Before, it was moved to the end. For example, a schema [Flag, string] with Flag as integer | boolean used to generate tuple[str, int | bool] and now generates tuple[int | bool, str], and [number, Label, boolean] changes from tuple[float, bool, str] to tuple[float, str, bool]. The new output matches the schema, but anyone who regenerates will see different tuple annotations, and code written against the old wrong order needs updating. This affects all output model types, including Pydantic v2, dataclasses, TypedDict and msgspec. Replacing a root model inside a union still puts it last, as before (#5291)None writes it once, in a different position, for example V | str | None | None | UnsetType becomes V | None | str | UnsetType; accepted values are unchanged but the generated text differs (#5125)source_ref, instead of the parser's internal path: SchemaParseError messages for schema values that fail validation, the "contains a boolean false schema that makes the schema unsatisfiable" errors for allOf and anyOf, the Schema path: warnings from --schema-version-mode strict, and the "A Parser can not resolve classes" error. Three changes are visible: the slash that used to separate the file name from the fragment is gone; a document root now has an empty fragment marker after the file name; and unsatisfiable-schema errors point at the real schema position (for example components/schemas/Derived/allOf/1/properties/value) instead of synthetic segments that contain datamodel-code-generator special markers. When the location is known, the path of the raised SchemaParseError is now a single location string rather than the list of parse-path parts. Scripts, CI checks or warning filters that match these messages, and code that reads SchemaParseError.path, must be updated (#4991)allOf schemas that no value can satisfy now warn - Generation emits a UserWarning when the type, enum or const of the parts of an allOf have no value in common. Some of these schemas stopped generation with an unsatisfiable-schema error in 0.86.0 and now generate, keeping the literals of the first source that has some. Builds that treat warnings as errors may fail, and tooling that relied on generation failing for these schemas must be updated (#5027, #5039)_is_ref_circular used to catch any Exception and treat the reference as circular. It now catches only Error, NotImplementedError, OSError and ValueError, so any other exception raised while checking $ref cycles now propagates and stops generation. (#5087)reject_alias_cycles_without_schema, runs for output that Pydantic builds, such as --output-model-type pydantic_v2.dataclass or pydantic_v2.BaseModel with --use-type-alias. It catches $ref chains where the aliases only point at each other and never reach a real schema, for example component A refs B and B refs A. If any non-alias class reaches one of these aliases, directly or through other aliases or containers such as arrays, generation now stops with an Error. Before, the generator wrote A = TypeAliasType("A", "B") and B = TypeAliasType("B", A) and exited successfully, but Pydantic could not build the resulting classes. The new message reads like Holder uses type aliases whose $ref chain loops back without reaching a schema, which Pydantic cannot build: A (...) -> B (...) -> A (...). Two cases keep their old output: cycles that no class reaches, and plain pydantic_v2.BaseModel output where the aliases are RootModel classes. Fix the schemas so that every $ref chain ends at a real schema (#5302)--output-model-type msgspec.Struct finished without error when a Struct field reached type aliases whose $ref chain loops back without reaching a schema, such as A: TypeAlias = "B" and B: TypeAlias = A. msgspec could not decode that output. The reject_alias_cycles_without_schema check now also runs for msgspec output, so generation stops with an error such as Holder uses type aliases whose $ref chain loops back without reaching a schema, which msgspec cannot decode: A (...) -> B (...) -> A (...). Aliases that no class reaches are still generated as before. Users whose schemas contain such cycles must fix the $ref chain so it reaches a real schema before they can generate msgspec models (#5308)$ref components now rejected for every output type - When a schema component is only a $ref to itself, deduplication drops that root model even though other code still names it. Generation now fails with an error such as C uses a $ref chain that loops back without reaching a schema, which Python cannot evaluate as the module runs whenever the generated module would look up the missing name at import time. Before this change the check ran only for Pydantic and msgspec output, and it skipped aliases that no class reached. Three kinds of output used to be written with no error even though the module then failed to import: dataclasses.dataclass and typing.TypedDict output whose module-level type aliases, functional TypedDicts or class annotations under --disable-future-imports name such a component, and Pydantic or msgspec output with an unused alias naming it. The generator now exits with an error for all three instead of writing output. Python 3.12 type statements and deferred annotations are not affected (#5392)GenerationStore.model_by_ref_id and GenerationStore.reverse_edges, and the matching GenerationFacts fields, are now keyed by a ModelKey. Each Reference gets this key when it is built, and it replaces id(reference). Custom parser code that looks up these maps with id(reference) will now silently find nothing and should use GenerationStore.model_key(reference) instead. Copies of a Reference made with deepcopy, model_copy or pickling keep the key of their original, so store queries such as model_for_reference and has_data_type_references now treat a copied Reference as the original model instead of an unknown one. (#4996)Reference.model_post_init now stores a per-instance _model_key in the object's __dict__. Pydantic versions before 2.6 compare __dict__ in ==, so on those versions two distinct Reference objects with identical fields now compare unequal. On every pydantic version, vars(reference) now includes the extra _model_key entry. (#4996)minimum, maxLength or multipleOf, to DataTypeManager.get_data_type even when field_constraints=True. Before, it passed an empty mapping or only a single zero bound. The Pydantic v2 manager now filters these itself. Custom DataTypeManager subclasses that build constrained types from these kwargs without checking field_constraints may now emit constrained types such as conint or confloat in addition to the Field() constraints (#5021)CARRIED_CONSTRAINT_KEYWORDS class attribute on DataType, and its override on EncodedBytesDataType, was replaced by a private _consumed_constraints property that is computed from the type's arguments. Subclasses that read or overrode CARRIED_CONSTRAINT_KEYWORDS must switch to _consumed_constraints (#5021)sort_data_models now uses model keys instead of reference paths - The public function datamodel_code_generator.parser.base.sort_data_models and the SortedDataModels alias now key models by integer model keys (ModelKey) instead of reference path strings. The returned dict was dict[str, DataModel] and is now dict[ModelKey, DataModel]. The returned list of models needing a reference update action was list[str] and is now list[ModelKey]. The require_update_action_models and runtime_validation_references arguments must also hold model keys now. Code that calls sort_data_models directly and looks up results by path, or passes path strings in require_update_action_models, has to switch to model keys, for example via datamodel_code_generator.reference.model_key_of (#5058)Parser subclasses that override or call internal hooks may need updates. Parser._generate_module_output now takes require_update: Collection[ModelKey] instead of require_update_action_models: list[str] of paths. Parser._build_module_structure no longer takes require_update_action_models and returns one fewer item, because the path-mapping dict is gone. Parser._keeps_root_model_named now takes model keys instead of paths. The Parser._circular_root_model_paths attribute was replaced by _recursion_facts. Overrides of _process_single_module that append paths to its list still work (#5058)--url or remote $ref schemas, the pinned transport used to pass no SSL context when verification was on. The HTTP core then built its own default context, which trusted the operating system's default CA paths plus certifi. The transport now builds the context with the backend's create_ssl_context, the same way HTTPX does. With the stable http extra, only certifi is trusted by default. SSL_CERT_FILE replaces the default roots entirely; if it is not set, SSL_CERT_DIR selects an OpenSSL hashed CA directory. Private or corporate CAs installed only in the OS trust store are no longer used on this path, so those fetches now fail certificate verification unless the CA is supplied through SSL_CERT_FILE or SSL_CERT_DIR. A custom SSL_CERT_FILE bundle also no longer gets the certifi roots added on top (#5111)http and validation extras now require certifi>=2026.10.19 - Environments or lockfiles that pin an older certifi will no longer resolve with these extras. The newer certifi bundle, along with the refreshed OS ca-certificates in the official Docker image, drops the roots distrusted in the October 2026 eMudhra CA incident, such as AAA Certificate Services and emSign ECC Root CA - G3. Remote schemas served from hosts whose certificate chains rely on those roots now fail TLS verification instead of loading (#5111)_internal by @koxudaxi in https://github.com/datamodel-code-generator/datamodel-code-generator/pull/4971Note truncated.
Base64 bytes with length constraints now use EncodedBytes - With --type-mappings string+byte=binary, a format: byte string with minLength or maxLength
EncodedBytes - With --type-mappings string+byte=binary, a format: byte string with minLength or maxLength used to generate conbytes(...), which did not decode base64. With --field-constraints it used to generate Base64Bytes with a Field(max_length=...). It now generates Annotated[bytes, Field(max_length=8), EncodedBytes(encoder=Base64Encoder)], which decodes the base64 text and checks the lengths on the encoded text, as JSON Schema counts them. Field values are now the decoded bytes instead of the raw text. Under --field-constraints, inputs whose base64 text is longer than the limit are now rejected, even when the decoded bytes fit. Generated modules now import Annotated, Field, EncodedBytes and Base64Encoder. Pydantic checks these lengths on the text only from 2.10 on, and an explicit --target-pydantic-version 2 now warns about each such field (#4798)--type-mappings string+byte=binary and --strict-types bytes, format: byte fields used to generate StrictBytes, or conbytes(..., strict=True) when they had lengths, and held the raw text. They now generate Base64Bytes, or the EncodedBytes form when they have lengths, and decode the base64 text, so validated values change. FastAPI path, query, header and cookie parameters with this combination no longer stop generation with an error (#4798)--type-mappings string+byte=binary, code paths that map a type and format without constraints now pass base64 decoding through. For example, a format: byte string member of a multi-type type list now generates Base64Bytes, as in Base64Bytes | list[int], instead of plain bytes. Its runtime value becomes the decoded bytes (#4798)These change generated output compared with 0.85.0, but only where 0.85.0 output failed or for options that are new in this release.
None member - An enum with a value type base (the IntEnum written for type: integer, or a --use-subclass-enum class such as (int, Enum)) that lists null used to get a member such as integer_None = None, which made the generated module raise TypeError at import. That member is no longer generated, and an enum whose only value is null becomes a RootModel[None]. Class names and field defaults are unchanged (#4884, #4889)Field() constraints no longer carry a pattern that every tag value satisfies. Such output failed at import in 0.85.0 because the tag was no longer a usable discriminator. Tags whose values contradict their own pattern are unchanged (#4888)kind: Literal['card'] | None = None is now written as kind: Literal['card'] = 'card'. The discriminated union failed at import before; a standalone model using such a tag now defaults to and dumps 'card' instead of None (#4895)Annotated[...] = None assignments like black - Where 0.85.0 put the None default in parentheses on its own lines, the line is now split inside the annotation, as black does. The code is equivalent, but --check runs with a dated preset (which uses the builtin formatter) report the reformatting (#4794)--use-tag-as-union-variant-name no longer repeats the key in prefixed names of models inside key-named branches (#4903), and --use-single-value-enum-as-const types nullable single-value unions as Literal[...] | None keeps mixed-type single-value branches apart instead of merging them into one Enum (#4926, #4927), and leaves nullable: true single-value enums as enums so they still accept null (#4944). Both options were added after 0.85.0, so output without them is unchanged<!-- Release notes generated using configuration in .github/release.yml at main -->
Full Changelog: https://github.com/datamodel-code-generator/datamodel-code-generator/compare/0.85.0...0.86.0
Output encoding failures now raise Error instead of raw codec exceptions - Generated output, model metadata from --emit-model-metadata, and API target
Error instead of raw codec exceptions - Generated output, model metadata from --emit-model-metadata, and API target package files are now encoded before anything is written. If the chosen --encoding / encoding cannot encode the text, generate() raises datamodel_code_generator.Error with the message Unable to encode output using encoding '...': ... instead of letting UnicodeEncodeError escape. The CLI now prints this as a single error line and exits with code 2 instead of showing a traceback. Python API callers that caught UnicodeEncodeError or UnicodeError need to catch Error instead. Also, when one module of a modular output fails to encode, no files are written; before, earlier modules could be written before the failure (#4615)Error - generate() now checks the encoding option during config preparation, before any input is read or any output path is created. An unknown encoding such as nosuch, or a codec that is not a text encoding such as hex, now raises datamodel_code_generator.Error (CLI exit code 2, one-line message) instead of a raw LookupError raised later. Code that caught LookupError for a bad encoding must catch Error instead (#4615)--class-name, --class-name-prefix, --class-name-suffix, --special-field-name-prefix, --model-name-map values and explicit field aliases. It also applies to client and FastAPI generation settings such as package, model_package, resource namespaces, operation, parameter and router names, and protocol helper names. These are now checked against the identifier rules of --target-python-version, not the running interpreter, so a name that uses characters only a newer Python accepts is now rejected (for example with E_CONFIG_VALUE or an invalid identifier error) when targeting an older Python, even if the running interpreter accepts it (#4790)--type-overrides, customTypePath or x-python-import (including its qualname and native-field paths) that does not exist in the target Python version now stops generation with TYPE is unavailable for target Python X.Y. Examples are enum.StrEnum for 3.10, pathlib.types.PathInfo for 3.13, builtins.frozendict for 3.14 and pathlib.DirEntryInfo for 3.15. Before this change the import was written as given and generation succeeded. The check runs only when the final output imports the type. To fix this, raise --target-python-version or use --import-overrides to point the import at a backport module, for example --import-overrides '{"StrEnum": "backports.strenum"}'. (#4788)to_camel, to_pascal, to_snake), OpenAPI operation model names and the builtin formatter's import ordering are now worked out from Unicode tables for --target-python-version. Those tables cover identifier characters, \w, numeric characters, case mappings and NFKC normalization. Before, these names came from the str, re and unicodedata behaviour of the interpreter running datamodel-codegen. ASCII names are unaffected, but output for non-ASCII schema names can change when the running interpreter's Unicode version differs from the target's. For example, a property 京都 (U+4EAC is numeric from Python 3.13) used to become field_京都 when generated on Python 3.13 or later. It is now emitted as 京都 for targets up to 3.12, and the reverse happens when generating on an older Python for a 3.13 or later target. Likewise, --capitalise-enum-members no longer turns ɤ into for targets older than 3.14, even when running on Python 3.14. Regenerate and review models whose names contain non-ASCII characters, because renamed fields and members break code that refers to them (#4790)typing_extensions - Standard-library typing or collections.abc names given through --type-overrides, customTypePath or x-python-import are now resolved against --target-python-version. If the name is newer than the target, the import now comes from typing_extensions. For example, typing.LiteralString and collections.abc.Buffer with target 3.10 now produce from typing_extensions import Buffer, LiteralString instead of importing them from typing and collections.abc as before. Projects that compare generated output, or that do not have typing_extensions installed, will see different imports. (#4788)--formatters builtin, whether an import goes in the standard library section or the third party section now depends on the standard library modules of --target-python-version. When no target is given, the minimum supported target, 3.10, is used. Before this change, the formatter used sys.stdlib_module_names of the running interpreter. When the running Python differs from the target, imports in generated files can move to a different section. For example, tomllib is grouped as third party when targeting 3.10, distutils is grouped as standard library when targeting 3.10 even on a newer interpreter, and sre_parse becomes third party while profiling becomes standard library when targeting 3.15 (#4791)--formatters builtin, an import a, b, c statement that names modules from different categories (standard library, third party, first party) now puts each module in its own section, as isort does. Before, all modules from that statement went into the section of the highest-priority module among them, so the order of generated imports can change (#4791)--reuse-model, model names that start with characters beyond ASCII (for example Ñumber or Ölen) are now masked as whole identifiers when models are compared. Models that are identical except for such references are now reused as subclasses (for example class Distance(Speed): pass) instead of being generated as separate duplicate classes. This matches how ASCII names already worked. As a result, some previously generated duplicate classes and their numbered names may no longer appear in the output (#4791)<!-- Release notes generated using configuration in .github/release.yml at main -->
Full Changelog: https://github.com/datamodel-code-generator/datamodel-code-generator/compare/0.84.0...0.85.0
Feature forms (StringConstraints, dataclass aliases, deprecated, dict-key ordering, TypeAliasType, regex engine) follow the newest supported choice; f…
Besides the models, datamodel-code-generator can now generate a FastAPI server package and a typed HTTPX2 client from one OpenAPI document. Both are new in 0.84.0 and experimental: options, templates and the generated packages may change in later releases (they are listed in the experimental registry with since_version 0.84.0). The generated code uses your generated models as its runtime contract: they validate requests and responses, and the generated server reads its packaged copy of the OpenAPI document only to serve it.
Get started:
# FastAPI server package in app/server/ (mkdir app && touch app/__init__.py first)
datamodel-codegen \
--input openapi.yaml \
--input-file-type openapi \
--openapi-scopes schemas api \
--output-model-type pydantic_v2.BaseModel \
--preset standard-py312-20260909 \
--output app/models.py \
--generate-server fastapi \
--server-output app/server \
--server-package app.server \
--server-model-package app.models
# HTTPX2 client package in app/client/
datamodel-codegen \
--input openapi.yaml \
--input-file-type openapi \
--openapi-scopes schemas api \
--output-model-type pydantic_v2.BaseModel \
--preset standard-py312-20260909 \
--output app/models.py \
--generate-client httpx2 \
--client-output app/client \
--client-package app.client \
--client-model-package app.models
--generate-server / --generate-client require --server-output / --client-output, --server-package / --client-package (the import path of the package) and --server-model-package / --client-model-package (the import path of the models). --output names the model file (models.py above), not a package. The other --server-* / --client-* options are in the CLI reference.servers in the document needs --client-default-base-url, otherwise generation stops with an error--generate-server and --generate-client require an explicit --input-file-type openapi: an input type left to detection, auto, or any other type stops with Error: --generate-server requires --input-file-type openapi, not auto and exit code 2 before the input is read (#4639)[tool.datamodel-codegen] key, and a generate() option; both targets reuse the model output options (formatters, file header, line length, and so on) (#4401, #4406, #4430)--check, --diff-against, --watch and --output-format json work as for models, and so do batch jobs (#4438, #4442, #4443, #4517)--check lists leftover files as EXTRA (#4167, #4456, #4461). A generation that leaves .py files it no longer generates in the package, such as the router module of a removed tag, names them in one LeftoverFilesWarning (#4626). The required runtime dependencies are printed as a uv add ... command instead of being written to a requirements file (#4166); datamodel-code-generator does not edit pyproject.toml. --output-format json reports the package and the same dependencies as target.package and target.dependencies (#4680). The line asks for pydantic>=2.14.0, as does the client README (#4601, #4651). An explicit --target-pydantic-version older than that minimum (2, 2.11 or 2.12) is refused with Error: and exit code 2 for a server, and for a client whose models use pydantic; leave it unset or use 2.14 (#4627). A warning is shown when an existing package directory shadows a generated module, for server and client packages and also for plain model output (#4470).generate_server="fastapi" or generate_client="httpx2" (plus server_* / client_* options) to generate(); with output=None it returns GeneratedModules with every model and package file (#4507)default on both targets: routers/default.py, DefaultService, create_app(default=...) and the --server-router-names key default on the server, client.default on the client. A tag that itself derives default is numbered apart in declaration order (default, default_1) the same way on both (#4608).allOf, or typed by additionalProperties, whose type has no single scalar kind (an object, a mapping, an array of objects, a mixed enum, or a union such as Filter | string or string | string[]) travels as application/json parts, one per item only for an array, and the server validates it with the member's model type. A member with a scalar kind travels as text, one value per array item. An explicit encoding.<name>.contentType naming one JSON media type is honoured by both targets (#4602, #4611). A member without a type ({}), each item of an array whose items have none, and other properties that the schema allows without a type travel as application/json parts too, a string included; the server keeps such a part that is not JSON as it arrives, text for a field and bytes for a file (#4728). The server parses a JSON part with the member's model field, so the field's constraints and discriminator apply; a model that populates by name also takes a part or field named like the Python field (max_age beside maxAge); typed other properties are checked by their type also when --reuse-model makes the form's model inherit an equal one; a form body whose schema is one schema or null is read and written as the form of that schema, and a multipart body that is a union of several schemas stops generation on both targets (needs an object schema to be sent as parts) (#4727). A client multipart body left without parts is sent as its closing boundary with a multipart/form-data Content-Type, which a server reads as an empty form (#4727).style, explode and allowReserved apply to URL-encoded bodies, and to multipart/form-data only in OpenAPI 3.1 and 3.2, whose parts carry the style's text without percent-encoding (the client refuses a delimited value that holds its delimiter); OpenAPI 3.0 ignores them for multipart, so the member is written and read as its contentType says. The server now reads styled members (form, deepObject, spaceDelimited, pipeDelimited), a URL-encoded member's contentType, and multipart members whose encoding names one UTF-8 or US-ASCII text media type or any media type for files, as the client writes them; a form whose exploded objects that allow other properties would take the same names stops generation on both targets, as such query parameters do (#4733), and so does such an exploded object next to other properties the form keeps, whether the schema declares them (additionalProperties true or a schema) or the model configuration keeps them (--extra-fields allow) (#4737).format: binary string is raw bytes that only a whole body (application/octet-stream, image/png, text/csv) or a multipart file part can carry; a text/* body whose model type is one binary string travels as raw bytes, also when the schema reaches it through $ref or a single allOf / anyOf / oneOf branch, beside null, a length limit or other binary strings (#4669), and the client method takes it as a binary body (bytes, a file object or a path). A binary string that would be sent as text (inside a JSON or URL-encoded body or response, a text/* body that is an object or array, a multipart part that is not a file, an item of a streamed response, a parameter or a header) stops generation on both targets with an error that names the operation and the schema location. Declare such a value format: byte for base64 text, optionally with --type-mappings string+byte=binary to hold the decoded bytes (#4658). The model type decides, so allOf: [{type: string}, {format: binary}] is a binary body too; bytes the models constrain (maxLength: 16 as conbytes(max_length=16)) are validated by the model: the server answers 422 to a request body and does not send a response body the model refuses, and the client raises DecodeError (unencodable for a bytes request body, invalid_value for a response) while files, paths and iterables stream unchecked. An enum or const of binary strings is text in the models and travels as text, and a binary body whose model types it as bytes only in part (type: [string, integer], bytes | int) stops generation (#4729)X Sp, X-Näme); a content key that is no media type (multipart/form data) or whose text is not ASCII header text (text/plain; label="café"); a URL-encoded body with patternProperties or that is not an object (the server reads such a body only with --server-body-mode request); a --server-router-names group key that matches no group (it was ignored) and a --client-resource-names tag that is the first tag of no operation. The server routes literal path text by its decoded value (/files/a%20b registers /files/a b, which the client's request /files/a%20b matches); literal %2F, %7B or %7D, and two operations of one method whose paths decode alike, stop generation. Client resources take their place among the derived names from their first operation, as server groups do.--openapi-scopes gets api added to the default scopes, --target-python-version becomes 3.11, pydantic_v2.dataclass models get --use-missing-sentinel with --target-pydantic-version 2.14 (a dataclass field cannot tell an unset member from one set to None; with the sentinel an optional field without a default holds MISSING, imported from pydantic, a member a request or response leaves out arrives as MISSING, a field left unset is not sent, and None sends null where the property is nullable), --use-missing-sentinel gets --target-pydantic-version 2.14, and msgspec.Struct models get --use-msgspec-tagged-unions and --use-msgspec-nullable-enum-alias (msgspec cannot decode untagged struct unions or enums with a None member). A setting counts as set when it comes from the command line, pyproject.toml (also a job or profile table), a --preset or a generate() argument; a value you set that the target cannot use stops generation with Error: and exit code 2, such as --openapi-scopes schemas, --target-python-version 3.10, a preset for Python 3.10, or --target-pydantic-version 2.12 with the sentinel. After a run that set anything, stderr shows the command with those options added (or the pyproject.toml lines to add, in the table you use), so you can set them yourself; --output-format json reports them as target.implied, and generate() prints nothing. The model files equal a model-only run given the same options (#4651, #4673, #4676, #4677, #4687)A parameter value needs one unambiguous scalar kind, unless the member's encoding gives it a style or a contentType (#4733); --server-body-mode request lets a server read such a body itself (#4611)A service Protocol per router group, applications, security dependencies, async handlers, and parameters, bodies (JSON, form, multipart) and responses (#4157, #4158, #4159, #4162).
<group> is class <Group> (the Protocol name without Service, Operations for the single layout) in module <parent of --server-package>.services.<group>, for example class Pets(PetsService) in app/services/pets.py; a secured document adds authorize in services/authorize.py. Generation writes each of these modules that does not exist yet once, with a stub for every method that raises NotImplementedError (HTTP 500), and never overwrites or deletes them; --check, --diff-against and generate() without an output write none, and --check reports none. The generated server/main.py imports them and builds app = create_app(pets=Pets(), ...), so uvicorn app.server.main:app serves the API; a missing module or class stops it at startup with the file and class to write, and a method whose parameters no longer accept the arguments the routes pass stops it at startup too. create_app stays public for tests and for passing services yourself. After generation, stderr shows the files to implement and the command to run, and --output-format json reports them as target.entrypoint, target.implementation and target.readme; the generated README lists the stubs. One parent package holds one server: the docstring of services/__init__.py names the server package it belongs to, and a second server package beside a live one, in a later run or in the same batch (--check included), or an existing services.py beside the server package, stops generation with an error; a renamed or moved server package takes the services package over, which --check reports and generation announces, and the imports of your modules are yours to update. The printed run commands add --app-dir (uvicorn) or uv run --directory with fastapi dev --entrypoint when the package is not importable from the working directory, as in a src layout. The generated README lists the runtime dependencies and shows a test that passes fakes to create_app (#4687, #4697)create_app serves the static source document, not one FastAPI builds. Generation writes the selected operations (external references bundled, unused components pruned) into _generated/openapi.json in the package, and the application reads it on the first /openapi.json request, a fresh copy per application (#4534, #4681). Build backends include the file by default, except setuptools, which needs it in package-data or MANIFEST.in; a distribution without it answers the first request with an error that says so. create_app(prefix=...) leads every path in the document, and the description settings you pass (title, version, servers, ...) replace the document's. Pass source_openapi=False to serve FastAPI's own document instead; an application of your own that includes build_router(...) can call serve_source_openapi(...)... and symbolic links resolve), and none for a document read from a URL; any other local file reference fails before the file is read, with or without --allow-remote-refs (#4642)input and ctx (#4457). The README of the generated package explains how to hide the defaults (docs_url=None, exception_handlers, ...).T | None = None, declared defaults reach every parameter, scalar cookies use FastAPI's Cookie(), repeated single-value inputs follow FastAPI, and strict parameter types are accepted (#4444, #4448, #4482, #4505, #4527)nullable: true, type: [..., "null"], a union with null, an any-value schema, and every root-model body under --force-optional) accepts a JSON null; an omitted or empty body answers 422 missing. A request that carries such a body under a wrong, undeclared or missing Content-Type answers 415 (#4604). An x-python-type that accepts null (Any under any alias, object, None, a Literal with None) counts as accepting null, and a JSON body that an adapter reads for another reason, such as several media types, reads a null its model rejects as FastAPI does: 422 missing when required, None when optional (#4725).None, bare or as an HTTPResult without a body, goes through the model of a declared 2XX response (exact status, range or default): the JSON body null with the declared media type when the model type accepts null, otherwise 500 with a ResponseValidationError. Another declared status sends null under a JSON response whose model accepts it, else an empty response without a Content-Type (HTTPResult(404)); responses without content, HEAD and 204/205/304 stay empty. The method's return annotation includes None when the primary response accepts null (#4606, #4725)200, else the lowest success status, else the 2XX and then the default response (sent as 200); --server-primary-responses can name a range or default. An operation that declares only other ranges, such as 4XX, has no primary response: a bare return answers 500, so its method returns an HTTPResult or a Response (#4725)text/* responses: text the server encodes is labelled with the charset it uses (the declared one, else utf-8), and bytes a method returns are sent as they are with the media type the document declares, so they carry a charset only when the document declares one (#4704, fixes #4667)media_type its entry names (such as text/plain beside JSON) and validated with that media type's model (#4653)--output-model-type pydantic_v2.dataclass, a JSON response whose type reaches a dataclass that allows extra members (additionalProperties) returns those members (#4655)required: true; a path parameter that names no placeholder of its path stops generation on both targets (#4618)["path", "item-id"]), also for placeholders that are not Python identifiers, with create_app, custom exception handlers and applications built with build_router (#4607)Authorization: Bearer <token>, so a Basic or other Authorization header no longer satisfies them, and the credential passed to authorize is the token, not the whole header (#4587)HTTPBasic reads ASCII only), and the 401 challenge names it: Basic charset="UTF-8" (#4726)400 {"detail": "Invalid request"}, whether FastAPI or an adapter reads it (FastAPI alone would read Latin-1); a JSON-content header is ASCII JSON text. An API key, bearer token or Digest credential outside ASCII presents no credential. An HTTPResult header that is not ASCII header text under a token name answers 500 with a ResponseValidationError; a Starlette Response sends its headers unchecked (#4726)accepted call still answers 422 once it reads a parameter value (#4726)%2F stays inside its path parameter instead of causing a 404, of whatever style. A value can therefore contain / and .. (..%2F..%2Fetc arrives as ../../etc): validate it, for instance with a schema pattern, before using it as a file system path or in another URL. API routes you add to the generated router (add_api_route, decorators) get the same routing; mounts, Starlette routes and routers you include into it keep FastAPI's decoded routing (#4591)Client and AsyncClient with a resource per tag (default for operations without a tag) and a method per operation: raw/streaming/multipart responses, retries, authentication including OAuth client-credentials and refresh-token providers, pagination, polling, SSE/NDJSON streams with resume, WebSockets, webhook verification, conditional-request caching and resumable uploads (#4221, #4223, #4224, #4225, #4230, #4344, #4251, #4275, #4279, #4287, #4295).
from <package> import Client, with Client(base_url=...) as client: client.<group>.<method>(...)) and the README path; --output-format json reports it as target.usage. The generated <package>/README.md starts with a quick start that calls a real operation (sync, async, and error handling), explains base_url and the document's servers, lists each method's signature and the runtime dependencies, and keeps the generation details at the end; JSONValue is exported from <package>.types, UNSET from <package>.options (#4687, #4697)Client(base_url=..., timeout=..., total_timeout=..., max_retries=..., default_headers=..., clock=...), per-view with_options(...), and per-call RequestOptions(...). RetryOptions stays for retry conditions that need changing (#4549).Clock provides monotonic, time, random, sleep (sync clients) and asleep (async clients), so tests can run every wait at once (#4549)RequestOptions(idempotency_key="...") to supply your own, or None to disable (#4380, #4549)max_body_bytes / max_header_bytes (the receiving web server bounds sizes), the cache has no max_entry_bytes, and resumable-upload helper configs have no max_chunk_bytes. A chunk is UploadOptions.chunk_bytes, 8 MiB by default, settable per helper or per call. Unsigned webhook helpers are decode_unverified(raw_body). WSOptions.max_message_bytes only passes through to HTTPX2's max_message_size_bytes; unset, HTTPX2's default applies (64 KiB in 2.13), so set it for APIs that send larger WebSocket messages (#4317, #4549, #4603).default_headers / extra_headers entries and idempotency keys are sent only as ASCII header text (HTAB, SP, visible ASCII, no whitespace at either end). A header parameter holding anything else raises DecodeError (reason unencodable); a default_headers / extra_headers entry or idempotency key raises ConfigurationError (reason invalid_value) when the options are built, and header names in those settings must be HTTP tokens. Send Unicode through a JSON-content header parameter or an encoding the API defines. A cache validator (ETag) that is not such text is not sent; when no usable validator remains, the entry is refetched without a condition, and an SSE event ID that is not ASCII cannot be sent as Last-Event-ID, so that reconnect or resume is refused (#4610). A credential sent in a header follows the same rule (an empty bearer token, a key with a trailing space or a line break, or café raises ConfigurationError with the reason invalid_value and the scheme's argument as field_path before sending), and a cookie credential must be a cookie value (#4731). A declared response header with a byte outside ASCII fails its decode_..._header accessor with a DecodeError (reason invalid_header) instead of depending on how HTTPX2 decoded the header set; ResponseInfo.headers keeps HTTPX2's text (#4726). A parameter value that UTF-8 cannot encode, such as a lone surrogate, raises DecodeError (reason unencodable) before sending (#4730).\ as %5C, a space, |, [, non-ASCII as UTF-8), so no proxy or server reads \ as /; a % and two hex digits the document already encodes is sent as it is, any other % as %25 (#4706, fixes #4668)204 that the operation declares without a body, by its status, its range or default, ends a server-sent event stream with no events, also on a reopen or resume; an undeclared 204 still fails (#4707, fixes #4593)--output-model-type pydantic_v2.dataclass, JSON, form and multipart request bodies send the extra members of a dataclass that allows them (additionalProperties) (#4655)None member of an object parameter or of a URL-encoded or multipart form body, and a FieldPart whose value is None, are left out of the request (#4651). None for an optional request body whose type rejects null is sent as UNSET is, without a body or Content-Type (a media_type beside it raises ConfigurationError with the reason without_body), while a JSON body whose type admits null sends null; generation decides this from the model type by the rule the server uses, so every model backend sends the same request (#4731)1.0 counts 1 and 9007199254740993.0 exactly that, while 9007199254740993.00000000000000000001 is mistyped (#4731)UploadOptions.chunk_bytes raises ConfigurationError whose field_path names where the call's size came from, ("helper_defaults", "<helper>", "chunk_bytes") or ("upload_options", "chunk_bytes") (#4731)httpx2.Client / httpx2.AsyncClient with event_hooks (or a wrapping transport) as http_client, and limit concurrency with its pool limits (#4535).Auth, and a request carrying a credential at a position other than Authorization is never redirected (#4533, #4506)httpx2[ws] (#4463, #4512, #4513, #4514)helper_defaults (options by helper name), cache_stores (the store each cache helper uses) and allowed_origins (origins a next-URL pagination helper may follow beyond the server's). A cache helper without a lent store uses a per-client in-memory store of 128 entries (#4554).Accept header and the identity the request is sent as, including the credentials and every header the call's Auth added. A response is not stored when the request was sent as another identity, for example a rotated token or a header that an Auth or a request hook added after the lookup. Credentials the client cannot see, such as a client certificate, need a client or store of their own.UNSET is a typing_extensions.Sentinel (PEP 661), so type-checking generated clients needs mypy 2.4 or later, or pyright 1.1.414 or later (#4553)snake_case and classes PascalCase, whatever the model naming options say: GET /pets/{petId} becomes get_pets_by_pet_id, or follows its operationId. Parameters and body fields are named after their wire names like model fields, so --snake-case-field, --aliases, --special-field-name-prefix and the related options apply: client.pets.get_pet(petId=1) by default, get_pet(pet_id=1) with --snake-case-field (#4562).--naming-strategy and --duplicate-name-suffix apply to the generated API names as to models (root-document declarations first for primary-first, other collisions numbered such as get_pet_1) (#4562)Call GET /pets. in clients, Handle GET /pets. in servers); the operation summary and description are used only with --use-schema-description, and one-line docstrings render on three lines unless --use-single-line-docstring (#4557, #4564)int, list[str]) and the model types; imports that only annotations use follow the model resolver, so with ruff-check TC rules typing.get_type_hints on a generated public class or function can raise NameError. Pass --no-use-type-checking-imports, or do not select the TC rules, to introspect annotations at run time (#4566).The client and server output is rendered by overridable templates, like models. Put replacements for the roles you want to change in the client/ or fastapi/ directory of --custom-template-dir; roles you do not override keep their builtin template. Each role ships as a .jinja2 source, and the builtin renderers are compiled Python modules, so Jinja2 is needed only to render your overrides (#4394, #4401, #4557, #4564, #4566).
x-python-type annotations (GHSA-qxmr-3m23-97jm, high): a schema could put a quoted string inside an x-python-type annotation, such as list["..."]. It was written into the generated model as a forward reference, which Pydantic v2 evaluates when the model is built, so importing models generated from an untrusted schema could run code from that schema. String and bytes constants are now accepted only inside Literal[...]; any other annotation that contains one, including Annotated metadata such as Annotated[str, "meta"] and quoted names such as list["Foo"], stops generation with exit code 2 (the error does not name the property yet). 0.83.0 and earlier versions that read x-python-type are affected: upgrade if you generate models from schemas you do not control. Thanks to @wsparks-vc for the report.api scope model names no longer start with Field, and plain $refs are no longer wrapped: models that --openapi-scopes ... api derives from schemas written inside paths (parameters, request bodies, responses, response headers) are named from the path without the Field prefix that the leading / produced, as the paths scope names them: FieldPetsGetResponse becomes PetsGetResponse, FieldPetsGetResponse200xNextHeader becomes PetsGetResponse200xNextHeader; / alone becomes Root (RootGetResponse), a path that starts with a digit keeps Field (Field2faCodesGetResponse), and a derived name that a component schema already holds takes a numeric suffix (OrdersGetResponse1). A $ref there whose other keys are only x- extensions or annotations such as description now uses the referenced model, as a property does, instead of a wrapper RootModel (FieldPetsGetResponse(RootModel[Error]) becomes Error, so an error body reads body.code instead of body.root.code). Update imports and .root accesses of these models after regenerating; other scopes keep their names and models (#4696)--target-pydantic-version now selects the newest feature forms - pydantic-specific output no longer depends on the installed pydantic version. Feature forms (StringConstraints, dataclass aliases, deprecated, dict-key ordering, TypeAliasType, regex engine) follow the newest supported choice; field-name config keeps the 0.83.0 behaviour (populate_by_name; validate_by_name only for an explicit 2.11+), and --use-missing-sentinel still imports MISSING from pydantic.experimental.missing_sentinel as for 2.12 (only an explicit 2.14 imports it from pydantic). Generating on the latest pydantic gives the same output as 0.83.0. If you generate for older pydantic without passing a target, pass --target-pydantic-version 2 (Pydantic 2.0-compatible forms) (#4414)--target-pydantic-version 2 with --alias-generator now writes an explicit alias= on every field (#4428). Type checkers then expect the alias as the constructor argument name; --use-annotated keeps the field names for them.--target-pydantic-version 2 always writes the forms that Pydantic 2.0 accepts, whatever pydantic is installed. Besides #4428 and #4480, a deprecated field is written Field(json_schema_extra={'deprecated': True}) instead of Field(deprecated=True) (2.11 and later keep deprecated=True), and models used as dict keys are declared before the models that use them (#4414). With --use-annotated and pydantic_v2.dataclass, a required field whose non-identifier alias forces this assignment form moves to the end of the required fields, the only valid order for it (#4674).api scope parameter schemas (primitive/array parameter root models) are generated exactly as --use-type-alias generates them (type aliases with Annotated constraints) instead of RootModel; object parameters stay models. If you use the 0.83.0 api scope, the names stay but they are no longer classes: X = TypeAliasType("X", int) replaces class X(RootModel[int]): root: int = 0, the declared default is no longer written on the alias, and X(5), .root and X.model_validate(...) stop working; use the plain value or TypeAdapter(X). The same holds for a parameter that $refs a component parameter. Response headers stay RootModel with their default (#4424)--use-type-alias alias bodies now use Annotated[T, Field(...)] instead of con* types; lookaround patterns are emitted as re.compile(...), which needs pydantic 2.8+ at runtime (#4409, #4408). With --target-pydantic-version 2 the alias keeps the string pattern and every model that reaches the alias selects the Python regex engine, which works from pydantic 2.5 (#4620). The pydantic_v2.dataclass output model type always writes its root models as type aliases, so it changes the same way without the flag, and so do the aliases the generator writes for the keys of type: [array, object] schemas with propertyNames (dict[constr(pattern=r'^a'), Any] becomes dict[Annotated[str, Field(pattern=r'^a')], Any]).bytes field selects it only with --target-pydantic-version 2.14, the first pydantic version that applies a pattern to bytes; other targets write bytes fields as 0.83.0 did (#4542, #4622)union_mode (#4417)time, date-time, ...) and number keywords keeps its time type in default mode instead of becoming a (strict) float (#4462, #4472). With --field-constraints or --use-annotated its bounds are written as in 0.83.0 (#4621)--alias-generator combined with serialization aliases keeps the schema names (#4474)allOf inheritance (cycles, base defined after subclass, MRO conflicts) is now an error instead of unimportable or empty output (#4348, fixes #4300). This includes a valid schema where --reuse-model merges two identical bases (for example Left and Right below the same base) that a model inherits from together: 0.83.0 wrote code that fails on import, and generation now stops with an inconsistent method resolution order error; run without --reuse-model for such a schema.--generate-cli-command prints mapping options as JSON / path=package (#4395)--external-ref-mapping FILE_PATH=PYTHON_PACKAGE splits at the last = instead of the first, so a file path may contain = and an entry with several = is read differently (#4395)--generate-cli (now also --generate-client), --generate-s (--generate-server, --generate-schema-validators), --ser (--server-*). Spell options in full.ORIGINAL_FIELD_NAME_DELIMITER_ERROR is no longer an attribute of datamodel_code_generator.__main__ (#4291).--use-annotated writes the key of a constrained dictionary as Annotated[str, StringConstraints(...)] instead of constr(...) (Annotated[str, Field(...)] with --target-pydantic-version 2) (#4244, fixes #4235)pydantic_v2.dataclass field that is named like its type is renamed only where its default or Field() call hides the type from the annotation: Pet: Pet | None = None becomes Pet_1: Pet | None = Field(None, alias='Pet'), output that failed in 0.83.0. Fields that worked in 0.83.0 keep their names, such as a required Pet: Pet. msgspec.Struct fields are never renamed: the hidden type is written as a forward reference, through from __future__ import annotations or, with --disable-future-imports, as a quoted name (Union["Pet", UnsetType]). Pydantic BaseModel fields named like their own type and standard dataclass field names are unchanged; the #4723 fixes under Bug fixes change only output whose annotations did not resolve in 0.83.0 (#4172, #4624, fixes #4144)--alias-generator with a serialization alias equal to the field name keeps that alias; the alias generator no longer rewrites it. 56 BaseModel outputs in the test suite change (#4488)minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf) are written only where the generated Python type takes them: int, float and Decimal; the four bounds on timedelta, datetime and time (with --field-constraints or --use-annotated, as in 0.83.0); and types the generator does not know (x-python-type, customTypePath, --type-overrides, --type-mappings). They are dropped from strings, bytes, booleans, dates, UUIDs, containers and null-only schemas, and multipleOf is dropped from timedelta, datetime and time, also when a custom template renders the field. msgspec.Struct keeps them on int, float and unknown types; constraints msgspec refuses (such as bounds on Decimal) are left out with a warning (#4715). The table is in the field-constraints page (#4489, #4621). Known limit, unchanged from 0.83.0: time bounds fail at import on pydantic 2.11.x and timedelta bounds on pydantic 2.11.0 to 2.11.2.type (written as Any) keeps none of them (#4641). minLength, maxLength and pattern are written on strings and bytes, minItems, maxItems and uniqueItems on arrays; a string schema still writes minItems / maxItems and an array schema minLength / maxLength as length bounds. With --field-constraints, {"minimum": 1} was num: Any | None = Field(None, ge=1) in 0.83.0 and is num: Any | None = None now; {"type": "integer", "pattern": "^1"} loses pattern='^1'; an array with pattern loses the pattern. msgspec.Struct output changes the same way with or without the flag (Annotated[Any, Meta(ge=1)] becomes Any); 0.83.0 output such as Annotated[int, Meta(pattern='^1')] failed when msgspec built the decoder. Add type to the schema to keep a constraint. The table is in the field-constraints page. Side effects: repeated or nested members of a union are written once and flat, for example anonymous members that become identical once their constraints are dropped (dict[Any | Root1 | Root2, Any] becomes dict[Any | Root1, Any]) and members repeated after --collapse-root-models (str | bool | int | bool | None becomes str | bool | int | None; Union[list[...], bool | str] becomes Union[list[...], bool, str]), which Python treats as the same type; and --formatters builtin splits a long union annotation where black does. A type given by x-python-type, customTypePath, --type-overrides or --type-mappings follows the rule of the type it names: "x-python-type": "dict[str, int]" or "str" with minItems: 2 wrote Field(None, min_length=2) in 0.83.0 and writes no constraint now, and type: boolean with multipleOf no longer writes multiple_of. Standard typing / collections.abc names follow the kind they stand for: sequences, sets, Sized, Collection, Iterable and Generator take length keywords, AnyStr and ByteString string keywords; protocols that guarantee no length or value kind (Container, Reversible, Buffer, SupportsInt, SupportsBytes, Callable, ...) take none (#4672). A Literal[...] type is read as the union of its value types (str, bytes, int, float; nested Literals flattened, None left out), so Literal["a", "bb", None] keeps minLength and Literal[1.5, 2.5] keeps minimum as in 0.83.0; a bool value takes no keyword, so Literal[True, False] with minimum: 1 no longer writes ge=1; a Literal that mixes value kinds (Literal['a', 1]), which made 0.83.0 models fail at every validation, gets no keyword, and msgspec.Struct writes none on a Literal override, where 0.83.0's Meta(...) raised TypeError on every decode (#4684).pydantic_v2.dataclass: with --target-pydantic-version 2.14, a required field written as = Field(...) (an alias, a description, a constraint) is placed before the fields with defaults of the same class, so the class has a valid signature on pydantic 2.13 and later; this changes the positional argument order of such classes for that target only (#4650, #4674). With the target unset or older, the 0.83.0 order is kept: such a class validates and constructs as before, but pydantic 2.13 and later cannot read its signature (FastAPI, IDEs) and on Python 3.10 a dataclass that inherits from it fails at import; generation now warns about each such class and the fix is to pass --target-pydantic-version 2.14.allOf that combines a scalar type with constraints now generates a scalar root model or alias that keeps the constraints, the description and the other metadata; wrappers over object bases, untyped constraints and several patterns are unchanged (#4484)# filename: and command: header lines and from the source_ref of --emit-model-metadata; the path is kept (#4570)allOf models are nullable where they are referenced (bug fix, #4647): a model written with allOf whose type list contains null (OpenAPI 3.1 / JSON Schema type: [object, "null"]) now carries the null to every reference, as a plain type: [object, "null"] object already did in 0.83.0. r_wrapper: Wrapper becomes r_wrapper: Wrapper | None, list[Wrapper] becomes list[Wrapper | None] and dict[str, Merged] becomes dict[str, Merged | None], on every backend and without any option. With --strict-nullable, an array whose inline item object is nullable: true (OpenAPI 3.0) is list[Item | None] (was list[Item]), and a union member that references a nullable model keeps its None (Obj | Obj2 becomes Obj | None | Obj2 | None for msgspec.Struct; Union[Optional[Kind1], Optional[Kind2]] without the union operator on the other backends). The models now accept the null the schema allows; type checkers report attribute access on these fields as possibly None.generate() applies the command line's implied model settings (#4734): command-line and pyproject.toml output is unchanged. When you leave them unset, generate() now derives the same settings as the CLI: msgspec.Struct output turns on use_annotated, and use_annotated turns on field_constraints. So generate(..., output_model_type=DataModelType.MsgspecStruct) writes the schema's constraints like the CLI: a maxLength: 3 string that 0.83.0 wrote as n: str | UnsetType = UNSET is now n: Annotated[str, Meta(max_length=3)] | UnsetType = UNSET, and the models reject values the schema rejects. generate(use_annotated=True) without field_constraints=True now generates instead of raising Exception: `use_annotated=True` has to be used with `field_constraints=True` . Pass use_annotated=False to keep the 0.83.0 msgspec output.Pydantic 2.14 as a target: --target-pydantic-version 2.14 imports MISSING from the public pydantic package for --use-missing-sentinel (#4542)
--use-missing-sentinel also supports --output-model-type pydantic_v2.dataclass: an optional field without a default is written as tag: str | MISSING = MISSING; 0.83.0 refused the combination (#4651)
graphql-core 3.3: input-field defaults are read correctly (#4546, fixes #4545)
Python API: project configuration loading with load_pyproject_config() (#4291)
msgspec.Struct: --use-msgspec-tagged-unions writes a discriminated union as msgspec tagged structs as a whole, so the union can be decoded: every variant is tagged with the document's property name and its value (from mapping, a single-value enum, or the schema name), or none is and a warning says why (for example a variant that inherits the property from a base struct). A tagged struct has no discriminator field, so Cat(petType=...) and cat.petType are not available. Without the option the 0.83.0 form is kept (#4646, #4670). Generated msgspec clients require the option (#4676). A struct that --reuse-model derives from a tagged variant, also in another module, stays importable, and a subclass that redeclares the tag field as an ordinary field (kind: str), which msgspec forbids beside a tag, is written with tag=False (#4735).
msgspec.Struct: --use-msgspec-nullable-enum-alias writes an enum that lists null without type: string / nullable as an Enum without the None member plus an Enum | None alias (class CEnum(Enum) and C: TypeAlias = CEnum | None), which msgspec can decode. Without the option the 0.83.0 form is kept (class C(Enum) with a None member, which msgspec cannot decode) (#4649, #4677). Generated msgspec clients require the option (#4677).
--use-typed-nullable-map-values types the values of nullable maps (additionalProperties of an object that may be null, nested maps, const nullable maps), which stay dict[str, Any] without it, as in 0.83.0. An inline value object becomes a class with a free name (Tags1 beside an existing Tags), and options keyed by class name (--base-class-map, --aliases, --extra-template-data, ...) apply to it under that name. With --reuse-model or --collapse-root-models, typed values follow the rules of other maps: equal models are merged, root models collapse into the value type, and maps whose value types differ are no longer subclasses of one another; where typed values would move models to another module or create _internal.py or a shared module, that run keeps dict[str, Any] (#4478, #4679, #4685, #4695)
--reuse-model --collapse-reuse-models and an import cycle merged into _internal.py, a module no longer re-exports a class that reuse removed from _internal.py, which made 0.83.0 packages fail at import (#4695)gc.get_threshold, such as PyPy, where 0.83.0 raised AttributeError (#4688, #4689)properties next to a oneOf or anyOf, each branch keeps the intersection of its enum and the parent's, as allOf does since #3961, instead of both lists with duplicate members; an empty intersection keeps both lists as before. In msgspec output a branch whose intersection has one value is written as that Literal (#4702, fixes #4469)--reuse-model: a variant that reuse writes as a subclass of an equal model takes the tag its own discriminator mapping gives it (class Kitten(Cat): kind: Literal['kitty']), where 0.83.0 kept the other model's tag (Literal['cat']) or wrote one no document names, so the union could not decode its own tag. With --collapse-reuse-models, which merges such variants into one class, the 0.83.0 output is kept and the warning above names each union that cannot decode the variant (#4735)--reuse-model, --collapse-reuse-models and --reuse-scope tree no longer merge discriminated unions whose discriminator property or mapping differs, so each union keeps its own discriminator; a variant that several such unions map to different tags keeps one union's tag and the shared-variant warning names the others (as without --reuse-model). Models named Literal keep their 0.83.0 name when reused variants get Literal tags; typing.Literal is imported under an alias instead (#4761, #4762)--read-only-write-only-model-type, the request and response variants of a discriminated union member take the member's tag (Literal['cat'], msgspec tag='cat') instead of an internal path that no document matches (#4711, fixes #4509)Meta constraints only on types msgspec accepts them on (number bounds on int/float, lengths on strings, bytes and collections, pattern on str) and warns about each field whose constraints it leaves out, instead of output such as Annotated[Decimal, Meta(ge=0)] that msgspec refused to decode (#4715). On a float, multiple_of is written only for a divisor a float represents exactly, such as 2, 0.5 or 1.5: msgspec checks it by a floating-point remainder, so 0.83.0's Meta(multiple_of=0.01) rejected valid multiples such as 0.07 and 0.5; such a divisor is left out with the same warning (#4734)--strict-types bytes keeps the constraints of a binary string: conbytes(min_length=100, strict=True) instead of StrictBytes, which dropped them and accepted bytes the schema rejects (#4734)contains / minContains / maxContains imply now also apply beside a sibling contains of a $ref, where 0.83.0 kept only the sibling contains (#4735)allOf models are closed (extra='forbid' for Pydantic models and dataclasses, closed=True for TypedDict) when an inline allOf member declares additionalProperties: false without patternProperties, including a member nested in another inline allOf or merged with several $ref members; before, the model kept or inherited the open configuration and accepted properties the schema rejects. A closed member with patternProperties keeps the model open as before (#4739)Meta constraints, with a per-field warning: members of one Python type (bytes | Annotated[bytes, Meta(max_length=3)] becomes bytes), members reached through an alias of a union or of a nullable type, and a constrained int beside a float member (msgspec decodes every integer as the int member). msgspec applied one member's constraints to the whole union and rejected values another branch accepts; when one member carries exactly the constraints all such members share, those are kept, otherwise all are left out (#4756), and the alias models keep their own (#4738)--reuse-model (with or without --collapse-reuse-models): a module that uses a model or enum that reuse removed from another module imports the kept one, instead of failing at import (#4717)generate_dynamic_models(..., module_name=...) no longer raises KeyError for generated generics such as RootModel[list[int]]; while the code runs, module_name is registered in sys.modules, and a module of that name that can be imported is imported first (#4718)tag (a single literal) or opts out with tag=False (any other type), so default msgspec output with const variants under a tagged base imports instead of failing with Required field ... cannot follow optional fields (#4735)dataclasses.dataclass output with a field named like a type it uses imports and resolves without from __future__ import annotations (--disable-future-imports), and --use-default-factory-for-optional-nested-models no longer writes a factory that calls the field's default (#4719)Bar: int | None = None beside Zed: Bar | None = None) failed in 0.83.0 with TypeError: unsupported operand type(s) for | when the annotations resolved. Pydantic BaseModel and pydantic_v2.dataclass now rename it (Bar_1: int | None = Field(None, alias='Bar')), also when the hiding field comes after the fields that use the type: with --disable-future-imports such output worked on Python 3.10 to 3.13 but fails on Python 3.14, which evaluates annotations after the class body. The new name never reuses a name another field or alias of the model family already has (#4758); msgspec.Struct and standard dataclass fields keep their names. Standard dataclasses.dataclass output writes the default of a field named like a type of its class as field(default_factory=lambda: None), on every target Python, so the class no longer binds the name and typing.get_type_hints, Pydantic's TypeAdapter and Python 3.14's deferred annotations find the type instead of the default (0.83.0's Bar: Bar | None = None resolved to None | None). Construction and defaults are unchanged; dataclasses.fields() reports a default_factory for such a field and the class has no attribute of its name.Bar_1: b.Bar without alias='Bar', so validation required Bar_1), and --field-type-collision-strategy rename-type imports a renamed type by its final name (0.83.0 wrote a.Bar, an AttributeError at import)--use-msgspec-tagged-unions / --use-msgspec-nullable-enum-alias, and a union of Structs that are not all tagged and that the option does not tag, such as a GraphQL union, is named too (#4713); enum member names beside null that keep the shifted 0.83.0 names say so (#4714)pydantic requirement excludes 2.10.0, 2.10.1 and 2.10.2, with which every generation failed with SerializeAsAny is not defined since 0.78.0 (#4700, fixes #4490)Literal import for overridden literal fields (#4135)Field for list/set defaults in Pydantic dataclasses (#4423)allowReserved by OpenAPI version (#4330)--check (#4466)--check / --diff-against / --output-format json for suffixless single-file outputs (#4451, #4471, #4475)generate() callers get datamodel_code_generator.Error instead of NotADirectoryError--aliases report too deeply nested values and huge integers as option errors (Unable to load alias mapping: nests too deeply to parse) instead of a traceback (#4413)$refs, which fixes failures with plain $ref parameters from before 0.84.0 (#4478).--target-pydantic-version 2: fields that reference a model declared later are written as assignments (x: T = Field(...)) instead of Annotated, including Pydantic dataclasses, so the output works with older Pydantic 2 releases (#4480)TypeAliasType values quote each recursive container as a whole ("list[JsonType]" instead of list["JsonType"]) when no target is set, so mypy no longer reports a cyclic definition; --target-pydantic-version 2 keeps quoting each name. --formatters builtin no longer adds a trailing comma after the only element of a split subscript, as black does not (#4422)$ref and schema-path messages; the path is kept, so @scope CDN paths still show (#4570, fixes #4521)--http-local-ref-path: the mirror lookup ignores userinfo and uses host[:port] and the path (#4570)httpx2.MockTransport and responses built with json= / content=, including raw reads of identity-coded bodies (#4584)generate() with non-string keys in the client_operations parameter_names, runtime or idempotency settings now reports a configuration error instead of an AttributeError / TypeError (#4585)None, as for UNSET; required parameters still refuse None at call time with a DecodeError (unencodable) (#4590)llms.txt (#4573, #4582, #4583)400 for a multipart field part over 1 MiB (the client sends JSON parts as fields; send a large value as a FilePart) and reads a field part that is not UTF-8 as Latin-1, HTTPX2 replaces the Cookie header on each redirect with the matching cookies of the client's jar, and ResponseInfo.headers holds the text HTTPX2 decodes for the whole header set (#4732)$ref allOf ({"allOf": [{"$ref": "#/$defs/Number"}], "minimum": 5}) are still not enforced, as in 0.83.0 (#4765).ValueError: '3.15' is not a valid PythonVersion (#4589).FutureWarning (so python -W error::FutureWarning now exits 2 on 3.10). Generating code for Python 3.10 with --target-python-version 3.10 is unaffected.--target-pydantic-version 2 (or 2.11) if you relied on the installed pydantic version choosing the output.X(value), .root and X.model_validate(value) with the plain value or TypeAdapter(X), and apply the parameter default yourself where you relied on the RootModel default.--use-type-alias: regenerate; aliases use Annotated[...], and lookaround patterns need pydantic 2.8+, or --target-pydantic-version 2 for pydantic 2.5 to 2.7.allOf: schemas that produced unimportable output now fail with an error; fix the inheritance cycle or ordering, or drop --reuse-model when it is what merges the bases into a conflicting order.--use-annotated dict keys: regenerate Pydantic dataclass output (an optional attribute such as Pet: Pet | None = None becomes Pet_1 with the original name kept as alias=; update code that reads it; msgspec.Struct fields keep their names), and --use-annotated output that has constrained dict keys.allOf: regenerate; serialization aliases equal to the field name stay, constraints disappear from non-number fields (use --type-mappings to number types to keep them), and scalar allOf schemas gain constrained root models.command: lines and source_ref no longer show URL credentials, query or fragment; regenerate if you checked in such output.--target-pydantic-version 2: affected fields change to assignments on regeneration.pydantic_v2.dataclass signatures: with pydantic 2.13 or later (and on Python 3.10 for subclasses), pass --target-pydantic-version 2.14 so required fields come first; the generator warns about each class that needs it.type to a schema whose constraints you want kept; an untyped schema is written as Any without type-dependent constraints.generate() with msgspec.Struct: the models now carry the schema's constraints, as the CLI's do; pass use_annotated=False to keep the 0.83.0 output without them.Note truncated.
Deduplication now compares referenced models - Models that render identically are only merged when the models they reference also match structurally,
LeafModel or Values1, changing class names and module contents compared with previous output (#4115)$dynamicRef are now specialized per dynamic scope - A plain-name $dynamicRef previously resolved lexically within its own schema resource, so every referrer shared one model of the referenced generic. The parser now tracks the dynamic scope of the schemas that referenced a model, binds each $dynamicAnchor name to its outermost declaration in that scope, and re-parses a referenced schema as an additional specialized model whenever its bindings differ. Schemas that combine $dynamicRef with $dynamicAnchor, including remote, embedded, recursive, root-level and tuple additionalItems generics, now emit extra model classes with suffixed names and different field types than before, so generated module contents, class names and import sites can change for existing users (#4117)Model suffixes. Output ordering and names of surrounding models can therefore differ from previous releases, and this applies under --naming-strategy full-path and --collapse-root-models as well (#4117)parse_raw now drains pending dynamic-scope specializations after every specification has been read, so components that reference external schemas rebinding a $dynamicAnchor produce additional specialized models instead of reusing a single shared model (#4117)$dynamicRef is now resolved within the schema resource a subschema stands for, namely an inline subschema declaring its own $id and the target of a $ref merged with sibling keywords, with enclosing and referencing resources still able to override the binding so the outermost $dynamicAnchor declaration wins; schemas combining $dynamicRef with embedded $id resources or with $ref plus sibling keywords may now generate different field types and model shapes than before, for example a resource-local anchor type such as RootModel[str] where the previous output used the anchor visible in the outer scope (#4119)--reuse-model, --collapse-reuse-models and --reuse-scope=tree previously matched models on rendered output and imports alone, so models that rendered identically but referenced different models sharing a name were incorrectly collapsed into one. Duplicate detection within a module and across modules now also requires the referenced models to match, so these models stay distinct. Affected schemas now generate additional or differently named classes, such as a suffixed FieldModel alongside Field, extra per-module classes, and inheritance from a shared base instead of a single merged model, which can change class names and module layout that downstream code imports (#4121)$ref targets now resolve through aliases - A referenced schema that is itself a $ref is merged with its own target, so a $ref with sibling keywords pointing at an alias now generates the aliased definition instead of the alias node, changing model names and field types in generated output for JSON Schema 2020-12 documents that use $ref alongside other keywords (#4122)$ref with sibling keywords points into another document, nested $ref and plain-name $dynamicRef values are rewritten to absolute locations before merging, so schemas whose relative references previously resolved against the wrong base now produce different models, imports, and field types (#4122)$recursiveRef in merged cross-document $ref targets - A self-pointing $recursiveRef inside a schema merged in from another document now resolves to the nearest enclosing $recursiveAnchor of its defining document, or that document's root, instead of resolving against the merging document; schemas that rely on the previous resolution generate different recursive model references and field annotations, so regenerated models may name different classes than before, and when the merging document itself declares $recursiveAnchor the reference is instead left to extend the dynamic scope (#4127)_prepare_schema_resources rather than the original raw specification, so specifications that use $id inside component schemas can produce different models, model names, and field types than before (#4128)Tree, Node, or Branch now reuse the single shared model, so generated class names, class counts, and field annotations can change and code importing the previously emitted duplicate class names will need updating (#4133)$id resources resolve to the resource root - A $recursiveRef located in a subschema that declares its own $id but no $recursiveAnchor now targets the root of that embedded resource instead of the nearest enclosing $recursiveAnchor or the document root, both when the document is parsed directly and when its schemas are merged into another document, so affected fields are annotated with the embedded resource model instead of the outer model, and targets reachable only through $recursiveRef are now loaded and can add generated models (#4130)Field or FieldModel; it is now named after the file stem, for example Tree or Node, so class names and field annotations such as list[Field] change for such schemas (#4132)allOf base class is referenced from a schema whose dynamic scope would rebind its $dynamicAnchor, the parser now emits a UserWarning stating that the base class resolves its $dynamicRef within its own schema resources. Generation still succeeds, but builds that treat warnings as errors or assert on captured warnings can now fail (#4117)SchemaResourceRefWarning, so generation runs that previously completed silently can now surface warnings and can fail where warnings are configured as errors (#4128)--external-ref-mapping entries must now name the path of the document the reference actually comes from rather than a path relative to the merged target, so existing mappings that relied on the previous matching may silently stop applying (#4122)<!-- Release notes generated using configuration in .github/release.yml at main -->
Full Changelog: https://github.com/datamodel-code-generator/datamodel-code-generator/compare/0.82.0...0.83.0
Constraints are now emitted on recursive container fields - Previously any field that was a self reference had all of its constraints suppressed. The
_can_apply_constraints property in the base field model only suppresses constraints for direct self references, so a self referencing field whose type is a container such as list, Sequence, dict, Mapping, set, frozenset, or tuple now keeps its size constraints. Pydantic output gains Field(min_length=..., max_length=...) and msgspec output gains Meta(min_length=..., max_length=...) where the generated code previously had a bare default, for example friends: list[Pet] | None = None becomes friends: list[Pet] | None = Field(None, min_length=1) (#4071)minItems or maxItems on a recursive array is rejected at validation time instead of being accepted. Existing code that relied on the previously unconstrained generated models may start raising pydantic ValidationError or msgspec.ValidationError for payloads that used to pass (#4071)<!-- Release notes generated using configuration in .github/release.yml at main -->
<!-- Release notes generated using configuration in .github/release.yml at main -->
Full Changelog: https://github.com/datamodel-code-generator/datamodel-code-generator/compare/0.81.0...0.82.0
Undeclared required keys now retained in variant runtime validation - When combining --read-only-write-only-model-type request/response variants with
--read-only-write-only-model-type request/response variants with --schema-validator-type runtime validators, generated models now keep runtime validation rules for required keys that are not declared as properties (for example keys required via additionalProperties or if/then/else), whereas these rules were previously dropped from the variant models. Regenerated Request and Response models therefore enforce stricter validation and may reject payloads that the previously generated validators accepted (#4055)<!-- Release notes generated using configuration in .github/release.yml at main -->
<!-- Release notes generated using configuration in .github/release.yml at main -->
<!-- Release notes generated using configuration in .github/release.yml at main -->
<!-- Release notes generated using configuration in .github/release.yml at main -->
<!-- Release notes generated using configuration in .github/release.yml at main -->
<!-- Release notes generated using configuration in .github/release.yml at main -->
<!-- Release notes generated using configuration in .github/release.yml at main -->
Full Changelog: https://github.com/datamodel-code-generator/datamodel-code-generator/compare/0.80.0...0.81.0
Python union annotations preserve unsupported member types - When generating from Python input models, unions containing members such as Callable reta
Callable retain each member type and the original union order instead of repeating the first non-null type. Regenerated annotations change for the affected unions and nested containers. (#3947)--use-default-factory-for-optional-nested-models, an optional child with required constructor fields, including inherited fields, keeps its normal None or UNSET default instead of receiving a factory that fails when called without arguments. (#3953)--use-root-model-type-alias, constraints are retained in the alias where supported; affected roots otherwise use a RootModel class instead of an unconstrained alias. Unconstrained aliases retain their prior form, and an existing custom root-alias template keeps its selection and remains responsible for its own constraints. (#3962)propertyNames generate inline constrained string key types instead of nested-model keys. This changes ordinary key annotations for affected schemas; custom schema runtime validators remain conditional on --schema-validator-type pydantic-v2. (#3970)--schema-validator-type pydantic-v2, required property names absent from generated fields are checked against the raw object input, including applicable pattern intersections. Payloads missing those required names are rejected where the previous validators accepted them; this fix does not add a validator when the option is disabled. (#3988)allOf roots with an outer format or type mapping, compatible numeric or string constraints are preserved while constraints incompatible with the mapped runtime type are omitted. Regenerated annotations change for these roots and avoid applying incompatible constraints to date, UUID, or other mapped values. (#4043)propertyNames alternatives combining ordinary string constraints with non-string-only branches, generated dictionary keys use the applicable constrained string type instead of retaining the non-string alternatives. References, complex patterns, and unsupported cases retain the existing fallback. (#4046)--type-mappings or --type-overrides remap Avro logical types to physical types such as int or bytes, affected defaults use the physical Avro value instead of a logical constructor such as a datetime, decimal, or duration expression. (#4031)<!-- Release notes generated using configuration in .github/release.yml at main -->
<!-- Release notes generated using configuration in .github/release.yml at main -->
Full Changelog: https://github.com/datamodel-code-generator/datamodel-code-generator/compare/0.79.0...0.80.0
Reject unsupported msgspec enum members - When generating msgspec.Struct output, enums that would render as a plain Enum and contain bool or float mem
msgspec.Struct output, enums that would render as a plain Enum and contain bool or float members now raise an error such as msgspec.Struct does not support bool Enum members, instead of producing code; schemas that previously generated output will now fail and no file is written (#3928)msgspec.Struct models with more than one base class, the generator now validates the inherited slot layouts and raises an Error refusing to write any output when the generated bases would produce incompatible instance layouts, whereas previously it emitted a module that only failed later at Python import time; both the CLI (which now exits with an error and writes no file) and the Python API (which now raises Error) are affected for such schemas (#3929)aliases option is used, an alias value that collides with another field, is not a valid Python identifier, is a Python keyword, or conflicts with a reserved Pydantic or msgspec attribute name now raises an Error and stops generation instead of being silently sanitized or deduplicated (#3936)aliases option are now preserved as the chosen field names and checked against each output backend's naming rules, so configurations that previously produced auto-adjusted output for dataclasses, msgspec, or TypedDict backends may now fail instead of quietly renaming the field (#3936)dict, so non-dict mapping objects such as UserDict or MappingProxyType bypassed pattern-property, required-group, conditional-required, property-count, and unique-items checks; they are now treated like dictionaries and validated, which can raise a ValidationError for mapping inputs that previously passed through silently (#3975)$id are now resolved within the containing document before any file or HTTP lookup, and resource-scoped anchors and JSON pointers are honored, so schemas that previously resolved such references to physical files or remote URLs (including cases where an embedded resource shares a physical filename) can now produce different generated models and different fetch behavior (#3977)treat-dot-as-module is combined with all-exports-scope, export depth and collision prefixes are recomputed against the final package layout and the empty-package re-export __init__.py files are emitted after module post-processing, so projects generated with both options together will see different import paths and __init__.py contents than before (#3926)
<!-- Release notes generated using configuration in .github/release.yml at main -->
<!-- Release notes generated using configuration in .github/release.yml at main -->
<!-- Release notes generated using configuration in .github/release.yml at main -->
<!-- Release notes generated using configuration in .github/release.yml at main -->_1, _2 suffixes when they collide with another validator, an existing field name, or an inherited validator, so models using the validators feature with inheritance or overlapping field names can produce method names that differ from previously generated output (#3942)Optional as Optional_aliased, Field as Field_aliased, or list as list_aliased_2 and rewrites the affected annotations and defaults to reference the alias; this runs by default with no opt-in flag, so generated output changes for any schema whose field names collide with imported names (#3943)
<!-- Release notes generated using configuration in .github/release.yml at main -->
<!-- Release notes generated using configuration in .github/release.yml at main -->_json_schema_conditional_equal helper and stop relying on Python in membership, so when an if then else conditional required rule has const or enum values that include booleans or the integers 0 and 1 (or nested objects and arrays containing them) the generated code now distinguishes booleans from numbers and compares objects and arrays deeply, changing both the generated output and the runtime acceptance of payloads for schemas built with schema-validator-type pydantic-v2 (#3960)
<!-- Release notes generated using configuration in .github/release.yml at main -->from collections.abc import Mapping as _Mapping import and every isinstance(data, dict) guard becomes isinstance(data, dict) or isinstance(data, _Mapping), while structural match cases change from case dict() to case dict() or _Mapping(); users who compare regenerated output against committed golden files will see these differences (#3975)
<!-- Release notes generated using configuration in .github/release.yml at main -->
<!-- Release notes generated using configuration in .github/release.yml at main -->
<!-- Release notes generated using configuration in .github/release.yml at main --><!-- Release notes generated using configuration in .github/release.yml at main -->
Full Changelog: https://github.com/datamodel-code-generator/datamodel-code-generator/compare/0.78.0...0.79.0
MCP tools schema-instance values preserved verbatim - Converting MCP tools inputs now keeps values under default, const, enum, and examples unchanged
default, const, enum, and examples unchanged instead of rewriting internal definition references contained within them, so generated model defaults for MCP tools schemas that embed ref-like values inside these instance keywords can differ from previously generated output (#3891)
<!-- Release notes generated using configuration in .github/release.yml at main -->
<!-- Release notes generated using configuration in .github/release.yml at main -->~0 and ~1 tilde escapes are unescaped, following RFC evaluation order, so a $ref fragment that combines percent-encoding with tilde escapes such as a%7E1b now resolves to a different definition than before and can change the generated models for those schemas (#3893)
<!-- Release notes generated using configuration in .github/release.yml at main -->_intersect_constraint logic no longer coerces minimum, maximum, exclusiveMinimum, and exclusiveMaximum operands to float before comparing them, so integer bounds beyond the 2^53 exact-float precision limit are now intersected exactly instead of after lossy float rounding, changing the generated ge, le, gt, and lt values for schemas that merge such large integer bounds via allOf (#3900)
<!-- Release notes generated using configuration in .github/release.yml at main -->multipleOf, exclusiveMinimum, and exclusiveMaximum now retain exact integer values instead of coercing them to floats, so regenerated models for schemas containing integers beyond float precision emit different constraint literals and validate differently than before (#3903)
<!-- Release notes generated using configuration in .github/release.yml at main -->allof_merge_mode is any value other than none, overlapping numeric, length, item, and property-count bounds from allOf subschemas are intersected to the tightest value and enum values are reduced to their intersection, instead of the previous deep-merge or concatenation behavior, so generated constraints and enum members differ from prior releases (#3961)field_constraints and generate_schema_validators both enabled and builtin types in use, a root-level array whose items declare a single ASCII-alphanumeric patternProperties key mapping to a length-bounded string now generates a constr adapter carrying min_length/max_length instead of a plain str, so regenerated models change output and enforce those bounds, rejecting values that previously passed validation (#3992)maxOccurs, an unbounded maximum is now propagated instead of computing a finite upper bound, so an unbounded parent combined with a finite child (and similar nesting) no longer emits a max_length constraint, changing the generated output for affected schemas (#3939)SchemaParseError and aborts instead of producing a widened or concatenated enum, so schemas that previously generated successfully can now fail (#3961)
<!-- Release notes generated using configuration in .github/release.yml at main -->
<!-- Release notes generated using configuration in .github/release.yml at main -->
<!-- Release notes generated using configuration in .github/release.yml at main -->
<!-- Release notes generated using configuration in .github/release.yml at main -->
<!-- Release notes generated using configuration in .github/release.yml at main -->
<!-- Release notes generated using configuration in .github/release.yml at main -->
<!-- Release notes generated using configuration in .github/release.yml at main -->
<!-- Release notes generated using configuration in .github/release.yml at main -->black or isort formatters through the CLI, resolved configuration, or the Python API now emits a FutureWarning announcing that Black/isort will become optional in a future release; previously explicit formatter selection produced no warning. Black and isort remain required dependencies and generated output is unchanged, but strict setups that treat FutureWarning as an error may now fail unless the warning is filtered or disable-warnings is used (#4009)
<!-- Release notes generated using configuration in .github/release.yml at main --><!-- Release notes generated using configuration in .github/release.yml at main -->
<!-- Release notes generated using configuration in .github/release.yml at main -->
<!-- Release notes generated using configuration in .github/release.yml at main -->
Full Changelog: https://github.com/datamodel-code-generator/datamodel-code-generator/compare/0.77.0...0.78.0
Nested Avro bytes and fixed defaults are now decoded to bytes - Avro bytes and fixed defaults nested inside arrays, maps, and records are now converte
bytes and fixed defaults nested inside arrays, maps, and records are now converted to Python bytes literals such as b'\xff', whereas previously only top-level bytes and fixed defaults were converted and nested ones remained as strings, so regenerating affected Avro schemas produces different default values across the pydantic v2, dataclass, and msgspec backends (#3896)Field(default_factory=...) and add a from pydantic import Field import instead of the previous plain default rendering, so regenerating existing schemas produces different output; ClassVar and plain required dictionary fields are additionally kept free of Field statements (#3883)as alias are split onto separate lines, so files regenerated from the same input will differ from output produced by earlier versions (#3874)bytes and fixed fields carrying a decimal logical type with a default now decode the default as a signed big-endian coefficient scaled by the declared scale and emit a Decimal(...) expression for backends that support deserialized defaults, replacing the previous raw bytes literal output, so regenerating existing models yields different default values (#3902)date, time-millis, time-micros, timestamp-millis, timestamp-micros, timestamp-nanos, or the local-timestamp variants, an integer default is now rendered as a temporal constructor like datetime_module.date.fromisoformat or an ISO-8601 string for backends that map these formats to str, instead of the previous raw integer literal, so generated models change for any schema using these defaults; timestamp defaults use UTC while local-timestamp and time defaults are naive (#3901)fixed fields using the duration logical type with a default now emit timedelta(milliseconds=N) values instead of the raw bytes previously produced, changing generated output for any schema that relies on such defaults (#3907)1 lexical value - Elements declared with nillable="1" are now treated the same as nillable="true" and generate a nullable field, so schemas that previously produced a required field for nillable="1" will now produce an optional (nullable) field (#3884)xs:pattern facets previously kept only the last pattern value, and now the parser merges all supported sibling patterns into a single anchored alternation and intersects any inherited base pattern through a nested lookahead, so regenerating from such schemas produces different pattern strings than before (#3908)regex_engine="python-re" configuration entry that was not present before, because the generated anchored lookahead requires Pydantic's Python regex engine, changing the generated model configuration for affected fields (#3908)convert to construct the referenced Struct instance, whereas previously such defaults were emitted as plain literal values because only direct Struct references were converted; empty collections, mapping and dict defaults, primitive aliases, and recursive non-model aliases keep their prior output (#3906)false now raise an Error reading "Referenced MCP boolean false definition is not supported" instead of emitting a permissive model, so schemas that previously generated code may now fail during conversion (#3890)root - When emitting model metadata for RootModel classes, the emitted field entry now uses root for both its name and alias instead of the previously emitted synthetic field name, so consumers of the emitted metadata for root models will see different name and alias values (#3897)generate_dynamic_models runtime helper now includes specialized RootModel type-alias classes that are assigned at the top level of the generated code, whereas it previously omitted any class whose defining module was not the generated module, so existing callers receive additional entries in the returned mapping while genuine imported dependencies remain excluded (#3904)<!-- Release notes generated using configuration in .github/release.yml at main -->
Full Changelog: https://github.com/datamodel-code-generator/datamodel-code-generator/compare/0.76.2...0.77.0
These corrections change generated output or existing configuration behavior for the affected cases. Regenerate and review affected models before upgr
These corrections change generated output or existing configuration behavior for the affected cases. Regenerate and review affected models before upgrading snapshots or downstream integrations.
bytes and fixed defaults become Python bytes using Avro's code-point mapping, including named fixed types. Review constructor requirements and default values. This release does not yet recursively decode nested bytes defaults. (#3842)Query or Mutation are no longer excluded solely by name. References to omitted operation roots become Any instead of unresolved class names. Review imports of previously emitted root classes and affected annotations. (#3842)None alongside UnsetType, and boolean enum values use supported non-literal types rather than boolean Literal annotations. TypedDict extra-item types now bring their required imports. Review generated annotations, default factories, and snapshots. (#3840)other.json#name resolves a matching anchor within that schema resource before falling back to the legacy /name pointer. Schemas that relied on the old pointer interpretation when an anchor also exists can resolve to a different definition. (#3838)pyproject.toml resolve from the configuration file's directory. This applies to input, output, custom headers/templates, comparison output, model metadata, local HTTP references, and lockfiles, including batch jobs. When invoking from another directory, adjust relative values or use absolute paths if you previously relied on the working directory. Explicit CLI paths retain their command-line interpretation. (#3845)use-annotated = false is respected. Implicit field constraints follow the final annotation setting. Review output if CLI, presets, and pyproject.toml previously supplied conflicting options. (#3845)Error diagnostics rather than leaking the previous lower-level exceptions. CLI configuration validation and input-decoding failures report concise errors. Update exception handlers or exact-error assertions where applicable. (#3838, #3842, #3845):80 or :443 from an omitted port. (#3844)Full Changelog: https://github.com/datamodel-code-generator/datamodel-code-generator/compare/0.76.1...0.76.2
Parser source loading, run state, output-model capabilities, field-name policies, and input-model transport have been separated to clarify internal ow
x-enum-descriptions now accepts null entries, allowing schemas with missing individual enum descriptions to generate successfully. (#3835)Full Changelog: https://github.com/datamodel-code-generator/datamodel-code-generator/compare/0.76.0...0.76.1
`--list-deprecations` output changed. Table and Markdown output add Status and rename the Warning since heading to Since. Table lines no longer retain…
propertyNames. When additionalProperties specifies a value schema, its generated dictionary key type now includes supported string-key constraints from propertyNames, instead of always using plain str. Regenerated annotations and imports change, and keys that violate those constraints can fail validation. Review affected extra-property inputs and generated-code snapshots. (#3794)--list-deprecations output changed. Table and Markdown output add Status and rename the Warning since heading to Since. Table lines no longer retain trailing padding. JSON adds status while retaining the existing warning_since key. Update scripts that depend on exact columns, whitespace, or JSON field sets. (#3810)# Before (table)
ID Kind Target Warning since Removal Replacement
# After (table)
ID Status Kind Target Since Removal Replacement
DefaultValueTypeWarning; the existing generated default stays unchanged when Decimal deserialization is disabled. Use --deserialize-default-values decimal to generate compatible Decimal defaults, or account for this warning if your application promotes warnings to errors. The new dated standard-*-20260826 and practical-*-20260826 presets enable Decimal and enum default deserialization; existing *-20260619 presets remain available. (#3792, #3811)--set-default-enum-member is registered as a scheduled deprecation. It still works and does not emit a runtime deprecation warning in this release. Prefer --deserialize-default-values enum; no removal version is set. (#3810, #3811)Full Changelog: https://github.com/datamodel-code-generator/datamodel-code-generator/compare/0.75.1...0.76.0
Update CHANGELOG for 0.75.0 by @dcg-generated-docs[bot] in https://github.com/koxudaxi/datamodel-code-generator/pull/3787
Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.75.0...0.75.1
minProperties/maxProperties now generate runtime validators - When using the experimental --generate-schema-validators option, minProperties/maxProper
--generate-schema-validators option, minProperties/maxProperties constraints on named object models are now emitted as Pydantic v2 model validators. Previously these constraints were ignored. Data that omits or exceeds the allowed property count will now be rejected at validation time, and generated models gain a new __json_schema_property_count_rule__ class variable (#3780)_JsonSchemaRuntimeValidationBase is now split: the core helper is renamed to _JsonSchemaRuntimeValidationBaseCore and a new _JsonSchemaRuntimeValidationBase subclass is inserted. Code that references the generated helper class name by hand will need to be updated (#3780)# Before (--generate-schema-validators)
class _JsonSchemaRuntimeValidationBase(BaseModel):
__json_schema_conditional_required__: ClassVar[tuple[Any, ...]] = ()
...
class ApiConditionalEnvelopeRequestModel(_JsonSchemaRuntimeValidationBase):
__json_schema_conditional_required__: ClassVar[tuple[Any, ...]] = (...)
# After
class _JsonSchemaRuntimeValidationBaseCore(BaseModel):
__json_schema_conditional_required__: ClassVar[tuple[Any, ...]] = ()
...
class _JsonSchemaRuntimeValidationBase(_JsonSchemaRuntimeValidationBaseCore):
__json_schema_property_count_rule__: ClassVar[tuple[Any, ...]] = ()
...
class ApiConditionalEnvelopeRequestModel(_JsonSchemaRuntimeValidationBase):
__json_schema_property_count_rule__: ClassVar[tuple[Any, ...]] = (2, 2)
__json_schema_conditional_required__: ClassVar[tuple[Any, ...]] = (...)
Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.74.0...0.75.0
Non-finite float values now render as structural float(...) expressions - Generated code for non-finite floats (inf, -inf, nan) from Protocol Buffers,
float(...) expressions - Generated code for non-finite floats (inf, -inf, nan) from Protocol Buffers, XML Schema, and AsyncAPI-embedded schemas — as field defaults, constraint bounds, list items, and enum values — now renders inline as float('inf'), float('-inf'), and float('nan') instead of emitting bare inf/nan literals with an injected from math import inf, nan header. Users relying on the previous output (e.g. snapshot/golden tests, or importing inf/nan from the generated module) will see different generated code (#3770)# Before
from math import inf
class Model(BaseModel):
value: float | None = inf
# After
class Model(BaseModel):
value: float | None = float('inf')
Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.73.0...0.74.0
Additional imports are now validated as Python import paths - Values passed via --additional-imports, the Python config API (GenerateConfig, JSONSchem
--additional-imports, the Python config API (GenerateConfig, JSONSchemaParserConfig, etc.), or --extra-template-data must now be dotted sequences of Python identifiers. Previously any value was accepted and split on commas without validation; now inputs that are not valid import paths (e.g. containing newlines, semicolons, or non-identifier syntax) raise an Error and abort generation instead of being emitted into the generated output. Valid dotted paths (optionally whitespace-padded) continue to work unchanged. (#3763)additional_imports must be a Python import path composed of identifiers: 'collections.deque\nINJECTION_MARKER = 1'
--extra-template-data now raise an error for built-in templates - When rendering a built-in (project-owned) template, supplying any generator-reserved key through --extra-template-data (or the extra_template_data API argument) now raises an Error and aborts generation instead of injecting the value. The reserved keys are class_body_lines, config_items, schema_runtime_validation, schema_runtime_validation_base_class_name, schema_runtime_validation_use_base, sequence_base_class, sequence_item_type, sequence_slice_type, _safe_config_items, typed_dict_kwargs, and typed_dict_kwargs_suffix. To inject raw code via these keys you must now use a custom root template through --custom-template-dir. (#3765)extra_template_data validation - extra_template_data that is not a dictionary, contains non-string keys, or contains duplicate (normalized) keys now raises an Error rather than being silently accepted. (#3765)extra_template_data values as non-executing literals - For built-in templates, user-supplied values that were previously emitted as raw Python source are now serialized as quoted, non-executing literals. This affects GraphQL scalar py_type, TypedDict additionalPropertiesType, ConfigDict values, msgspec base_class_kwargs, and comments. Only bare or dotted identifiers (e.g. datetime.date) are still emitted unquoted; more complex expressions become string literals. For example, a scalar py_type supplied as a type expression is now rendered as:Evil = TypeAliasType("Evil", "__import__('os').system('id') or str")
Trusted custom root templates (--custom-template-dir providing the root template) keep the previous unrestricted raw behavior. (#3765)
template_file_path.is_absolute() to _uses_custom_root_template. A --custom-template-dir that only supplies include/partial templates (not the model's root template) no longer opts the built-in root into the unrestricted raw-context path; its extra_template_data is now treated with the hardened built-in rules (and reserved keys raise an error). (#3765)Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.72.4...0.73.0
Update CHANGELOG for 0.72.3 by @dcg-generated-docs[bot] in #3724
Full Changelog: 0.72.3...0.72.4
Update CHANGELOG for 0.72.2 by @dcg-generated-docs[bot] in https://github.com/koxudaxi/datamodel-code-generator/pull/3715
Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.72.2...0.72.3
Bump aiohttp from 3.13.3 to 3.14.3 by @dependabot[bot] in https://github.com/koxudaxi/datamodel-code-generator/pull/3701
Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.72.1...0.72.2
Add TypedDict total=False option by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/3689
Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.72.0...0.72.1
Deprecated decorator detection now requires an exact name match - The check that decides whether a @deprecated class decorator is already present chan…
{}) default whose type is a nested Struct reference now renders a conversion factory instead of a plain dict factory, changing the runtime default from an empty dict to an actual model instance. No CLI flag is required to trigger this. Regenerating existing schemas that have empty-object defaults for nested Struct fields will produce different output and different default values (#3668)# Before
nested: Nested | UnsetType = field(default_factory=dict)
# After
nested: Nested | UnsetType = field(
default_factory=lambda: convert({}, type=Nested)
)
--use-default-factory-for-optional-nested-models, optional nested Pydantic dataclass fields now emit Field(default_factory=<Nested>) where they previously did not, because the field now resolves Pydantic dataclass references. Output for these fields changes on regeneration when that flag is enabled (#3668)# After (with --use-default-factory-for-optional-nested-models)
nested: Nested | None = Field(default_factory=Nested)
dict), so regenerating existing schemas can produce different output. The constructor form is only used when every required argument of the nested model is satisfied and the mapping is not recursive; otherwise the previous dict-literal default is preserved. (#3669)# Before
@dataclass
class Model:
inner: Inner | None = field(default_factory=lambda: {'v': float('inf')})
# After
@dataclass
class Model:
inner: Inner | None = field(default_factory=lambda: Inner(v=float('inf')))
@deprecated class decorator is already present changed from a text prefix match (decorator.startswith("@deprecated")) to an exact unqualified-name match (is_named_python_decorator(decorator, "deprecated")). If a schema marks a class as deprecated and you also apply a custom class decorator that merely shares the deprecated prefix (e.g. @deprecated_custom), the generator previously treated it as the deprecated decorator and skipped emitting one; it now recognizes them as distinct and adds the real @deprecated('... is deprecated.') decorator along with the typing_extensions.deprecated import. Generated output for these cases changes accordingly. Idempotency for the standard @deprecated('...') decorator is unchanged. (#3685)# Input: deprecated class + custom decorator "@deprecated_custom"
# Before
@deprecated_custom
@dataclass
class LegacyUser:
...
# After
@deprecated_custom
@deprecated('LegacyUser is deprecated.')
@dataclass
class LegacyUser:
...
Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.71.0...0.72.0
New warning emitted by default for unresolved local $ref pointers - By default, an unresolved local $ref JSON pointer now emits a new DanglingRefWarni
$ref pointers - By default, an unresolved local $ref JSON pointer now emits a new DanglingRefWarning and generates a fallback Any model. Previously such refs resolved to a silent fallback, and some cases (e.g., out-of-range JSON pointer array indices) raised a hard error. Schemas that previously generated cleanly can now produce warnings, which breaks workflows that treat warnings as errors (e.g., python -W error). Use --strict-refs to fail on unresolved pointers instead, or --disable-warnings to silence them (#3639)$ref to a non-dict file now raises InvalidFileFormatError instead of TypeError - Resolving a $ref to a JSON/YAML file whose top-level value is not a mapping (e.g., a list) now raises datamodel_code_generator.InvalidFileFormatError (a subclass of Error/Exception) rather than the built-in TypeError. Programmatic callers that catch TypeError around generate() must catch InvalidFileFormatError (or Error) instead (#3639)Invalid file format for <type> at <source>: ..., and the missing-file message changed from File not found to File not found: <path>. Tooling that matches on the exact previous strings needs updating (#3639)generate() Python API and the CLI. Invocations that previously succeeded now raise an Error (CLI exits with an error code) in these cases: the output path resolves to an existing input file, the --emit-model-metadata path resolves to an existing input file, or the output and model-metadata paths resolve to the same file. Symlinks and hardlinks are resolved before the comparison. Workflows that intentionally wrote output over an input path, or that pointed the model-metadata artifact at the same path as the output, will now fail with one of:Output path must not overwrite an input path: <path>
Model metadata path must not overwrite an input path: <path>
Output and model metadata paths must be different: <path>
(#3647)
Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.70.0...0.71.0
One column per quarter.