Code Generation with datamodel-code-generator¶
Thedatamodel-code-generator project is a library and command-line utility to generate pydantic models from just about any data source, including:
- OpenAPI 3 (YAML/JSON)
- JSON Schema
- JSON/YAML/CSV Data (which will be converted to JSON Schema)
- Python dictionary (which will be converted to JSON Schema)
- GraphQL schema
Whenever you find yourself with any data convertible JSON but without pydantic models, this tool will allow you to generate type-safe model hierarchies on demand.
Installation¶
pipinstalldatamodel-code-generatorExample¶
In this case, datamodel-code-generator creates pydantic models from a JSON Schema file.
datamodel-codegen--inputperson.json--input-file-typejsonschema--outputmodel.pyperson.json:
{"$id":"person.json","$schema":"http://json-schema.org/draft-07/schema#","title":"Person","type":"object","properties":{"first_name":{"type":"string","description":"The person's first name."},"last_name":{"type":"string","description":"The person's last name."},"age":{"description":"Age in years.","type":"integer","minimum":0},"pets":{"type":"array","items":[{"$ref":"#/definitions/Pet"}]},"comment":{"type":"null"}},"required":["first_name","last_name"],"definitions":{"Pet":{"properties":{"name":{"type":"string"},"age":{"type":"integer"}}}}}model.py:
# generated by datamodel-codegen:# filename: person.json# timestamp: 2020-05-19T15:07:31+00:00from__future__importannotationsfromtypingimportAnyfrompydanticimportBaseModel,Field,conintclassPet(BaseModel):name:str|None=Noneage:int|None=NoneclassPerson(BaseModel):first_name:str=Field(description="The person's first name.")last_name:str=Field(description="The person's last name.")age:conint(ge=0)|None=Field(None,description='Age in years.')pets:list[Pet]|None=Nonecomment:Any|None=NoneMore information can be found on theofficial documentation