Package: datamodel-code-generator
datamodel-code-generatorThis code generator createspydantic v1 and v2model,dataclasses.dataclass,typing.TypedDictandmsgspec.Structfrom an openapi file and others.HelpSeedocumentationfor more details.SponsorsQuick InstallationTo installdatamodel-code-generator:$pipinstalldatamodel-code-generatorSimple UsageYou can generate models from a local file.$datamodel-codegen--inputapi.yaml--outputmodel.pyapi.yamlopenapi:"3.0.0"info:version:1.0.0title:Swagger Petstorelicense:name:MITservers:-url:http://petstore.swagger.io/v1paths:/pets:get:summary:List all petsoperationId:listPetstags:-petsparameters:-name:limitin:querydescription:How many items to return at one time (max 100)required:falseschema:type:integerformat:int32responses:'200':description:A paged array of petsheaders:x-next:description:A link to the next page of responsesschema:type:stringcontent:application/json:schema:$ref:"#/components/schemas/Pets"default:description:unexpected errorcontent:application/json:schema:$ref:"#/components/schemas/Error"x-amazon-apigateway-integration:uri:Fn::Sub:arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PythonVersionFunction.Arn}/invocationspassthroughBehavior:when_no_templateshttpMethod:POSTtype:aws_proxypost:summary:Create a petoperationId:createPetstags:-petsresponses:'201':description:Null responsedefault:description:unexpected errorcontent:application/json:schema:$ref:"#/components/schemas/Error"x-amazon-apigateway-integration:uri:Fn::Sub:arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PythonVersionFunction.Arn}/invocationspassthroughBehavior:when_no_templateshttpMethod:POSTtype:aws_proxy/pets/{petId}:get:summary:Info for a specific petoperationId:showPetByIdtags:-petsparameters:-name:petIdin:pathrequired:truedescription:The id of the pet to retrieveschema:type:stringresponses:'200':description:Expected response to a valid requestcontent:application/json:schema:$ref:"#/components/schemas/Pets"default:description:unexpected errorcontent:application/json:schema:$ref:"#/components/schemas/Error"x-amazon-apigateway-integration:uri:Fn::Sub:arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PythonVersionFunction.Arn}/invocationspassthroughBehavior:when_no_templateshttpMethod:POSTtype:aws_proxycomponents:schemas:Pet:required:-id-nameproperties:id:type:integerformat:int64name:type:stringtag:type:stringPets:type:arrayitems:$ref:"#/components/schemas/Pet"Error:required:-code-messageproperties:code:type:integerformat:int32message:type:stringapis:type:arrayitems:type:objectproperties:apiKey:type:stringdescription:To be used as a dataset parameter valueapiVersionNumber:type:stringdescription:To be used as a version parameter valueapiUrl:type:stringformat:uridescription:"TheURLdescribingthedataset'sfields"apiDocumentationUrl:type:stringformat:uridescription:A URL to the API console for each APImodel.py# generated by datamodel-codegen:#   filename:  api.yaml#   timestamp: 2020-06-02T05:28:24+00:00from__future__importannotationsfromtypingimportList,OptionalfrompydanticimportAnyUrl,BaseModel,FieldclassPet(BaseModel):id:intname:strtag:Optional[str]=NoneclassPets(BaseModel):__root__:List[Pet]classError(BaseModel):code:intmessage:strclassApi(BaseModel):apiKey:Optional[str]=Field(None,description='To be used as a dataset parameter value')apiVersionNumber:Optional[str]=Field(None,description='To be used as a version parameter value')apiUrl:Optional[AnyUrl]=Field(None,description="The URL describing the dataset's fields")apiDocumentationUrl:Optional[AnyUrl]=Field(None,description='A URL to the API console for each API')classApis(BaseModel):__root__:List[Api]Projects that use datamodel-code-generatorThese OSS projects use datamodel-code-generator to generate many models.
See the following linked projects for real world examples and inspiration.airbytehq/airbytecode-generator/Dockerfileapache/icebergGenerate Python codemake generateargoproj-labs/heraMakefileawslabs/aws-lambda-powertools-pythonRecommended foradvanced-use-casesin the official documentationDataDog/integrations-coreConfig modelshashintel/hashcodegen.shIBM/compliance-trestleBuilding the models from the OSCAL schemas.Netflix/consolemeHow do I generate models from the Swagger specification?Nike-Inc/brickflowCode generate tools./tools/gen-bundle.shopen-metadata/OpenMetadataMakefilePostHog/posthogGenerate models vianpm runSeldonIO/MLServergenerate-types.shSupported input typesOpenAPI 3 (YAML/JSON,OpenAPI Data Type);JSON Schema (JSON Schema Core/JSON Schema Validation);JSON/YAML/CSV Data (it will be converted to JSON Schema);Python dictionary (it will be converted to JSON Schema);GraphQL schema (GraphQL Schemas and Types);Supported output typespydantic.BaseModel;pydantic_v2.BaseModel;dataclasses.dataclass;typing.TypedDict;msgspec.Struct;Custom type from yourjinja2template;InstallationTo installdatamodel-code-generator:$pipinstalldatamodel-code-generatorhttpextra optionIf you want to resolve$reffor remote files then you should specifyhttpextra option.$pipinstall'datamodel-code-generator[http]'graphqlextra optionIf you want to generate data model from a GraphQL schema then you should specifygraphqlextra option.$pipinstall'datamodel-code-generator[graphql]'Docker ImageThe docker image is inDocker Hub$dockerpullkoxudaxi/datamodel-code-generatorAdvanced UsesYou can generate models from a URL.$datamodel-codegen--urlhttps://<INPUTFILEURL>--outputmodel.pyThis method needs thehttp extra optionAll Command OptionsThedatamodel-codegencommand:usage:datamodel-codegen[options]GeneratePythondatamodelsfromschemadefinitionsorstructureddata

Options:--http-headersHTTP_HEADER[HTTP_HEADER...]SetheadersinHTTPrequeststotheremotehost.(example:"Authorization: Basic dXNlcjpwYXNz")--http-ignore-tlsDisableverificationoftheremotehost's TLScertificate--input INPUT         Input file/directory (default: stdin)--input-file-type {auto,openapi,graphql,jsonschema,json,yaml,dict,csv}Input file type (default: auto)--output OUTPUT       Output file (default: stdout)--output-model-type {pydantic.BaseModel,pydantic_v2.BaseModel,dataclasses.dataclass,typing.TypedDict,msgspec.Struct}--url URL             Input file URL. `--input` is ignored when `--url` isusedTyping customization:--base-class BASE_CLASSBase Class (default: pydantic.BaseModel)--enum-field-as-literal {all,one}Parse enum field as literal. all: all enum field typeare Literal. one: field type is Literal when an enumhas only one possible value--field-constraints   Use field constraints and not con* annotations--set-default-enum-memberSet enum members as default values for enum field--strict-types {str,bytes,int,float,bool} [{str,bytes,int,float,bool} ...]Use strict types--use-annotated       Use typing.Annotated for Field(). Also, `--field-constraints` option will be enabled.--use-generic-container-typesUse generic container types for type hinting(typing.Sequence, typing.Mapping). If `--use-standard-collections` option is set, then import fromcollections.abc instead of typing--use-non-positive-negative-number-constrained-typesUse the Non{Positive,Negative}{FloatInt} types insteadof the corresponding con* constrained types.--use-one-literal-as-defaultUse one literal as default value for one literal field--use-standard-collectionsUse standard collections for type hinting (list, dict)--use-subclass-enum   Define Enum class as subclass with field type whenenum has type (int, float, bytes, str)--use-union-operator  Use | operator for Union type (PEP 604).--use-unique-items-as-setdefine field type as `set` when the field attributehas `uniqueItems`Field customization:--capitalise-enum-members, --capitalize-enum-membersCapitalize field names on enum--empty-enum-field-name EMPTY_ENUM_FIELD_NAMESet field name when enum value is empty (default: `_`)--field-extra-keys FIELD_EXTRA_KEYS [FIELD_EXTRA_KEYS ...]Add extra keys to field parameters--field-extra-keys-without-x-prefix FIELD_EXTRA_KEYS_WITHOUT_X_PREFIX [FIELD_EXTRA_KEYS_WITHOUT_X_PREFIX ...]Add extra keys with `x-` prefix to field parameters.The extra keys are stripped of the `x-` prefix.--field-include-all-keysAdd all keys to field parameters--force-optional      Force optional for required fields--original-field-name-delimiter ORIGINAL_FIELD_NAME_DELIMITERSet delimiter to convert to snake case. This optiononly can be used with --snake-case-field (default: `_`)--remove-special-field-name-prefixRemove field name prefix if it has a special meaninge.g. underscores--snake-case-field    Change camel-case field name to snake-case--special-field-name-prefix SPECIAL_FIELD_NAME_PREFIXSet field name prefix when first character can'tbeusedasPythonfieldname(default:`field`)--strip-default-noneStripdefaultNoneonfields--use-defaultUsedefaultvalueevenifafieldisrequired--use-default-kwargUse`default=`insteadofapositionalargumentforFieldsthathavedefaultvalues.--use-field-descriptionUseschemadescriptiontopopulatefielddocstring

Modelcustomization:--allow-extra-fieldsAllowtopassextrafields,ifthisflagisnotpassed,extrafieldsareforbidden.--allow-population-by-field-nameAllowpopulationbyfieldname--class-nameCLASS_NAMESetclassnameofrootmodel--collapse-root-modelsModelsgeneratedwitharoot-typefieldwillbemergedintothemodelsusingthatroot-typemodel--disable-appending-item-suffixDisableappending`Item`suffixtomodelnameinanarray--disable-timestampDisabletimestamponfileheaders--enable-faux-immutabilityEnablefauximmutability--enable-version-headerEnablepackageversiononfileheaders--keep-model-orderKeepgeneratedmodels' order--reuse-model         Reuse models on the field when a module has the modelwith the same content--target-python-version {3.6,3.7,3.8,3.9,3.10,3.11}target python version (default: 3.7)--use-schema-descriptionUse schema description to populate class docstring--use-title-as-name   use titles as class names of modelsTemplate customization:--aliases ALIASES     Alias mapping file--custom-file-header CUSTOM_FILE_HEADERCustom file header--custom-file-header-path CUSTOM_FILE_HEADER_PATHCustom file header file path--custom-template-dir CUSTOM_TEMPLATE_DIRCustom template directory--encoding ENCODING   The encoding of input and output (default: UTF-8)--extra-template-data EXTRA_TEMPLATE_DATAExtra template data--use-double-quotes   Model generated with double quotes. Single quotes oryour black config skip_string_normalization value willbe used without this option.--wrap-string-literalWrap string literal by using black `experimental-string-processing` option (require black 20.8b0 orlater)--additional-imports  Custom imports for output (delimited list input).For example "datetime.date,datetime.datetime"--custom-formatters   List of modules with custom formatter (delimited list input).--custom-formatters-kwargs A file with kwargs for custom formatters.OpenAPI-only options:--openapi-scopes {schemas,paths,tags,parameters} [{schemas,paths,tags,parameters} ...]Scopes of OpenAPI model generation (default: schemas)--strict-nullable     Treat default field as a non-nullable field (OnlyOpenAPI)--use-operation-id-as-nameuse operation id of OpenAPI as class names of models--validation          Deprecated: Enable validation (Only OpenAPI). thisoption is deprecated. it will be removed in futurereleasesGeneral options:--debug               show debug message (require "debug". `$ pip install 'datamodel-code-generator[debug]'`)--disable-warningsdisablewarnings--no-colordisablecolorizedoutput--versionshowversion-h,--helpshowthishelpmessageandexitRelated projectsfastapi-code-generatorThis code generator createsFastAPIapp from an openapi file.https://github.com/koxudaxi/fastapi-code-generatorpydantic-pycharm-pluginA JetBrains PyCharm pluginforpydantic.https://github.com/koxudaxi/pydantic-pycharm-pluginPyPihttps://pypi.org/project/datamodel-code-generatorContributingSeedocs/development-contributing.mdfor how to get started!Licensedatamodel-code-generator is released under the MIT License.http://www.opensource.org/licenses/mit-license