Files
pydantic/docs/datamodel_code_generator.md
T
Koudai Aono 6e29848608 Add datamodel-code-generator link in pydantic document site (#1532)
* Add datamodel-code-generator link in pydantic document site.

* tweak menu

* fix blank lines

Co-authored-by: Samuel Colvin <samcolvin@gmail.com>
Co-authored-by: Samuel Colvin <s@muelcolvin.com>
2020-05-31 15:23:20 +01:00

1.6 KiB

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-generato

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:

{!.tmp_examples/generate_models_person_model.py!}

More information can be found on the official documentation