Package: improved-datamodel-codegen
datamodel-code-generatorThis code generator creates pydantic model from an openapi file and others.HelpSeedocumentationfor more details.Supported source 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)Implemented listOpenAPI 3 and JsonSchemaDataTypestring (include patter/minLength/maxLenght)number (include maximum/exclusiveMaximum/minimum/exclusiveMinimum/multipleOf/le/ge)integer (include maximum/exclusiveMaximum/minimum/exclusiveMinimum/multipleOf/le/ge)booleanarrayobjectString Formatdatedatetimetimepasswordemailidn-emailuuid (uuid1/uuid2/uuid3/uuid4/uuid5)ipv4ipv6ipv4-networkipv6-networkhostnamedecimalOther schemaenum (as enum.Enum or typing.Literal)allOf (as Multiple inheritance)anyOf (as typing.Union)oneOf (as typing.Union)$ref (http extrais required when resolving $ref for remote files.)$id (forJSONSchema)InstallationTo installdatamodel-code-generator:$pipinstalldatamodel-code-generatorhttpextra optionIf you want to resolve$reffor remote files then you should specifyhttpextra option.$pipinstalldatamodel-code-generator[http]UsageThedatamodel-codegencommand:usage:datamodel-codegen[-h][--inputINPUT][--urlURL][--http-headersHTTP_HEADER[HTTP_HEADER...]][--http-ignore-tls][--input-file-type{auto,openapi,jsonschema,json,yaml,dict,csv}][--openapi-scopes{schemas,paths}[{schemas,paths}...]][--outputOUTPUT][--base-classBASE_CLASS][--field-constraints][--use-annotated][--use_non_positive_negative_number_constrained_types][--field-extra-keysFIELD_EXTRA_KEYS[FIELD_EXTRA_KEYS...]][--field-include-all-keys][--snake-case-field][--original-field-name-delimiterORIGINAL_FIELD_NAME_DELIMITER][--strip-default-none][--disable-appending-item-suffix][--allow-population-by-field-name][--enable-faux-immutability][--use-default][--force-optional][--strict-nullable][--strict-types{str,bytes,int,float,bool}[{str,bytes,int,float,bool}...]][--disable-timestamp][--use-standard-collections][--use-generic-container-types][--use-schema-description][--reuse-model][--enum-field-as-literal{all,one}][--set-default-enum-member][--empty-enum-field-nameEMPTY_ENUM_FIELD_NAME][--use-subclass-enum][--class-nameCLASS_NAME][--use-title-as-name][--custom-template-dirCUSTOM_TEMPLATE_DIR][--extra-template-dataEXTRA_TEMPLATE_DATA][--aliasesALIASES][--target-python-version{3.6,3.7,3.8,3.9}][--wrap-string-literal][--validation][--encodingENCODING][--debug][--version]optionalarguments:-h,--helpshowthishelpmessageandexit--inputINPUTInputfile/directory(default:stdin)--urlURLInputfileURL.`--input`isignorewhen`--url`isused--http-headersHTTP_HEADER[HTTP_HEADER...]SetheadersinHTTPrequeststotheremotehost.(example:"Authorization: Basic dXNlcjpwYXNz")--http-ignore-tlsDisableverificationoftheremotehost'sTLScertificate--input-file-type{auto,openapi,jsonschema,json,yaml,dict,csv}Inputfiletype(default:auto)--openapi-scopes{schemas,paths}[{schemas,paths}...]ScopesofOpenAPImodelgeneration(default:schemas)--outputOUTPUTOutputfile(default:stdout)--base-classBASE_CLASSBaseClass(default:pydantic.BaseModel)--field-constraintsUsefieldconstraintsandnotcon*annotations--use-annotatedUsetyping.AnnotatedforField().Also,`--field-constraints`optionwillbeenabled.--use_non_positive_negative_number_constrained_typesUsetheNon{Positive,Negative}{FloatInt}typesinsteadofthecorrespondingcon*constrainedtypes.--field-extra-keysFIELD_EXTRA_KEYS[FIELD_EXTRA_KEYS...]Addextrakeystofieldparameters--field-include-all-keysAddallkeystofieldparameters--snake-case-fieldChangecamel-casefieldnametosnake-case--original-field-name-delimiterORIGINAL_FIELD_NAME_DELIMITERSetdelimitertoconverttosnakecase.Thisoptiononlycanbeusedwith--snake-case-field(default:`_`)--strip-default-noneStripdefaultNoneonfields--disable-appending-item-suffixDisableappending`Item`suffixtomodelnameinanarray--allow-population-by-field-nameAllowpopulationbyfieldname--enable-faux-immutabilityEnablefauximmutability--use-defaultUsedefaultvalueevenifafieldisrequired--force-optionalForceoptionalforrequiredfields--strict-nullableTreatdefaultfieldasanon-nullablefield(OnlyOpenAPI)--strict-types{str,bytes,int,float,bool}[{str,bytes,int,float,bool}...]Usestricttypes--disable-timestampDisabletimestamponfileheaders--use-standard-collectionsUsestandardcollectionsfortypehinting(list,dict)--use-generic-container-typesUsegenericcontainertypesfortypehinting(typing.Sequence,typing.Mapping).If`--use-standard-collections`optionisset,thenimportfromcollections.abcinsteadoftyping--use-schema-descriptionUseschemadescriptiontopopulateclassdocstring--reuse-modelRe-usemodelsonthefieldwhenamodulehasthemodelwiththesamecontent--enum-field-as-literal{all,one}Parseenumfieldasliteral.all:allenumfieldtypeareLiteral.one:fieldtypeisLiteralwhenanenumhasonlyonepossiblevalue--set-default-enum-memberSetenummembersasdefaultvaluesforenumfield--empty-enum-field-nameEMPTY_ENUM_FIELD_NAMESetfieldnamewhenenumvalueisempty(default:`_`)--use-subclass-enumDefineEnumclassassubclasswithfieldtypewhenenumhastype(int,float,bytes,str)--class-nameCLASS_NAMESetclassnameofrootmodel--use-title-as-nameusetitlesasclassnamesofmodels--custom-template-dirCUSTOM_TEMPLATE_DIRCustomtemplatedirectory--extra-template-dataEXTRA_TEMPLATE_DATAExtratemplatedata--aliasesALIASESAliasmappingfile--target-python-version{3.6,3.7,3.8,3.9}targetpythonversion(default:3.7)--wrap-string-literalWrapstringliteralbyusingblack`experimental-string-processing`option(requireblack20.8b0orlater)--validationEnablevalidation(OnlyOpenAPI)--encodingENCODINGTheencodingofinputandoutput(default:UTF-8)--debugshowdebugmessage--versionshowversionExampleOpenAPI# Generate models from a local file.$datamodel-codegen--inputapi.yaml--outputmodel.py# or directly from a URL.$datamodel-codegen--urlhttps://<INPUTFILEURL>--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]Related 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-generatorLicensedatamodel-code-generator is released under the MIT License.http://www.opensource.org/licenses/mit-license