Repository navigation
Releases
Releases · datamodel-code-generator/datamodel-code-generator
0.102.0
Breaking Changes
Code Generation Changes
- A package class beside a same-named submodule no longer binds the class name through the import of the submodule's models - In dataclass, msgspec and TypedDict output the modules that use a model of the submodule now import it from the submodule, so they no longer bind the class name of the package (from .pkg import Warn) through that import. They read the class through it, and resolving their annotations (type hints, msgspec decoding) failed. (#7444)
- A Pydantic package class beside a same-named submodule is refused where only the root package loads the submodule - Where a package's init.py defines a class named like one of its submodules and imports from the root package (from .. import common), the root's own import of the submodule (from .pkg import Warn) was taken as a load of the init.py. The root runs first, so that import ran after the class was defined and bound the class, and the root's model of the submodule (Warn.Detail) read the class. Where the classes evaluate their annotations as they are defined (Pydantic, which builds a class as it is defined, or output without from future import annotations) the root failed at import with AttributeError, so no module of the package imported: those runs now refuse the class as for other packages that do not load the submodule, and name --rename-submodules-hidden-by-classes. Dataclasses, TypedDict and msgspec with deferred annotations, where every module imported, keep their output; the stored outputs of the root-imported and cyclic layouts pin that. (#7444)
- --recommend-options takes the target Python version from requires-python - Experimental:
cli-option.recommend-options. When no option, pyproject.toml key or preset sets the target Python version, --recommend-options takes the lower bound of requires-python in the project's pyproject.toml (>=3.12, ~=3.12, ==3.12.*, with upper bounds or exclusions beside it), clamped to the supported targets and to the lowest one a client or server target supports, starts from that preset, and adds --target-python-version to the command and the pyproject.toml block with a note naming the source; other forms keep the note that the default is assumed. Generation never reads requires-python. (#7493)
API/CLI Changes
- Public names for --apply-default-values-to-true-properties - The option adds its config field; nothing is removed or changed. (#7455)
- Public names for --distribute-allof-over-object-branches - The option adds its config field; nothing is removed or changed. (#7445)
- A store operation that names the classes of the additional properties - GraphBuilder.name_additional_properties_classes() (and GenerationStore.name_additional_properties_classes()) gives a model the type of its additional properties with the classes they name, which replace those recorded; nothing is removed or changed. (#7473)
- A store operation that drops one entry of a field's extras - GraphBuilder.drop_field_extra() (and GenerationStore.drop_field_extra()) drops one key of a field's extras in place, as drop_field_discriminator() does for the discriminator; nothing is removed or changed. (#7494)
- Store signatures name the graph classes, and its operations lose their deprecation markers - GenerationStore.seal_facts, FinalFacts and the union keyword methods of DataTypeManager name DataType, DataModel and Reference where they named the read-only views of model/_views.py, which are gone. The operations of GenerationStore lose their Daniel Edeling (@deprecated)(category=None) markers, which warned no caller at run time, and GraphBuilder(store) takes no token; heki keeps the package's own calls of the operations inside the generation store. (#7484)
- Public names for --write-pyproject-config - The option adds a row to the option table and the fast path of --generate-prompt steps aside for it; nothing is removed or changed. (#7495)
New Warnings
- A pydantic dataclass that redeclares an inherited field without a pattern Python's re rejects warns - Where a pydantic_v2.dataclass selects python-re for a look-around pattern of a base and another base has a pattern Python's re rejects, such as \p{L}, the dataclass redeclares that field of a base of its module without the pattern and warns that the field is generated without the constraint. Such a module failed at import before. (#7489)
- Warn where an allOf over a union drops what the union checks - Without --distribute-allof-over-unions an allOf member naming an allOf over a union warns that the model checks none of its branches (#5305), and without --distribute-allof-over-object-branches so does a branch of an allOf's union that is itself a union or an alias (#6869). The generated output does not change. (#7445)
New Options
- New option
--apply-default-values-to-true-properties(--no-apply-default-values-to-true-properties): Give a property whose schema istruethe default that --default-values gives it, in the class that declares it and in a child that restates an inherited property astrue(name: str | None = 'rex'forDog.name); without it such a property takes no default, as in 0.100.0 (#7455) - New option
--distribute-allof-over-object-branches(--no-distribute-allof-over-object-branches): Give anallOfover ananyOforoneOfone union variant per object branch, also where a branch is itself ananyOforoneOf(named by a$refor written there), anallOfor a$refwith sibling keywords over one, or an alias of an object schema, and have each variant require every name a part of theallOfrequires, typed as the field it takes from its branch (allOf: [Pet, {required: [name]}] with Pet a oneOf of Cat and Dog that declare name optional). Without it such a branch gives a variant of the other members alone, or none, and warns, and a variant takes the name as its bases hold it, optional or Any, as in 0.100.0 (#7445) - New option
--write-pyproject-config: Write the pyproject.toml table that --recommend-options or --generate-pyproject-config prints into the project's pyproject.toml, setting only the keys it adds or changes, and print what was written (experimental). (#7495)
New Dated Presets
standard-py3XX-20261124andpractical-py3XX-20261124: they keep the 20261123 options and add allOf distributed over object branches (--distribute-allof-over-object-branches): Give an allOf over an anyOf or oneOf one union variant per object branch, also where a branch is itself an anyOf or oneOf, named by a $ref or written there, and have each variant declare every name a part of the allOf requires as a required field, typed as its branch declares it, so a variant needs such a name, and output types that validate values reject one its branch rejects; Default values of true properties (--apply-default-values-to-true-properties): Under --default-values, give a property whose schema is true the default its Class.field or field key gives it, also where a child restates an inherited property as true, as a property whose schema is {} takes it. (#7455, #7445)
Experimental Features
--write-pyproject-config, its report, and the written key of the recommend-options and pyproject-config JSON payloadsis experimental. Writing the pyproject.toml table is experimental; the file it chooses, the edits it refuses, and its report may change.
Changes That Need No Action
- A package class beside a same-named submodule that its init.py loads first no longer hides the submodule's models - Where a package's init.py loads a submodule while its imports run (--all-exports-scope re-exports it, or a module it imports loads it) and also defines a class of the submodule's name, the modules that use a model of the submodule now import it from the submodule, as the output already did where the init.py names a type of the submodule. They read the class through the package: a Pydantic module failed at import with AttributeError, and the other backends failed where the annotations are resolved (type hints, msgspec decoding). They no longer bind the class name through that import. (#7444)
- Select python-re in a pydantic dataclass that builds a base's lookaround - A pydantic_v2.dataclass whose config does not select python-re, such as one with its own config under --extra-fields, or one that takes the config of another first base, now selects it when a base it inherits has a pattern only Python's re reads, keeping every item of a config it took from a base, such as extra='forbid'. Such a module failed at import with a SchemaError. Where a base of its module also has a pattern Python's re rejects, such as \p{L}, the dataclass redeclares the inherited field without it and warns, and the base keeps its output. (#7489, #7452)
- Read a boolean parameter schema as Any - An OpenAPI parameter or response header whose schema is true or false no longer stops the paths and parameters scopes with a validation error; the parameter is typed Any, like an empty schema. (#7483, #7454)
- Flatten msgspec bases under --reuse-model by the models reuse merges - With --output-model-type msgspec.Struct, a model with two generated bases whose layouts still conflict once every module is processed stopped with incompatible layouts, for instance under --reuse-model when one base has the field names of another base's ancestor but a different type, default, description or constraint, or when a discriminator field of a base is not tagged. It declares the fields of its bases itself, as it does without --reuse-model. (#7446)
- Show the warnings of msgspec runs that now generate - A msgspec run that stopped with incompatible layouts under --reuse-model now generates, so it shows the warnings its models raise, such as that msgspec cannot decode a union whose Struct types are not all tagged; a directory input shows those of every module, and the single-file attempt before its modular output now stops on the mod...
0.101.0
Breaking Changes
Code Generation Changes
- A named allOf whose merged root is an enum class is written as that enum - A named allOf of an untyped constraint $ref and a typed enum member, such as allOf: [{$ref: ThreeLetters}, {type: string, enum: [GBP, JPY]}], stopped with "a $ref chain that loops back" for Pydantic and msgspec output, and under --collapse-root-models and the presets wrote a field or a root model that accepted no value of the enum; it is now written as its enum class, which accepts the values of the enum. Standard dataclasses keep Any without --intersect-merged-allof-members. (#7399, #7314)
- AsyncAPI handshake parameters take the default of their model field - Experimental:
cli-option.generate-client. A WebSocket handshake query or header parameter of a generated AsyncAPI client took the default at the end of its whole$refchain, while the models take a referenced default one reference deep. The parameter now takes the default of its model field, so both agree: two references deep, or under --collapse-root-models or --ignore-ref-siblings-by-schema-version, the argument has no default where the model field has none. (#7394, #6975) - A reference to a component Multi Format Schema Object names the schema it holds - Experimental:
input-format.asyncapi. A payload, headers or component $ref to a Multi Format Schema Object in components.schemas, also through component aliases, is typed by the JSON Schema the object holds: the RootModel[Any] read from the wrapper (NoteModel) is gone, the payload, headers and alias classes are root models over the held model, and the held model takes the component's name where the wrapper took it before (Tag1 is Tag). (#7389, #6936) - A directory input with hidden files that are not text generates the same models - The stored outputs of the directory inputs with hidden files; the models are the same as without those files. (#7398, #7128)
- A default Pydantic validates holds the values strict types read from its JSON text - With --strict-types bytes, datetime, date, time or a strict Decimal, a field whose type names a model and whose default holds the text or number of a JSON document was written Field(, validate_default=True). Pydantic validates that default as Python input, where strict mode refuses the JSON value, so every instance that left the field out failed. The default is now written as the values Pydantic reads from the JSON default: bytes for a strict bytes, datetime_module.date.fromisoformat(...) and the like for an RFC 3339 date, time or datetime, Decimal(...) for a strict Decimal, through root models, objects, lists, sets, tuples and mappings. validate_default stays, so Pydantic still validates the value; text that is no RFC 3339 date or time, a value under a union of several types, bytes under a configured base class the generator cannot read and an object key the field is not written to read are left as written, so Pydantic reports them as before. Only outputs that failed at every construction without the field change; model_json_schema() shows the default as Pydantic serializes the converted value. (#7420, #7380)
- Generated dataclass clients decode boolean and number enums inside a union - Experimental:
cli-option.generate-client. In a union, the dataclasses.dataclass client codec read an enum's JSON kinds from its string and integer values alone, so a boolean or float enum decoded to the raw value and accepted values outside the enum. It now reads the kind of every value:falseofenum: [false]decodes to the member andtrueis refused, as in Pydantic clients. A union of an open number or boolean enum and a plain number or boolean is now refused at generation, as open string and integer enums already were. (#7394, #7014) - Client field arguments keep the None of a nullable field - Experimental:
cli-option.generate-client. Field arguments (--client-body-arguments both) and the other client and server plans now type a field with the None its model accepts where the schema admits null, also when the null sits on the field rather than in its type: a nullable map withpatternPropertiesorpropertyNames, and OpenAPI 3.0nullable: truereferences, maps and arrays.labels: {type: [object, 'null'], patternProperties: ...}now giveslabels: dict[str, str] | Nonewhere it gavedict[str, str]. A union of several part or payload types writes None once, last. (#7394, #7348) - Helper selectors read the null a field's own type accepts beside nullable: false - Experimental:
cli-option.generate-client. A helper selector of a generated client read no null for a field declarednullable: falsewhose own type accepts null (allOf: [{$ref: MaybeText}], MaybeText nullable), except through a type alias, so the result depended on --use-type-alias. The models accept null in both forms, so the selector now reads it in both, and a root model's null counts like an alias's: a cursor over such a field needs a{kind: null}end condition with and without --use-type-alias. (#7394, #7115) - Generated dataclass and TypedDict clients read a nullable discriminated union by its own discriminator - Experimental:
cli-option.generate-client. A property, array item or map value typed as a discriminated union or null (anyOf: [{$ref: D}, {type: 'null'}]withDaoneOfwith adiscriminator) stopped generation of dataclasses.dataclass and typing.TypedDict clients with 'needs a declared discriminator'. The codec now reads each model by the discriminator of the union it comes from, as it already did forDalone; several such unions join their declarations when they share the property. (#7394, #7303) - --input-model keeps the Python type of an unserializable field in every held class - A field JSON Schema cannot express, such as a Callable, kept its Python type (callback: Callable[[int], int]) only in a Pydantic model; in a dataclass, TypedDict, Pydantic dataclass or RootModel that the model holds it became str, which refused every valid value, and with --field-include-all-keys the id() of a schema reached the output as x-python-unserializable, a different number on every run. The field now keeps its type, found by the class the schema generation recorded for the definition, so two same-named classes keep their own fields. Class and field names stay. (#7433, #6885)
- --input-model reuse imports the class a definition comes from - With
--input-model-ref-strategy reuse-allorreuse-foreign, a field whose type is one class (item: Itemofshop.Item) was typed by another class of that name that the model's fields also name, such astype[legacy.Item]or a nestedLegacy.Item(item: legacy.Item), which refused every valid value. It is now typed by its own class (from shop import Item), also for a dataclass or TypedDict input and for the fields of a parent model; this is the output of 0.75.0. Every imported name keeps the class it named in 0.100.0 (hereItemisshop.ItemandItem1islegacy.Item), sofrom <generated module> import Itemis unchanged. Class and field names stay; schema-valid documents that were refused now validate. Code that passed an object of the other class (alegacy.Item) to such a field, against the schema, is now refused. (#7390, #6883) - A map key names the root type of its RootModel members - A map key that is a union (propertyNames anyOf or oneOf) whose members are all RootModels, a one-member wrapper of a RootModel included, was written with the RootModel class, which Pydantic cannot use as a dict key, so every key the union accepts raised TypeError. The members are now written as their root types, as a key that names the RootModel alone is; the class itself stays. A union key with a member that is no RootModel (a str, a constr call, an enum, Any) keeps the RootModel class unless --use-root-types-for-mixed-union-map-keys is set. (#7434)
- Discriminated variants whose tag also admits null - A union that writes discriminator= over a variant whose tag field admits None is written without it, as Pydantic reads no such tag and the module failed to import (#7102); a null in the variant's enum is no tag, so it takes the enum's values instead of its schema name or, inline, the internal path marker (#7357), and an inline msgspec variant of several values takes them in its tag field and stays untagged. Variant classes keep their names, fields and the null their schema admits. (#7405, #7102, #7357)
API/CLI Changes
- Public names for --read-allof-parents-as-their-models and --read-set-item-fields-in-class-order - The options add their config fields; nothing is removed or changed. (#7400)
- Public name of the AsyncAPI JSON Schema media types lists application/schema - parser.asyncapi.JSON_SCHEMA_FORMATS gains the bare application/schema media type; the models are written as before. (#7389, #6937)
- A check or JSON run reads a custom formatter's relative paths where the output lies - --check and --output-format json build the custom formatter in the directory of the real output, as the run that writes does, so a relative path of --custom-formatters-kwargs is found; they built it in a staging directory, where it was not. (#7398, #6945)
- A Pydantic v2 model warns for the config keys it leaves out of model_config - A key of the config entry of --extra-template-data that pydantic_v2.BaseModel does not write, such as validate_assignment, was dropped without a message; the generation now warns and names the keys the model writes. The output is unchanged. (#7398, #7001)
- A directory input skips hidden files that are not text - A hidden file of a directory input (a name or a directory below the input that starts with a dot) whose first bytes hold a NUL byte, such as the .DS_Store file Finder writes, is no longer read as a schema, so generation no longer stops with Invalid file format; a hidden file that reads as text stays an input. (#7398, #7128)
- A stdout run with a repaired d...
0.100.0
Breaking Changes
Code Generation Changes
- Generated clients and servers now include None in container items built from several schemas - This affects the experimental
--generate-clientand--generate-serveroptions. Argument and parameter types for an array or map whose items are several schemas now include None inside the container when the item union admits null. This coversprefixItems, the OpenAPI 3.0 items-array form such asitems: [{type: string}, {type: integer, nullable: true}], and msgspec pattern maps. It matches what the generated models have written since 0.89.0. For example,prefixItems: [{type: string}, {type: 'null'}]withitems: {type: string}now gives the client method argument, the FastAPI endpoint parameter and the generated service Protocol parameter the typelist[str | None], where it waslist[str]. Service implementations written against the old, narrower parameter types may no longer match the regenerated Protocol under a type checker, and code that reads these parameters must handle None items. The wire format is unchanged (#7305)
What's Changed
- Name the cells of change records and judge differing cells by them by Koudai Aono (@koxudaxi) in #7228
- Hash outside outputs and normalise version lines in compared outcomes by Koudai Aono (@koxudaxi) in #7229
- Stamp the upgrade guide entries of 0.99.0 by Koudai Aono (@koxudaxi) in #7233
- Decide each remaining no-cover site of the package by Koudai Aono (@koxudaxi) in #7224
- Pick the catalog cells that run a change's lines by Koudai Aono (@koxudaxi) in #7236
- Drop the expected-path arguments of the rest of the OpenAPI tests by Koudai Aono (@koxudaxi) in #7237
- Pin the public API in one record written from source by Koudai Aono (@koxudaxi) in #7235
- Drop the expected-path arguments of the rest of the JSON Schema tests by Koudai Aono (@koxudaxi) in #7241
- Judge the gate's differing cells by the change records by Koudai Aono (@koxudaxi) in #7242
- Fix the 3.13 rows and the gate's memory cap below the worker by Koudai Aono (@koxudaxi) in #7244
- Move the names other modules import from the root and main to leaves by Koudai Aono (@koxudaxi) in #7245
- Fail the harness labels the gate refuses in the records check by Koudai Aono (@koxudaxi) in #7248
- Drop the expected-path arguments of the CLI, API and parser leftovers by Koudai Aono (@koxudaxi) in #7247
- Read the uuid6, uuid7 and uuid8 formats under an option by Koudai Aono (@koxudaxi) in #7246
- Describe the record cells, categories and verdicts in the guide by Koudai Aono (@koxudaxi) in #7252
- Judge the records covering one cell together, by kind and by line by Koudai Aono (@koxudaxi) in #7254
- Approve the baseline of the decision-home caller guard by Koudai Aono (@koxudaxi) in #7260
- Guard the callers of decision homes against their records by Koudai Aono (@koxudaxi) in #7256
- Drop the expected-path arguments of directory and multi-output tests by Koudai Aono (@koxudaxi) in #7257
- Name the files in protoc messages without the run's temporary directory by Koudai Aono (@koxudaxi) in #7251
- Move the generation core out of the package root by Koudai Aono (@koxudaxi) in #7259
- Declare the protoc message change of #7251 by Koudai Aono (@koxudaxi) in #7262
- Add name, suffix and stdout arguments to the stored-output helpers by Koudai Aono (@koxudaxi) in #7263
- Refuse imports of the package root and main inside the package by Koudai Aono (@koxudaxi) in #7264
- Hoist the local imports of modules that are already loaded by Koudai Aono (@koxudaxi) in #7265
- Drop the inferred expected-path arguments of the JSON Schema tests by Koudai Aono (@koxudaxi) in #7267
- Drop the expected-path arguments of the scripts, model and codec tests by Koudai Aono (@koxudaxi) in #7266
- Judge changed outputs by cell in the ratchets job by Koudai Aono (@koxudaxi) in #7255
- Drop the expected-path arguments of the general, kr and watch tests by Koudai Aono (@koxudaxi) in #7268
- Apply the decided lint rules and make private boolean flags keyword-only by Koudai Aono (@koxudaxi) in #7270
- Drop the expected-path arguments of the OpenAPI tests by Koudai Aono (@koxudaxi) in #7269
- Drop the expected-path arguments of more JSON Schema tests by Koudai Aono (@koxudaxi) in #7271
- Drop the expected-path arguments of the parser and dynamic model tests by Koudai Aono (@koxudaxi) in #7272
- Drop the expected paths of the FastAPI API, scope and checkout tests by Koudai Aono (@koxudaxi) in #7280
- Drop the expected paths of the client render tests by Koudai Aono (@koxudaxi) in #7283
- Drop the expected paths of the other client generation tests by Koudai Aono (@koxudaxi) in #7284
- Drop the expected-path arguments of the avro, payload and HTTP tests by Koudai Aono (@koxudaxi) in #7282
- Approve the baseline of the builder-home guard by Koudai Aono (@koxudaxi) in #7295
- Record the builder homes of L1 and guard their bypasses by Koudai Aono (@koxudaxi) in #7294
- Drop the expected-path arguments of the protobuf tests by Koudai Aono (@koxudaxi) in #7290
- Record the placement table and check its passes by Koudai Aono (@koxudaxi) in #7304
- Keep the None of a container's item union in client and server types by Koudai Aono (@koxudaxi) in #7305
- Approve the entries the embedded-source scan restores by Koudai Aono (@koxudaxi) in #7306
- Drop the expected paths of the client runtime and typing tests by Koudai Aono (@koxudaxi) in #7302
- Test typing imports and union tags through the public surface by Koudai Aono (@koxudaxi) in #7307
- Describe clients and servers in the agent skill and the overview by Koudai Aono (@koxudaxi) in #7299
- Move older presets to a history page and update the site description by Koudai Aono (@koxudaxi) in #7300
- Break the import cycle between reference and the model base by Koudai Aono (@koxudaxi) in #7310
- Drop the expected paths of the model, codec and script test leftovers by Koudai Aono (@koxudaxi) in #7312
- Test or prove four no-cover guards outside the JSON Schema parser by Koudai Aono (@koxudaxi) in #7317
- Drop the expected paths of the JSON Schema test leftovers by Koudai Aono (@koxudaxi) in #7319
- Describe planned changes in comments instead of internal plan ids by Koudai Aono (@koxudaxi) in #7321
- Drop the private re-exports of the parser base and their dead branches by Koudai Aono (@koxudaxi) in #7322
- Approve the heki baseline of today's findings by Koudai Aono (@koxudaxi) in #7328
- cfeat(msgspec): add --merge-msgspec-str-like-union-members by Mark Paronyan (@markparonyan) in #6549
- Test or prove seven no-cover gu...
0.99.0
Breaking Changes
Code Generation Changes
- Generated AsyncAPI clients now follow references into other loaded documents (experimental
--generate-client) - With--generate-clientand AsyncAPI input, the generator now reads a channel, operation, message, trait, binding, parameter, reply, server or security scheme declared in another loaded document at the place where the parser resolves its$ref. Channels that used to be skipped with a "references another document" warning are now generated as client helpers. An AsyncAPI 3 operation in another loaded document no longer stops the whole run with "operation ... references another document". When you regenerate such a client, it gains these helpers, and theSOCKET_N,OPERATION_Nandcodec_Nconstants in the generatedprotocols/_plans.py,_operations.pyand_generated/model_bindings.pyare renumbered. Channels that are still left out may give a different reason in their skip warning. References into a document the run did not load, and references that loop, still leave the channel out (#7137) - Channel servers and security requirements are now matched by where their reference leads (experimental
--generate-client) - In AsyncAPI input, a channelserversentry or an operation or server security requirement whose$refdoes not point straight at an entry of the root document'sserversorcomponents/securitySchemesnow names the root entry that leads to the same object. Before, such an entry was ignored or the channel was skipped. So a generated channel can now get extra servers or security requirements it did not have before, or be generated where it used to be skipped (#7137) - Constrained union members are written as
Annotatedunder--use-annotated- In Pydantic v2 output (pydantic_v2.BaseModel,pydantic_v2.dataclass) with--use-annotated, a union member that has its own constraints used to be written as acon*()call. This covers members in a field, a list item, a dict value or aRootModelroot and generic parameter, for example thestringoftype: [integer, string]with apattern, or theintegerof a type list with aminimum. Such a member is now written asAnnotated[<type>, Field(...)], and aDecimalmultipleOfbecomesMultipleOf(...). For example,code: int | constr(pattern=r'^[0-9]+$')becomescode: int | Annotated[str, Field(pattern=r'^[0-9]+$')], andRootModel[conint(ge=2) | constr(max_length=2)]becomesRootModel[Annotated[int, Field(ge=2)] | Annotated[str, Field(max_length=2)]]. The generated imports change too:constr,conint,confloat,condecimalandconbytesare no longer imported frompydanticfor these members, whileAnnotated,Fieldandannotated_types.MultipleOfare added where needed. This also changes the output of theread-kubernetes-extensionspresets. The models accept and reject the same values, but the generated code text and imports are different. Output without--use-annotatedand with--field-constraintsalone does not change (#7117) - Generated clients now bind the keys of a TypedDict whose bases have conflicting orders - With the experimental
--generate-clientoption and--output-model-type typing.TypedDict, a TypedDict whose bases Python cannot order (for exampleE: allOf [C, D]whereC: allOf [A, B]andD: allOf [B, A]) used to get an empty binding. Its codec inmodel_bindings.pywasModel(()), decoded objects held no keys, and a body of it took no field arguments under--client-body-arguments both. Its keys are now bound in the order the models give its bases. The codec lists every field (for exampleModel((Field('b', 'b'), Field('a', 'a'), Field('d', 'd'), Field('c', 'c'), Field('e', 'e')))), decoded objects contain those keys in that order, and the client call that sends such a body now accepts them as field arguments. Generated clients that relied on the old empty binding behave differently (#7150) - AsyncAPI client payloads written as a
$refwith annotation siblings are now typed by the referenced model - This affects the experimental--generate-clientoption with AsyncAPI input. A message payload written as a$refbeside annotations only (such as adescription) is now typed and coded by the model of the schema it names, the same way an OpenAPI body is. Before, it was typed by the payload's own wrapper root model. For example,ChannelPlan[models.FeedTradePayload | models.Quote, Never]becomesChannelPlan[models.Trade | models.Quote, Never]. Code that annotates or handles session messages as the wrapper model must switch to the referenced model (#7163) - AsyncAPI 2 client unions now list
publishmessages beforesubscribemessages - This affects the experimental--generate-clientoption with AsyncAPI 2 input. The operations of a channel are now read in the parser's order,publishthensubscribe, so a stream or channel that carries both has its union written in the opposite order. For example,EventPlan[models.StatusSubscribePayload | models.StatusPublishPayload]becomesEventPlan[models.StatusPublishPayload | models.StatusSubscribePayload](#7163) - Served OpenAPI document of
--generate-server fastapinow resolves references the way the models do (experimental) - The_generated/openapi.jsonthat a generated FastAPI server serves now resolves each$refthrough the$id,$anchorand$dynamicAnchornames the parser registers for the models, and no longer uses its own index. Three kinds of reference used to be kept as written with the warning "The served document keeps ..., which names nothing the generation loaded". They now point to the schema the models use: a plain-name reference to an$anchorinside a namespace of definitions (such as$defs: {v1: {Label: {$anchor: label}}}) now points to/components/schemas/Pet/$defs/v1/Label; a reference through the root$idof a referenced JSON Schema document into that document (such ashttps://example.com/schemas/petfollowed by a pointer to/$defs/Name) is now bundled as a component; and under OpenAPI 3.0, a reference by the$idof a component schema (such ashttps://example.com/owner.jsonwith--no-allow-remote-refs) now resolves to that component. A plain name whose anchor is also declared by aschemabeside a Reference Object (which OpenAPI ignores) now points to the anchored property the models read, not to the ignored schema. The generated models do not change, but regenerating changes the servedopenapi.json, so--checkruns and anything that reads the served document will see different output (#7178) - Served OpenAPI document keeps some pointer references unresolved that it used to bundle (experimental) - With
--generate-server fastapi, two kinds of JSON pointer that the models already treat as dangling references (they fall back toAnywith aDanglingRefWarning) are now also left as written in the served_generated/openapi.json, and each now emits aDocumentationAnnotationWarning: a pointer below the$idof a parameter document that was first loaded through a pointer (such as/properties/size), and a pointer below the$idof a schema written inline inpaths(such as/$defs/Title). The first used to be bundled. The second used to point to the inline schema's own$defsentry. Builds that treat warnings as errors will now fail on these inputs (#7178)
API/CLI Changes
- Removed
create_module_getattrfromdatamodel_code_generator.typesanddatamodel_code_generator.parser.asyncapi- Both modules used to importcreate_module_getattrfromdatamodel_code_generator.utilfor their old lazy__getattr__hooks. That meantfrom datamodel_code_generator.types import create_module_getattr, the same import fromdatamodel_code_generator.parser.asyncapi, and star imports of either module all gave you that name. Those imports are gone because the modules now use the internal_lazy_exportshelper, so code that reached the function through either module getsImportErrororAttributeError. Import it fromdatamodel_code_generator.util, where it is still available. (#7155) - Module
dir()now lists lazily exported names - The package root,types,util,parser.avro,parser.asyncapi,parser.base,parser.jsonschemaand__main__now define__dir__, sodir()now includes lazy names such asStrictTypes,BaseModel,SafeLoader,dataclass_model,msgspec_model,TypedDictModel,Config,generate_dynamic_modelsandload_pyproject_config, which it used to leave out. Anything that walksdir()and reads each attribute, such asinspect.getmembers(),help()and REPL completion, now imports the modules behind those names. For example, it loads the dataclass and msgspec model modules forparser.baseand the protobuf and XML Schema parsers forparser.asyncapi. Also, once a resolver name indatamodel_code_generator.referencehas been read,dir()and__all__now list it once instead of twice. (#7155)
Default Behavior Changes
- AsyncAPI client reads channels by the configured
--schema-version- This affects the experimental--generate-clientoption with AsyncAPI input. Channels are now read by the AsyncAPI version the models are read by:--schema-version 2.0or3.0where it is given, else the document'sasyncapifield. Before, only theasyncapifield was read. A run that passes a--schema-versiondifferent from the document's declared version now reads its channels by that version. This can leave channels out or make the client generation fail, for example a 3.0 document generated with--schema-version 2.0(#7163)
Error Handling Changes
- AsyncAPI client skip warnings change in wording, category and order - This affects the experimental
--generate-clientoption with AsyncAPI input. A message$refthat loops is now read as the message it is written in. Its channel is reported under messages without a payload, ...
0.98.0
Breaking Changes
Error Handling Changes
- Client name collision errors are reported once per name and sorted (experimental
--generate-client) - With the experimental--generate-clientoption, an explicit argument name (parameter_namesor--aliases), an explicit method name (nameof--client-operations) or a channel setting'sresourcethat is taken three or more times is now reported in oneE_NAME_COLLISIONdiagnostic instead of one per repeat. When several names collide, they are listed in sorted order instead of declaration order. Argument collisions now come after all reserved-name and--aliasesdiagnostics of the operation's parameters instead of being mixed in with them, and channel resource collisions come after the refusals of dotted resources. For example,The arguments of GET /items take 'b' twice; ... take 'a' twicebecomes... take 'a' twice; ... take 'b' twice. Tooling that matches the exact text, count or order of these error messages must be updated. Generated code is unchanged (#6987) - Reserved explicit method name taken twice no longer adds a collision error (experimental
--generate-client) - An explicit client method name that is a reserved member name such asclose, given to two operations of one resource, is now reported only as a reserved name. The extraThe resource ... takes the name ... twicecollision error is no longer emitted (#6987) - Generated servers stop validating dropped other members against their additionalProperties type - With the experimental
--generate-server, other members that a model drops by its configuration are no longer checked against the typeadditionalPropertiesgives them. Under--extra-fields ignore, a multipart body whose other members are typed as an object now servesx=abc, where it used to answer 422json_invalid(andmodel_typeordict_typeforx=5). Withpydantic_v2.dataclass, a URL-encoded or multipart body typed byadditionalProperties: {type: integer}now servesx=abc, where it used to answer 422int_parsing. Under--extra-fields forbidsuch members are still refused with 422. Separately, under--extra-fields forbida request that leaves out a query or cookie object but carries other keys is now served withobj=None, where it used to get 422 (#7039) - Omitting a body field the model requires now raises TypeError before any request - This affects the experimental
--generate-clientfeature. With--strip-default-none, calling a generated method without a field the model constructor requires (for examplecreate_pet(id=1)) now raisesTypeError: create_pet() missing required field arguments for application/json: 'tag'before any request is sent. Before, the model raisedDecodeError(reason='unencodable')(#7070) - AsyncAPI messages without their tag, or with a null tag, are refused with different reasons - This affects the experimental
--generate-clientfeature. With--strip-default-none, on a channel routed by an optional tag property, a received message that lacks the property is now refused asmissinginstead ofvalue. A message whose tag is null, which the union decoder used to accept as the first member, is now refused with reasonnull(#7070)
Code Generation Changes
- Generated client and server plans drop other-member entries for objects whose model drops extra members - With the experimental
--generate-clientand--generate-server, form bodies, client form and query object parameters, and multipart bodies typed by a Pydantic model or dataclass now follow the configuration the model applies, bases included. Where that configuration saysextra='forbid'or'ignore', they take no other members.'ignore'includes a class that sets noextra, which is the default. Regenerated code no longer hasadditional=FieldPlan('', 'string')or the matchingreserved_names=(...)in a client's form or query plans,additional=PartPlan('', 'json')and itsparts=in a client's multipart body sent whole, oradditional=JsonPart('', TypeAdapter(object), untyped=True)in a server's_generated/contract.py. A client call option also no longer counts the undeclared names of such an object as written by its pagination. Nothing changes under--extra-fields allow(#7039) - Pydantic dataclass extra-member serialization follows the applied configuration - With the experimental
--generate-clientor--generate-serverand--output-model-type pydantic_v2.dataclass, the client codecextras_serializer, the server responsedump=extras_json(with theprimarystatus it adds) and the copied_runtime/model_codecs/pydantic_extras.py(a server'sshared.pytoo) are now emitted only where the configuration Pydantic applies saysextra='allow'. That is the dataclass's own configuration, or its first base's when it has none. A class written with--class-decoratorsnow counts, so such a dataclass withadditionalProperties: truenow sends and returns its extra members: the client sends{"v":"a","foo":"b"}where it used to send{"v":"a"}. Two kinds of dataclass loseextras_serializeranddump=extras_json: one whose own configuration sets noextra(for example from--allow-population-by-field-name) under a base withadditionalProperties: true, and one whose first base forbids extra members (#7039) - Server form field-name members follow the applied by-name configuration - With the experimental
--generate-server, a form the server reads through its own adapter (multipart, or URL-encoded withpydantic_v2.dataclass) now lists the field-nameFieldPlanentries only where the applied configuration setspopulate_by_nameorvalidate_by_name, with bases merged as Pydantic does. A model that turns it off over a base that sets it, or a dataclass with its own configuration under such a base, no longer lists the field names. A class written with--class-decoratorsnow lists them (#7039) - Schema validators reject a boolean for a numeric const or enum value and a number for a boolean one - With the experimental
--generate-schema-validatorsoption (or--schema-validator-type pydantic-v2), a const or enum that holds a boolean, or a number equal to one (0,1), now gets a check on the raw input. Payloads that Python'sTrue == 1used to let through are now rejected withExpected the JSON type of the schema constant:trueforconst: 1,enum: [1, 2]orenum: [1, "x"], and1forconst: true. The check covers properties, array items, mapping values, referenced Enum classes, the consts of oneOf and anyOf branches, and root models.1.0forconst: 1is still accepted, and an enum that holds both, such asenum: [1, true], still accepts both. Data that the generated models accepted before may now fail validation. (#7067) - Generated models gain a constant-type validator base and class variable - Under
--generate-schema-validators, models with such constants now declare__json_schema_constant_types__: ClassVar[tuple[tuple[object, ...], ...]]and inherit a shared helper base that adds the_validate_json_schema_constant_typesmodel validator. A model whose only schema-validator rule is a const or enum can now subclass_JsonSchemaRuntimeValidationBaseinstead of plainBaseModel. When a module also needs the core or uniqueItems helper, that helper is renamed to_JsonSchemaRuntimeValidationBaseCore, and_JsonSchemaRuntimeValidationBasebecomes the constant-type layer on top of it. These modules also gainimport re, so the generated output and helper class names change for existing schemas. (#7067) - Generated client body field arguments now follow the model constructor under
--strip-default-none- This affects the experimental--generate-clientfeature. With--strip-default-none, a property the schema leaves optional whose Pydantic model field has no default (for exampletag: str | None) is now a required field argument of the call that sends the body. It is written astag: strinstead oftag: str | UNSET = UNSET, the README marks ittag (required)and itsFieldArgumentsflag is true. An OpenAPI 3.0nullable: trueproperty that the model writes without a default also becomes required, and so does an optionalnullable: trueproperty withdefault: nullinpydantic_v2.dataclassoutput. A property whose schema type includes null (OpenAPI 3.1type: [string, "null"]) keeps its= Nonedefault and stays optional. In the other direction, a required property markedx-is-classvar(with--field-include-all-keys) becomes optional inpydantic_v2.BaseModelandpydantic_v2.dataclassoutput, because aClassVaris not a constructor argument. Calls that left out the newly required arguments must now pass them (#7070) - AsyncAPI channels and SSE streams told apart by an optional tag property now route by that tag - This affects the experimental
--generate-clientfeature. With--strip-default-none, a generated WebSocket channel whose messages are told apart by an optional constant property (kind: {const: join}) now routes received messages by that property (MessageRoute(..., tag='join')with aBodySelectordiscriminator) instead of decoding them as a union of the message models. Server-sent event streams under--strip-default-none --force-optionallikewise route events by the body tag (BodySelector(pointer="/type")) instead of using one union codec (#7070) - Model field defaults are wrapped in
typing.castunder--use-annotated- With--use-annotatedand--output-model-type pydantic_v2.BaseModel, Pydantic validates some field defaults into a model (validate_default=True). This covers fields whose type holds a model or root model, including lists, dicts, sets and tuples of models, unions of models, scalar root models, and unions of a model with a format type such as a URL or date. Before, such a field was assigned the raw schema value, for example `flags: Annotated[Flags | Non...
0.97.0
Breaking Changes
Error Handling Changes
- Unmatched
--type-overrideskeys now emit aUserWarning- The--type-overridesoption (and thetype_overridesargument of the Python API and parsers) now checks every key after parsing. If any key names no generated model or field, it emits a singleUserWarningsuch as--type-overrides: 2 keys matched no generated model or field: 'Order.itme' (did you mean 'Order.item'?), 'Ordr' (did you mean 'Order'?). Where a close key exists, the warning suggests it, for example the class name a schema name was renamed to (ItemModel.priceforItem.price). The generated code does not change. Previously such keys were silently ignored, so runs that passed with no warnings can now print a warning on stderr. Callers that turn warnings into errors (-W error, pytestfilterwarnings = error) will now get an error. To fix it, correct or remove the keys the warning names. With--diff-against, the warning covers only the current input, not the baseline. (#6838) - Server and client targets raise
Errorfor a preset that does not fit the target Python version (experimental) - Whengenerate()runs with the experimentalgenerate_serverorgenerate_clienttarget and itspresetdoes not matchtarget_python_version, it now raisesdatamodel_code_generator.Errorwith the same message a model-only run gives. Before, it raiseddatamodel_code_generator.preset.PresetError, which is not a subclass ofError, so code that caughtPresetErroraround a target run no longer catches it and should catchdatamodel_code_generator.Errorinstead. The command line is unchanged. (#6864) - A new
UserWarningis emitted when an option is turned off but another option turns it back on ---use-annotatedturns on--field-constraints,--use-type-alias-typeturns on--use-type-aliasand--intersect-combined-schema-keywordsturns on--intersect-allof-keywords, including when a preset sets the first option or the output model type does (for example msgspec turning on--use-annotated). Previously, a run that turned the second option off kept it on without saying so. This happened with an argument such as--no-intersect-allof-keywords, withfalseinpyproject.toml, or withFalsepassed togenerate(). Now such a run emits aUserWarningthat names both options, says where the implying option came from, and explains how to turn both off. The generated code does not change, but callers that turn warnings into errors (for example-W erroror pytestfilterwarnings = error) now get an error for these combinations. The warning is not shown under--disable-warnings. It is also not emitted for apyproject.tomlvalue that a--presetargument replaces, foruse_type_aliaspassed togenerate(), or for values of a config returned byload_pyproject_config()(#6889) - A dataclass instance passed to
--input-modelnow fails with a clear error - Pointing--input-modelat an instance of a dataclass, for examplemodule:default_user, now reports'default_user' is not a supported type. Supported: dict, Pydantic v2 BaseModel, dataclass, TypedDict. In 0.96.0 it crashed with anAttributeError; pass the class (module:User) instead. - New
SchemaResourceRefWarningbefore fetching a document whose own$idends with an empty fragment - When a JSON Schema or OpenAPI document declares an$idending with an empty fragment and a$refin that same document names that URI or a pointer under it, the generator still fetches the document from that URL as in 0.96.0, but now warns first with aSchemaResourceRefWarning. The warning names the document, the URL and the written$id, and suggests--read-ids-with-empty-fragment. The generated output does not change. Callers that turn warnings into errors (for example-W errororwarnings.simplefilter("error")) now get an error instead of a successful run. To avoid it, pass--read-ids-with-empty-fragmentor write the$idwithout the trailing fragment marker (#6898) - New
UserWarningwhen a command-line argument turns off an option thatpyproject.tomlturned on - Withuse-annotated = trueandfield-constraints = falseinpyproject.toml, passing--no-use-annotatedturns--use-annotatedoff.--field-constraintsstays on, because the command line applies thepyproject.tomlvalues, and the option they imply, before the arguments. That was already the 0.96.0 behaviour, but such a run now emits aUserWarning:--field-constraints was turned off but stays on: use-annotated = true in pyproject.toml turns it on, which --no-use-annotated does not undo; use-annotated = false in pyproject.toml or --read-implied-options-from-merged-values turns it off. The generated output does not change. Callers that turn warnings into errors, for example with-W erroror pytestfilterwarnings = error, now fail. To avoid the warning, setuse-annotated = falseinpyproject.tomlinstead of passing--no-use-annotated, or pass--disable-warnings. You can also opt in to the new--read-implied-options-from-merged-values, under which the argument also turns--field-constraintsoff, which changes the output toconint. (#6911) - AsyncAPI client skip warnings reworded - In the experimental generated AsyncAPI client, a channel skipped because an AsyncAPI 2 operation's own HTTP binding declares
queryorheadersnow warnsthe query schema of its HTTP binding has no model(or theheadersequivalent) instead ofthe HTTP binding of an AsyncAPI 2 operation on it declares query, which no model types. Aqueryorheadersobject is now reported asis not an object of propertiesonly when the models type it as something other than an object, so some skip warnings disappear or change their text and tooling that matches these warning messages needs updating (#6958)
Code Generation Changes
- Generated AsyncAPI clients skip channels whose payload format generation does not read - With the experimental
--generate-client, a channel is now left out with amessage_content_typeswarning in two cases. The first is an AsyncAPI 2 message trait that gives aschemaFormatthe parser does not read, such asapplication/schema;version=draft-07. The client used to accept anyapplication/schemaorapplication/vnd.aai.asyncapispelling through a regex, and now codes only formats whose kind isasyncapi,jsonschemaoropenapi. The second is a messagecontentTypethat is not a valid media type but ends in+json, such asx+json, which is no longer treated as JSON. These channels used to be generated with a JSON codec, so their helpers are missing after regenerating. Write the format as the AsyncAPI specification lists it (application/schema+json;version=draft-07) and the content type as a real media type (application/x+json). (#6939) - Generated AsyncAPI clients now generate channels that were skipped or failed - With the experimental
--generate-client, some channels are now generated instead of being skipped asmessage_content_types. These are channels whose payload gives itsschemaFormatin another case or with spaces (application/SCHEMA+JSON;version=draft-07,application/schema+json ; version=draft-07), in an OpenAPI format (application/vnd.oai.openapi;version=3.0.0), or in such a spelling through an AsyncAPI 2 trait. Also, a payload written{schema: ...}without aschemaFormatnow binds the model generated for itsschema. Generation used to fail withThe use has no generated native typewhen it was the channel's only message, and the channel was skipped asseveral_messageswhen it sat beside another JSON message. A regenerated client gains helpers for these channels and loses their skip warnings. The numbered internal names after them shift, for exampleSOCKET_6becomesSOCKET_7inprotocols/_plans.pyandcodec_13becomescodec_14in_generated/model_bindings.py, so snapshot tests and committed generated clients change. (#6939) - Generated AsyncAPI clients carry binary-string JSON messages as raw bytes - This affects the experimental
--generate-clientfeature. A WebSocket channel message with a JSON content type whose payload is a binary string (type: string, format: binary) is now typed, sent and received as rawbytesin binary frames. Before, the payload's model encoded and decoded it in text frames. Code that passes or expects the model type for such channels must switch tobytes. Server-sent event channels still decode the event data with the model (#6957) - Generated AsyncAPI clients type some octet-stream and text messages as str instead of bytes - This affects the experimental
--generate-clientfeature. Two kinds of message are now typedstrand sent and received as UTF-8 text frames, where they werebytesin binary frames: anapplication/octet-streammessage whose payload is an enum of strings, and a text message whose binary-string payload the models type asstr(for example with--type-mappings binary=string). The send and receive types of the generated channel helpers change for these channels (#6957) - AsyncAPI client handshake parameters now follow the generated models - With the experimental
--generate-clienton AsyncAPI documents, the query and header parameters of a channel'sconnect(...)oropen(...)are now the fields of the models generated for its binding'squeryandheadersobjects, including inherited ones, and are required only where the models require them. Under--force-optionalevery handshake parameter is now optional, where it used to be required whenever the binding object required it. A parameter written as a$refnow takes thedescriptionof the schema it names in the generated helper. Some channels that used to be skipped with a warning are now generated and add new helpers to the client: channels whosequeryorheadersobject usesallOf, has keywords beside its pr...
0.96.0
Breaking Changes
Code Generation Changes
- Generated client methods return raw bodies for itemSchema stream responses - For an OpenAPI 3.2 response media of
text/event-streamor a JSON Lines or NDJSON type (application/jsonl,application/jsonlines,application/ndjson,application/x-jsonl,application/x-jsonlines,application/x-ndjson) whose schema is only anitemSchema, the generated client no longer binds the model of the item schema's array projection to the operation's response. The operation method, itswith_responseview and its result type alias now read the whole body raw:strfor an event stream (a text branch) andbytesfor JSON Lines or NDJSON (a binary branch). For example,WatchEventsResponsebecomesstr, and a JSON plus JSON Lines response becomesmodels.ExcerptGetResponse | bytes. Code that relied on the old result type must parse the raw body or use the new stream helper that regenerated clients now get atclient.protocols.<resource>.<method>, which yields typed items (#6767) - Generated client stream helpers now type items as the model the
itemSchemareferences - In generated Python clients, SSE, JSON Lines and NDJSON stream helpers whoseitemSchemais a bare$refnow use the referenced model, for exampleEventStream[models.LogEntry],AsyncEventStream[models.Event]andEventPlan[models.LogEntry]. Before, they used the duplicateItemSchemaorItemSchemaModelmodel generated at the item schema location. The codecs in_generated/model_bindings.pychange to match. With Pydantic v2 output, decoded stream items are now instances of the referenced model, for examplemodels.LogEntryinstead ofmodels.ItemSchemaModel, and validation error messages name that model. With dataclasses output, only the type annotations change. Code that annotates,isinstance-checks or pattern-matches stream items againstmodels.ItemSchemaormodels.ItemSchemaModelhas to switch to the referenced model (#6771) - Const, enum and allOf branches no longer take object keywords under
--read-object-keywords-by-type- With--read-object-keywords-by-type, which the standard and practical 20261112 presets also turn on, the check for ananyOforoneOfbranch that admits no object now looks at more than a declaredtypeor a$refto such a schema. It also countsconst,enum, nestedallOf,anyOfandoneOfparts, false schemas, and the full schema a$refnames together with the keywords beside it. Branches found this way are now read without the siblingproperties,patternProperties,additionalProperties,propertyNames,unevaluatedProperties,required,minPropertiesandmaxProperties. For example, ananyOfof aconstbranch, anenumbranch and an object branch next topropertiesandrequiredused to generate a single model fieldOwner | Noneand now generates a union likeLiteral['none'] | Owner | Owner1 | None. That adds new enum classes and can shift model names: the formerOwnermodel becomesOwner1. Under--generate-schema-validatorsthese sites also become unions instead of one validated object model. Output without the option is unchanged (#6777) - Regex patterns containing quotes are written differently in Pydantic v2 output - With
pydantic_v2.BaseModelandpydantic_v2.dataclassoutput, apatterncontaining a single quote used to be written as a single-quoted raw literal with the quote escaped by a backslash, for exampleconstr(pattern=r'^it\'s$'). Because raw literals keep backslashes, the runtime pattern string had an extra backslash before the quote. The generator now picks a quote character the pattern does not use, so this becomesconstr(pattern=r"^it's$"). A pattern containing both quote characters is now written as a plain (non-raw) literal, for example'^a-z\'"+$'instead ofr'^a-z\'"+$', and backslashes in such patterns are doubled. A pattern that already holds a backslash before a quote changes only in source text:"^don\\'t$"becomesr"^don\'t$". This affects string field patterns,propertyNameskey patterns, andStringConstraintswritten under--field-constraintsor--use-annotated. Python'srematches the same values, so validation does not change. However, the pattern stored inconstrorStringConstraints, and the pattern thatmodel_json_schema()publishes (for example in FastAPI OpenAPI docs), no longer has the extra backslash. The generated source text for these fields also changes, so snapshot tests or committed generated code will show differences after regenerating (#6790)
Error Handling Changes
- Helper names that collide with derived item stream helpers are now refused - When an OpenAPI 3.2 document has responses that stream an
itemSchema, generation now derives a stream helper named<resource>.<method>for each such operation. A helper in the protocols helper file whose name contains a derived name, or is contained in one (for example a declared helper nameddefaultbeside the deriveddefault.watch_events), now fails generation with anE_NAME_COLLISIONconfig diagnostic reported under the client protocols option. The same helper file used to generate. To fix it, rename the declared helper (#6767) - Deprecation and migration notices now name the code that called datamodel-code-generator instead of a module inside the package - Notices emitted through the central deprecation registry used to be attributed to a frame inside
datamodel_code_generator, picked by a fixedstacklevelat each call site. They are now attributed to the outermost frame outside the package. In the Python API that is the user module that calledgenerate()or another API. In the CLI it is the console script, or therunpyframe forpython -m. This covers the optional-dependency notices (Genson, Jinja2, Black/isort, Pydantic runtime minimum), the default formatters notice, the deprecated--validation,--parent-scoped-namingand--allow-extra-fieldsnotices, the remote$refdefault notice, the OpenAPInullableand JSON Schema arrayitemsnotices,PythonVersion.has_type_aliasand the other registry notices. As a result, each notice reports a different filename, line number and module. Filters that matched these notices bymodule="datamodel_code_generator"no longer suppress them, whether set inwarnings.filterwarnings,-W,PYTHONWARNINGSor pytestfilterwarnings. To silence them, filter by category and message, or target the calling module, for examplewarnings.filterwarnings("ignore", category=FutureWarning, module="mypackage.models"). Python's default filters showDeprecationWarningonly when it is attributed to__main__. A script that calls the API directly may therefore now show registry notices of categoryDeprecationWarningthat were hidden before (#6793)
What's Changed
- List client and server generation in What it does by Koudai Aono (@koxudaxi) in #6766
- Stream OpenAPI 3.2 itemSchema responses in the generated client by Koudai Aono (@koxudaxi) in #6767
- Bind the model a $ref names, not a root model another use made there by Koudai Aono (@koxudaxi) in #6771
- Skip the Genson notice when an installed package declares the extra by Ivan Shcheklein (@shcheklein) in #6785
- Stop fact walks at mapped refs in one ref-follow step by Koudai Aono (@koxudaxi) in #6775
- Decide a branch's object exclusion by one predicate by Koudai Aono (@koxudaxi) in #6776
- Read const, enum and allOf branches for object keywords by type by Koudai Aono (@koxudaxi) in #6777
- Merge every class that inherits an enum into the enum by Koudai Aono (@koxudaxi) in #6781
- Keep a regex holding a quote unchanged in the pattern literal by Koudai Aono (@koxudaxi) in #6790
- Type users of unmodelled mapped and x-python-import refs by import by Koudai Aono (@koxudaxi) in #6791
- Give GraphQL models a __typename property graphql-core can read by Koudai Aono (@koxudaxi) in #6792
- Point dependency notices at the code that called the library by Koudai Aono (@koxudaxi) in #6793
- Import a mapped class only in the modules that use it by Koudai Aono (@koxudaxi) in #6796
- Accept stacklevel in warn_deprecated again by Koudai Aono (@koxudaxi) in #6802
New Contributors
- Ivan Shcheklein (@shcheklein) made their first contribution in #6785
Full Changelog: 0.95.0...0.96.0
0.95.0
Breaking Changes
Code Generation Changes
- Required nullable parameters in generated FastAPI servers are now typed without None - A required query, path, header or cookie parameter can have a nullable schema, such as OpenAPI 3.0
nullable: trueor 3.1type: [string, "null"], and not be described bycontent. For such a parameter, the generated router endpoint now writes the plain type, for exampleAnnotated[str, Query(alias='q')]instead ofAnnotated[str | None, Query(alias='q')]. The generated service Protocol method now takes it asq: strinstead ofq: str | None. This also covers a nullable type that the target reads through a root model or alias. Optional parameters and parameters with acontentmedia type keep| None. Implementations that still declareX | Nonekeep type-checking, because such a parameter can never receive None. After regenerating, though, code that calls service methods with None for these parameters, or that relies on the old signatures, gets type errors. FastAPI's own OpenAPI document, served withsource_openapi=False, also no longer marks these parameters nullable. (#6737) - Schema validators no longer read references mapped by
--external-ref-mapping- With--generate-schema-validators, a$refthat--external-ref-mappingmaps to an imported class is no longer loaded when runtime validation rules are collected. Before, if the mapped document could be read, its rules went into the generated validators. These wereminProperties/maxPropertiesand scoped object rules such aspatternPropertiesreached throughallOf/anyOf/oneOfitems, and theuniqueItemsrules of union branches. Now the mapped reference adds no rules, and it is treated as possibly accepting both object and array data. Generated models can therefore lose validation checks they had before, for example theuniqueItemscheck on an array branch next to a mapped object branch, and accept data they used to reject. Schemas that used to fail because the mapped document was missing or refused by--strict-refsnow generate. (#6762)
Default Behavior Changes
- Dynamic model generation no longer formats generated code by default -
generate_dynamic_models()andgenerate_dynamic_module()now skip formatting when none offormatters,custom_formattersor the config'spresetselects formatters. Before, they formatted the code with Black and isort, asgenerate()does. Black and isort are no longer imported in that case, and the "Default formatters will change to builtin"FutureWarningis no longer emitted. Presets that do not set formatters, such asstandard-py313-20260619, now also give unformatted code. Formatting stripped spaces and tabs from the ends of lines in class docstrings. So withuse_schema_description=True, a schema description whose lines end with spaces or tabs (for example a Markdown hard break) now keeps that trailing whitespace in the class__doc__and in thedescriptionthat Pydantic'smodel_json_schema()reports. Setformatters(for exampleformatters=[Formatter.BUILTIN]) to bring back formatting and the stripped docstrings.generate()and the CLI are unchanged. (#6750) - New FutureWarning when custom templates are used - Generation with a custom template directory (
--custom-template-dir,custom-template-dirin pyproject.toml, orcustom_template_dirin thegenerate()config) now emits thedependency.jinja2-optionalFutureWarning "Jinja2 will become optional. Declare the jinja2 extra for --custom-template-dir; see --help." It is shown once per CLI invocation and on eachgenerate()call. Python shows FutureWarning by default, so this is new stderr output for existing users. Setups that turn warnings into errors (-W error,PYTHONWARNINGS=error, pytestfilterwarnings = error) now fail until the warning is filtered. Jinja2 is still a required dependency; declare the newjinja2extra to prepare for it becoming optional. (#6755) - New FutureWarning when generating from raw data input - Generating from JSON, YAML, CSV or dict sample data (
--input-file-type json,yamlorcsv, orgenerate()with a dict) now emits thedependency.genson-optionalFutureWarning "Genson will become optional. Declare the genson extra for JSON, YAML, CSV and dict input; see --help." Schema inputs such as JSON Schema and OpenAPI do not warn. Setups that turn warnings into errors now fail for these inputs until the warning is filtered. Genson is still a required dependency; declare the newgensonextra to prepare for it becoming optional. (#6755)
Error Handling Changes
- Experimental
--untrusted-inputnow refuses deeply nested or very large schemas - With the experimental--untrusted-inputoption (untrusted_input=Trueingenerate()and in theGenerateConfigof the dynamic API), a schema whose objects and arrays nest more than 100 levels deep, or that holds more than 2,000,000 objects and arrays, now stops generation with an error. A YAML alias counts each time it is used. The check runs before the document is parsed: on each input document, on converted sources, and ingenerate_dynamic_modelsbefore the schema is hashed for the cache. These schemas could generate under--untrusted-inputin 0.94.0. The error names the limit and how deep or large the schema is. To process such a schema, flatten or split it, or generate without--untrusted-inputif the schema is trusted. Behaviour without the option does not change. (#6752)
What's Changed
- Leave None out of server signatures of required style parameters by Koudai Aono (@koxudaxi) in #6737
- Call the JSON Schema concern homes directly, not through the parser by Koudai Aono (@koxudaxi) in #6738
- Skip unread Pydantic floor work and the lockfile path resolution by Koudai Aono (@koxudaxi) in #6740
- Ask for one PyPI approval per release by Koudai Aono (@koxudaxi) in #6745
- Build type-map entries without validating their values again by Koudai Aono (@koxudaxi) in #6746
- Document runtime schemas in dynamic model generation by Koudai Aono (@koxudaxi) in #6747
- Skip formatting dynamic models unless formatters are selected by Koudai Aono (@koxudaxi) in #6750
- Document LLM tool and MCP schemas in dynamic model generation by Koudai Aono (@koxudaxi) in #6751
- Refuse untrusted schemas past a nesting depth or node count by Koudai Aono (@koxudaxi) in #6752
- Apply options a command-line flag implies beside a pyproject table by Koudai Aono (@koxudaxi) in #6753
- Read object keywords beside anyOf for object branches under an option by Koudai Aono (@koxudaxi) in #6754
- Announce that jinja2, genson and argcomplete become optional by Koudai Aono (@koxudaxi) in #6755
- Compile a record's init once per shape of its fields by Koudai Aono (@koxudaxi) in #6759
- Update ruff to 0.17.4 and follow its lint rules by Koudai Aono (@koxudaxi) in #6760
- Leave a mapped $ref unread by the schema validators by Koudai Aono (@koxudaxi) in #6762
- Build private mutable dataclasses without generating their methods by Koudai Aono (@koxudaxi) in #6764
Full Changelog: 0.94.0...0.95.0
0.94.0
Breaking Changes
Code Generation Changes
- Generated client methods no longer accept None for required nullable parameters - For a required query, path, header or cookie parameter serialized by its style rather than by a
contentmedia type, whose schema is nullable (for exampletype: string, nullable: truewith--strict-nullable, ortype: [string, "null"]in OpenAPI 3.1, directly or through a root model or type alias), the generated client now types the keyword argument without None, such asq: strinstead ofq: str | Noneandids: list[int]instead of a nullablelist[int]for a root model of a nullable array; the fields of theOperation0Arguments-styleTypedDictused by theunpacksignature style change the same way. Code that passes None or an optional-typed value to these arguments now fails type checking after regeneration, while parameters sent throughcontent, optional parameters, and nullable items inside arrays such aslist[str | None]keep None (#6726)
What's Changed
- Quote the names the root-name rule suggests in its evidence by Koudai Aono (@koxudaxi) in #6725
- Leave None out of client signatures of required style parameters by Koudai Aono (@koxudaxi) in #6726
- Check nested subschemas under --schema-version-mode strict by Koudai Aono (@koxudaxi) in #6728
- Add the 20261111 presets by Koudai Aono (@koxudaxi) in #6729
- Fix a float const by equal bounds under --use-bounds-for-float-const by Koudai Aono (@koxudaxi) in #6730
- Let pytest name the stored outputs of the input-model tests by Koudai Aono (@koxudaxi) in #6731
- Publish a datamodel-codegen alias package with each release by Koudai Aono (@koxudaxi) in #6732
- Update ty, types-setuptools, pip, pinned actions and three hooks by Koudai Aono (@koxudaxi) in #6734
Full Changelog: 0.93.0...0.94.0
0.93.0
Breaking Changes
Error Handling Changes
- The deprecated
--validationoption is now rejected when used with--no-allow-remote-refs- Passing--validationtogether with--no-allow-remote-refs(orvalidation=Truewithallow_remote_refs=Falsein the Python API) when parsing OpenAPI input used to run the prance validator, which fetched remote$refURLs even though remote refs were turned off. The parser now raises anErrorinstead: "--validation is refused under --no-allow-remote-refs: its validator resolves the $ref of the document by itself and fetches the URLs that --no-allow-remote-refs blocks." The command exits with an error and no code is generated. This works the same way as the existing refusal of--validationunder--untrusted-input. If you use both options, drop--validation(it is deprecated) or stop passing--no-allow-remote-refs. (#6688)
Python Version Changes
- Dropped support for running on Python 3.10 - The package now declares
requires-python = ">=3.11". The Python 3.10 classifier is gone, and so is thetomlidependency that was only installed below Python 3.11. datamodel-code-generator can no longer be installed or run on Python 3.10, and pip and uv will keep Python 3.10 environments on the 0.92.x release. This completes the deprecation announced in 0.84.0: thedependency.python-310-runtimeFutureWarning is no longer emitted, and its registry entry, shown by--list-deprecations, now records removal in 0.93.0. Only the interpreter running the generator is affected. The default target is still Python 3.10, and code generated for Python 3.10, with or without--target-python-version 3.10, is unchanged. Projects still on Python 3.10 can keep generating code by running the tool on a newer Python, for exampleuvx datamodel-code-generator --target-python-version 3.10 ...(#6701)
What's Changed
- Measure builtin line widths in display columns like black by Koudai Aono (@koxudaxi) in #6659
- Choose builtin string quotes like black under string normalization by Koudai Aono (@koxudaxi) in #6660
- Wrap string literals in the builtin formatter like black by Koudai Aono (@koxudaxi) in #6661
- Sort and wrap nested import runs in the builtin formatter like isort by Koudai Aono (@koxudaxi) in #6662
- Lay out function bodies and clause headers in the builtin formatter by Koudai Aono (@koxudaxi) in #6663
- Speed up the builtin formatter's line layout by Koudai Aono (@koxudaxi) in #6664
- Wrap strings in return, assert and long annotated heads like black by Koudai Aono (@koxudaxi) in #6666
- Keep comments between statements and place black's blank lines by Koudai Aono (@koxudaxi) in #6675
- Write comments with black's spacing in the builtin formatter by Koudai Aono (@koxudaxi) in #6676
- Sort template-written imports with their comments like isort by Koudai Aono (@koxudaxi) in #6677
- Indent by four spaces per block in the builtin formatter by Koudai Aono (@koxudaxi) in #6678
- Leave out request media types the client cannot write, not the operation by Koudai Aono (@koxudaxi) in #6679
- Write reserved parameter names only where additional keys read them by Koudai Aono (@koxudaxi) in #6681
- Wait for the test server before reading what it saw by Koudai Aono (@koxudaxi) in #6682
- Add a datamodel-code-generator command for uvx and pipx run by Koudai Aono (@koxudaxi) in #6684
- Add six more downstream projects to the behaviour diff projects tier by Koudai Aono (@koxudaxi) in #6685
- Describe the threat model in the security policy by Koudai Aono (@koxudaxi) in #6687
- Refuse --validation together with --no-allow-remote-refs by Koudai Aono (@koxudaxi) in #6688
- Warn when Pydantic 2.14 refuses a bytes pattern at import by Koudai Aono (@koxudaxi) in #6691
- Update locked dependencies to their security fix releases by Koudai Aono (@koxudaxi) in #6692
- Remember logical line layouts in the builtin formatter by Koudai Aono (@koxudaxi) in #6697
- Mark brackets with less work per leaf in the builtin line split by Koudai Aono (@koxudaxi) in #6698
- Find the opening bracket from the line end in the builtin line split by Koudai Aono (@koxudaxi) in #6699
- Call the schema resource and definition cores directly by Koudai Aono (@koxudaxi) in #6702
- Name the current and located document and definition entries once by Koudai Aono (@koxudaxi) in #6703
- Route the enum, key keyword and root split rules to their homes by Koudai Aono (@koxudaxi) in #6704
- Build the predicted and parameter class scopes in one place by Koudai Aono (@koxudaxi) in #6705
- Pass one module import target to the reference import functions by Koudai Aono (@koxudaxi) in #6706
- Call the type override functions instead of their Parser forwarders by Koudai Aono (@koxudaxi) in #6707
- Drop the test-only module_dependency_cycles forwarder by Koudai Aono (@koxudaxi) in #6708
- Read variant tags through one TagReading and msgspec clashes in one walk by Koudai Aono (@koxudaxi) in #6709
- Read target types through one TypeTables index per batch by Koudai Aono (@koxudaxi) in #6710
- Fold the binder's schema reader into the parser and read others once by Koudai Aono (@koxudaxi) in #6711
- Call the lock plan home directly and import partial once by Koudai Aono (@koxudaxi) in #6712
- Build scheme catalogues and media encodings once per planner and media by Koudai Aono (@koxudaxi) in #6713
- Name the moved helpers in the architecture docs by Koudai Aono (@koxudaxi) in #6714
- Remove test-only JsonSchemaParser forwarders of allOf and rw-split homes by Koudai Aono (@koxudaxi) in #6715
- Remove test-only JsonSchemaParser forwarders of validator and ref homes by Koudai Aono (@koxudaxi) in #6716
- Remove test-only parser forwarders and parse-end cache clears by Koudai Aono (@koxudaxi) in #6718
- Write site marks through their homes and walk recommender paths once by Koudai Aono (@koxudaxi) in #6719
- Read live models, package paths and wrapper chains from their homes by Koudai Aono (@koxudaxi) in #6720
- Stop running datamodel-code-generator on Python 3.10 by Koudai Aono (@koxudaxi) in #6701
Full Changelog: 0.92.0...0.93.0