コンテンツにスキップ

Code Generation with datamodel-code-generator

datamodel-code-generatorプロジェクトは、以下のようなあらゆるデータソースからpydanticモデルを生成するためのライブラリとコマンドラインユーティリティです。

  • OpenAPI 3 (YAML/JSON)
  • JSON Schema
  • JSON/YAML/CSV Data (JSONスキーマに変換されます)
  • Python dictionary (JSONスキーマに変換されます)
  • GraphQL schema

データ変換可能なJSONを使用していますが、pydanticモデルを使用していない場合は、このツールを使用すると、タイプセーフなモデル階層をオンデマンドで生成できます。

Installation

pip install datamodel-code-generator

Example

この場合、datamodel-code-generatorはJSON Schemaファイルからpydanticモデルを作成します。

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

from pydantic import BaseModel, Field, conint


class Pet(BaseModel):
    name: str | None = None
    age: int | None = 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: conint(ge=0) | None = Field(None, description='Age in years.')
    pets: list[Pet] | None = None
    comment: Any | None = None

詳細については、official documentationを参照してください。