Skip to content

Code Generation

datamodel-code-generator is a command to generate pydantic models from other data types.

  • Supported source types
    • OpenAPI 3 (YAML/JSON)
    • JSON Schema
    • JSON/YAML Data (It will be converted to JSON Schema)

Install🔗

pip install datamodel-code-generator

Example🔗

In this case, The datamodel-code-generator creates pydantic models from JSON Schema.

datamodel-codegen  --input person.json --input-file-type jsonschema --output model.py

person.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:00
from __future__ import annotations
from typing import Any, List, Optional
from pydantic import BaseModel, Field, conint


class Pet(BaseModel):
    name: Optional[str] = None
    age: Optional[int] = None


class Person(BaseModel):
    first_name: str = Field(..., description="The person's first name.")
    last_name: str = Field(..., description="The person's last name.")
    age: Optional[conint(ge=0)] = Field(None, description='Age in years.')
    pets: Optional[List[Pet]] = None
    comment: Optional[Any] = None

More information can be found on the official documentation