Pydantic model generator for easy conversion of JSON, OpenAPI, JSON Schema, and YAML data sources.

Overview

datamodel-code-generator

This code generator creates pydantic model from an openapi file and others.

Build Status PyPI version Downloads PyPI - Python Version codecov license Code style: black Total alerts Language grade: Python

Help

See documentation for more details.

Supported source types

Implemented list

OpenAPI 3 and JsonSchema

DataType

  • string (include patter/minLength/maxLenght)
  • number (include maximum/exclusiveMaximum/minimum/exclusiveMinimum/multipleOf/le/ge)
  • integer (include maximum/exclusiveMaximum/minimum/exclusiveMinimum/multipleOf/le/ge)
  • boolean
  • array
  • object
String Format
  • date
  • datetime
  • time
  • password
  • email
  • idn-email
  • uuid (uuid1/uuid2/uuid3/uuid4/uuid5)
  • ipv4
  • ipv6
  • hostname
  • decimal

Other schema

  • enum (as enum.Enum or typing.Literal)
  • allOf (as Multiple inheritance)
  • anyOf (as typing.Union)
  • oneOf (as typing.Union)
  • $ref (http extra is required when resolving $ref for remote files.)
  • $id (for JSONSchema)

Installation

To install datamodel-code-generator:

$ pip install datamodel-code-generator

http extra option

If you want to resolve $ref for remote files then you should specify http extra option.

$ pip install datamodel-code-generator[http]

Usage

The datamodel-codegen command:

usage: datamodel-codegen [-h] [--input INPUT] [--url URL]
                         [--http-headers HTTP_HEADER [HTTP_HEADER ...]]
                         [--input-file-type {auto,openapi,jsonschema,json,yaml,dict,csv}]
                         [--openapi-scopes {schemas,paths} [{schemas,paths} ...]]
                         [--output OUTPUT] [--base-class BASE_CLASS]
                         [--field-constraints] [--use-annotated]
                         [--field-extra-keys FIELD_EXTRA_KEYS [FIELD_EXTRA_KEYS ...]]
                         [--field-include-all-keys] [--snake-case-field]
                         [--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-name EMPTY_ENUM_FIELD_NAME]
                         [--class-name CLASS_NAME] [--use-title-as-name]
                         [--custom-template-dir CUSTOM_TEMPLATE_DIR]
                         [--extra-template-data EXTRA_TEMPLATE_DATA]
                         [--aliases ALIASES]
                         [--target-python-version {3.6,3.7,3.8,3.9}]
                         [--wrap-string-literal] [--validation]
                         [--encoding ENCODING] [--debug] [--version]

optional arguments:
  -h, --help            show this help message and exit
  --input INPUT         Input file/directory (default: stdin)
  --url URL             Input file URL. `--input` is ignore when `--url` is
                        used
  --http-headers HTTP_HEADER [HTTP_HEADER ...]
                        Set headers in HTTP requests to the remote host.
                        (example: "Authorization: Basic dXNlcjpwYXNz")
  --input-file-type {auto,openapi,jsonschema,json,yaml,dict,csv}
                        Input file type (default: auto)
  --openapi-scopes {schemas,paths} [{schemas,paths} ...]
                        Scopes of OpenAPI model generation (default: schemas)
  --output OUTPUT       Output file (default: stdout)
  --base-class BASE_CLASS
                        Base Class (default: pydantic.BaseModel)
  --field-constraints   Use field constraints and not con* annotations
  --use-annotated       Use typing.Annotated for Field(). Also, `--field-
                        constraints` option will be enabled.
  --field-extra-keys FIELD_EXTRA_KEYS [FIELD_EXTRA_KEYS ...]
                        Add extra keys to field parameters
  --field-include-all-keys
                        Add all keys to field parameters
  --snake-case-field    Change camel-case field name to snake-case
  --strip-default-none  Strip default None on fields
  --disable-appending-item-suffix
                        Disable appending `Item` suffix to model name in an
                        array
  --allow-population-by-field-name
                        Allow population by field name
  --enable-faux-immutability
                        Enable faux immutability
  --use-default         Use default value even if a field is required
  --force-optional      Force optional for required fields
  --strict-nullable     Treat default field as a non-nullable field (Only
                        OpenAPI)
  --strict-types {str,bytes,int,float,bool} [{str,bytes,int,float,bool} ...]
                        Use strict types
  --disable-timestamp   Disable timestamp on file headers
  --use-standard-collections
                        Use standard collections for type hinting (list, dict)
  --use-generic-container-types
                        Use generic container types for type hinting
                        (typing.Sequence, typing.Mapping). If `--use-standard-
                        collections` option is set, then import from
                        collections.abc instead of typing
  --use-schema-description
                        Use schema description to populate class docstring
  --reuse-model         Re-use models on the field when a module has the model
                        with the same content
  --enum-field-as-literal {all,one}
                        Parse enum field as literal. all: all enum field type
                        are Literal. one: field type is Literal when an enum
                        has only one possible value
  --set-default-enum-member
                        Set enum members as default values for enum field
  --empty-enum-field-name EMPTY_ENUM_FIELD_NAME
                        Set field name when enum value is empty (default: `_`)
  --class-name CLASS_NAME
                        Set class name of root model
  --use-title-as-name   use titles as class names of models
  --custom-template-dir CUSTOM_TEMPLATE_DIR
                        Custom template directory
  --extra-template-data EXTRA_TEMPLATE_DATA
                        Extra template data
  --aliases ALIASES     Alias mapping file
  --target-python-version {3.6,3.7,3.8,3.9}
                        target python version (default: 3.7)
  --wrap-string-literal
                        Wrap string literal by using black `experimental-
                        string-processing` option (require black 20.8b0 or
                        later)
  --validation          Enable validation (Only OpenAPI)
  --encoding ENCODING   The encoding of input and output (default: UTF-8)
  --debug               show debug message
  --version             show version

Example

OpenAPI

# Generate models from a local file.
$ datamodel-codegen --input api.yaml --output model.py
# or directly from a URL.
$ datamodel-codegen --url https://<INPUT FILE URL> --output model.py
api.yaml
openapi: "3.0.0"
info:
  version: 1.0.0
  title: Swagger Petstore
  license:
    name: MIT
servers:
  - url: http://petstore.swagger.io/v1
paths:
  /pets:
    get:
      summary: List all pets
      operationId: listPets
      tags:
        - pets
      parameters:
        - name: limit
          in: query
          description: How many items to return at one time (max 100)
          required: false
          schema:
            type: integer
            format: int32
      responses:
        '200':
          description: A paged array of pets
          headers:
            x-next:
              description: A link to the next page of responses
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Pets"
        default:
          description: unexpected error
          content:
            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}/invocations
                  passthroughBehavior: when_no_templates
                  httpMethod: POST
                  type: aws_proxy
    post:
      summary: Create a pet
      operationId: createPets
      tags:
        - pets
      responses:
        '201':
          description: Null response
        default:
          description: unexpected error
          content:
            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}/invocations
                  passthroughBehavior: when_no_templates
                  httpMethod: POST
                  type: aws_proxy
  /pets/{petId}:
    get:
      summary: Info for a specific pet
      operationId: showPetById
      tags:
        - pets
      parameters:
        - name: petId
          in: path
          required: true
          description: The id of the pet to retrieve
          schema:
            type: string
      responses:
        '200':
          description: Expected response to a valid request
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Pets"
        default:
          description: unexpected error
          content:
            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}/invocations
      passthroughBehavior: when_no_templates
      httpMethod: POST
      type: aws_proxy
components:
  schemas:
    Pet:
      required:
        - id
        - name
      properties:
        id:
          type: integer
          format: int64
        name:
          type: string
        tag:
          type: string
    Pets:
      type: array
      items:
        $ref: "#/components/schemas/Pet"
    Error:
      required:
        - code
        - message
      properties:
        code:
          type: integer
          format: int32
        message:
          type: string
    apis:
      type: array
      items:
        type: object
        properties:
          apiKey:
            type: string
            description: To be used as a dataset parameter value
          apiVersionNumber:
            type: string
            description: To be used as a version parameter value
          apiUrl:
            type: string
            format: uri
            description: "The URL describing the dataset's fields"
          apiDocumentationUrl:
            type: string
            format: uri
            description: A URL to the API console for each API

model.py:

# generated by datamodel-codegen:
#   filename:  api.yaml
#   timestamp: 2020-06-02T05:28:24+00:00

from __future__ import annotations

from typing import List, Optional

from pydantic import AnyUrl, BaseModel, Field


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


class Pets(BaseModel):
    __root__: List[Pet]


class Error(BaseModel):
    code: int
    message: str


class Api(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'
    )


class Apis(BaseModel):
    __root__: List[Api]

Related projects

fastapi-code-generator

This code generator creates FastAPI app from an openapi file.

https://github.com/koxudaxi/fastapi-code-generator

pydantic-pycharm-plugin

A JetBrains PyCharm plugin for pydantic.

https://github.com/koxudaxi/pydantic-pycharm-plugin

PyPi

https://pypi.org/project/datamodel-code-generator

License

datamodel-code-generator is released under the MIT License. http://www.opensource.org/licenses/mit-license

Comments
  • Support generating models from json-schemas defined in multiple files

    Support generating models from json-schemas defined in multiple files

    Is your feature request related to a problem? Please describe. Now the tool cli API supports only single file as input. I'd suggest to extend it to have directory as as option. This would help with generating models from json-schema (or may be even from other formats as well). For example, let's have the following schemas (see below).

    Since the tool doesn't support directory as input I make a separate CLI call for both file. In that case the output would have:

    • model generated from object.json for Object
    • model generated from object.json for referenced Metadata
    • model generated from metadata.json

    Even more, if we have 2 and more files, which, like object.json refer to the same external reference, we will have copy of the model in every output file.

    // object.json
    {
      "$schema": "http://json-schema.org/schema#",
      "type": "object",
      "title": "Object",
      "properties": {
        "metadata": {
          "$ref": "metadata.json#/"
        }
      },
      "required": [
        "metadata",
      ]
    }
    
    // another file in the same dir
    {
      "$schema": "http://json-schema.org/schema#",
      "type": "object",
      "title": "Object",
      "properties": {
        "somefield": {
          "type": "integer"
        }
      },
      "required": [
        "metadata",
      ]
    }
    

    Describe the solution you'd like In the described case I would like to avoid duplicated models output for the references.

    Describe alternatives you've considered May be, another alternative is to recursively call the datamodel-codegen in case of reference to the external file (then even if we had made few calls to generate the same reference from different referees we would just override the previous result in a separate file, instead of generating inline pydantic model-duplicate).

    Additional context Add any other context or screenshots about the feature request here.

    bug released 
    opened by mikhail-sakhnov 37
  • Change install requirements from pinpoint to lower bounds

    Change install requirements from pinpoint to lower bounds

    Hi,

    first of all thank you for the project this looks really interesting!

    Is your feature request related to a problem? Please describe. All the versions in requirements are pinpoint which might cause version conflicts when using this with other packages e.g. fastapi.

    Describe the solution you'd like Instead of pinpoint the pydantic version make it lower bound pydantic[email]>=1.5.1

    enhancement released 
    opened by dennis-wey 26
  • Does not inherit all the classes mentioned in `allOf`

    Does not inherit all the classes mentioned in `allOf`

    Describe the bug It is not extending all the mentioned classes in the allOf attribute of the schema.

    To Reproduce I am running this on the directory: https://github.com/AnalyticalGraphicsInc/czml-writer/tree/master/Schema. But it does not inherit all the classes as I mentioned above. For example, one of the schemas is as follows,

    {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "$id": "https://analyticalgraphicsinc.github.io/czml-writer/Schema/Color.json",
        "title": "Color",
        "description": "A color. The color can optionally vary over time.",
        "allOf": [
            { "$ref": "InterpolatableProperty.json" },
            { "$ref": "DeletableProperty.json" },
            { "$ref": "ValueProperties/RgbaValueProperty.json" },
            { "$ref": "ValueProperties/RgbafValueProperty.json" },
            { "$ref": "ValueProperties/ReferenceValueProperty.json" }
        ],
        "type": [
            "array",
            "object"
        ],
        "items": {
            "$ref": "#"
        },
        "properties": {
            "rgba": {
                "$ref": "Values/RgbaValue.json",
                "description": "The color specified as an array of color components `[Red, Green, Blue, Alpha]` where each component is an integer in the range 0-255."
            },
            "rgbaf": {
                "$ref": "Values/RgbafValue.json",
                "description": "The color specified as an array of color components `[Red, Green, Blue, Alpha]` where each component is a double in the range 0.0-1.0."
            },
            "reference": {
                "$ref": "Values/ReferenceValue.json",
                "description": "The color specified as a reference to another property."
            }
        }
    }
    

    It generates the class as follows:

    # generated by datamodel-codegen:
    #   filename:  Color.json
    #   timestamp: 2021-03-29T05:46:25+00:00
    
    from __future__ import annotations
    
    from typing import Optional
    
    from pydantic import BaseModel, Field
    
    from . import Cylinder, LabelStyle
    
    
    class Color(BaseModel):
        """
        A color. The color can optionally vary over time.
        """
    
        rgba: Optional[Cylinder.RgbaValue] = Field(
            None,
            description='The color specified as an array of color components `[Red, Green, Blue, Alpha]` where each component is an integer in the range 0-255.',
        )
        rgbaf: Optional[Cylinder.RgbafValue] = Field(
            None,
            description='The color specified as an array of color components `[Red, Green, Blue, Alpha]` where each component is a double in the range 0.0-1.0.',
        )
        reference: Optional[LabelStyle.ReferenceValue] = Field(
            None, description='The color specified as a reference to another property.'
        )
    
    

    Expected behavior It should have inherited the classes DeletableProperty and InterpolatableProperty

    Additional context Those classes have been generated and are residing in the same directory. It's just that they are not being imported and inherited.

    released 
    opened by rushabh-v 22
  • Optional not generated for nullable strings in OpenAPI

    Optional not generated for nullable strings in OpenAPI

    Describe the bug

    When using type: string in combination with nullable: true in an OpenAPI specification, the resulting type should be Optional[str] but it is not.

    To Reproduce

    Example schema:

    openapi: 3.0.3
    info:
      version: 1.0.0
      title: testapi
      license:
        name: proprietary
    servers: []
    paths: {}
    components:
      schemas:
        TopLevel:
          type: object
          properties:
            cursors:
              type: object
              properties:
                prev:
                  type: string
                  nullable: true
              required:
              - prev
          required:
          - cursors
    

    Used commandline:

    $ env/bin/datamodel-codegen --input spec.yaml --output test.py
    

    Expected behavior

    The generated class should be

    class Cursors(BaseModel):
        prev: Optional[str]
    

    but currently it is:

    class Cursors(BaseModel):
        prev: str
    

    Version:

    • OS: Linux
    • Python version: 3.9
    • datamodel-code-generator version: 0.7.0
    opened by languitar 19
  • testing with https://www.schemastore.org/json/

    testing with https://www.schemastore.org/json/

    Hello,

    thanks again for this piece of software. I have a little project for that I would like to use the code generator. The basic idea is the following:

    1. parse existing data models from https://www.schemastore.org/json/ or ontologies in the form of *.ttl or *.owl to create pydantic models.
    2. create instances of my models from a large dictionary of data
    3. validate the data via pydantic, at least with the build-in validators
    4. store the data in a mongodb based RestAPI, using the pydantic serialization mechanisms.

    As a first step, I was playing around with the data models from https://www.schemastore.org/json expecting them to work out of the box. However, I faced several issues with this:

    1. In most cases the schemas provide titles that cannot directly be parsed as ClassName. This is solvable by creating my own ClassName. By somehow pre-parsing the file and generate my own Name and set it to the parser using the data model generator with CLI. However, in most cases the "Top-Layer" Model does not even be created because one might even be more interested in the underlying submodels the schema consists of.
    2. Furthermore, I experienced that several types are not parsed correctly. Maybe it would be good to use 'Any' as default type instead of simply failing.

    Suggestion to solve:

    • Writing a test that parses a randomized subset of https://www.schemastore.org/json. This would at least provide sophisticated testing data schemas to test for integrity.

    Thanks for your help

    Cheers

    released 
    opened by tstorek 18
  • oneOf items are not parsed recursively

    oneOf items are not parsed recursively

    Describe the bug Given the type Union[int, List[A], B]:

    • A is treated as Any
    • B class is generated empty with extra=allowed

    To Reproduce

    Example schema:

    {"$schema":"http://json-schema.org/draft/2019-09/schema#", "oneOf":[{"type":"integer","$comment":"int"},{"type":"array","items":{"type":"object","properties":{"key":{"type":"object","properties":{"address":{"type":"string","$comment":"address"},"nat":{"type":"string","$comment":"nat"}},"required":["address","nat"],"additionalProperties":false,"$comment":"pair"},"value":{"type":"string","$comment":"nat"}},"required":["key","value"],"additionalProperties":false}}],"$comment":"big_map"}
    

    Used commandline:

    $ datamodel-codegen --input schema.json --output schema.py
    

    Expected behavior All the oneOf sub-schemas are parsed recursively.

    Version:

    • OS: Ubuntu 18
    • Python version: 3.9
    • datamodel-code-generator version: 0.10.2
    released 
    opened by m-kus 15
  • update isort and black

    update isort and black

    Hey @koxudaxi!

    very nice package, thanks a lot for your work on this! I'd like to use it and I am already using the latest version of isort and black. It would be nice if the datamodel-code-generator is compatible with this which is whiy I make this PR.

    From my perspective, this PR can be merged if the CI passes.

    opened by Chilipp 12
  • codegen for enum with empty string

    codegen for enum with empty string

    Is your feature request related to a problem? Please describe.

    Environment

    datamodel-code-generator==0.9.3

    Scenario

    Wanted to generate pydantic models from docker engine API.

    datamodel-codegen --url "https://converter.swagger.io/api/convert?url=https://docs.docker.com/engine/api/v1.30.yaml"

    Note that docker engine api uses openapi 2.0 spec. Therefore, I used converter.swagger.io to translate it into 3.0.0.

    Error message

    Traceback (most recent call last):
      File "<my_path>/python3.7/site-packages/datamodel_code_generator/__main__.py", line 424, in main
        strict_types=config.strict_types,
      File "<my_path>/python3.7/site-packages/datamodel_code_generator/__init__.py", line 311, in generate
        results = parser.parse()
      File "<my_path>/python3.7/site-packages/datamodel_code_generator/parser/base.py", line 386, in parse
        self.parse_raw()
      File "<my_path>/python3.7/site-packages/datamodel_code_generator/parser/openapi.py", line 34, in parse_raw
        [*path_parts, '#/components', 'schemas', obj_name],
      File "<my_path>/python3.7/site-packages/datamodel_code_generator/parser/jsonschema.py", line 997, in parse_raw_obj
        self.parse_obj(name, JsonSchemaObject.parse_obj(raw), path)
      File "<my_path>/python3.7/site-packages/datamodel_code_generator/parser/jsonschema.py", line 1002, in parse_obj
        self.parse_object(name, obj, path)
      File "<my_path>/python3.7/site-packages/datamodel_code_generator/parser/jsonschema.py", line 624, in parse_object
        fields=self.parse_object_fields(obj, path),
      File "<my_path>/python3.7/site-packages/datamodel_code_generator/parser/jsonschema.py", line 571, in parse_object_fields
        field_type = self.parse_enum(field_name, field, [*path, field_name])
      File "<my_path>/python3.7/site-packages/datamodel_code_generator/parser/jsonschema.py", line 820, in parse_enum
        name=self.model_resolver.get_valid_name(field_name),
      File "<my_path>/python3.7/site-packages/datamodel_code_generator/reference.py", line 362, in get_valid_name
        if name[0] == '#':
    IndexError: string index out of range
    

    Cause

    The docker engine openapi spec defines a schema with an Enum that contains an empty string:

        RestartPolicy:
          type: object
          properties:
            Name:
              type: string
              description: ...
              enum:
              - ""   # here
              - always
              - unless-stopped
              - on-failure
    

    It seems that get_valid_name cannot handle empty strings.

    Describe the solution you'd like

    I've tested the following workaround by changing the function get_valid_name as below.

    def get_valid_name(self, name: str, camel: bool = False) -> str:
        if not name:    # +
            return "_"     # +
        if name.isidentifier():
            return name
        if name[0] == '#':
            name = name[1:]   # note that original error is caused here. 
        ...
    

    The resulting enum is

    class Name(Enum):
        """
            - Empty string means not to restart
        - `always` Always restart
        - `unless-stopped` Restart always except when the user has manually stopped the container
        - `on-failure` Restart only when the container exit code is non-zero
    
        """
    
        _ = ''
        always = 'always'
        unless_stopped = 'unless-stopped'
        on_failure = 'on-failure'
    

    Describe alternatives you've considered

    If we are targeting python 3.8 and above, this issue can be easily mitigated by using --enum-field-as-literal all. Therefore this issue can be resolved by allowing --enum-field-as-literal option in python 3.7 by importing Literal from typing_extensions.

    opened by yuyupopo 11
  • json_schema_data_formats fail when looking up 'array'

    json_schema_data_formats fail when looking up 'array'

    When trying to convert file data.json to model.py, I get a keyerror on line 171 of jsonschema.py when the type in types is 'array'.

    To Reproduce

    Example schema:

    
     
    bug released 
    opened by javierabosch2 10
  • two imports with the same import-name are not distinguised

    two imports with the same import-name are not distinguised

    Describe the bug I am not yet sure how to reproduce which state, as I have two different observation:

    Example 1:

    Generated code:

    from ...apimachinery.pkg.apis.meta import v1
    from ..core import v1
    

    (from: https://github.com/FlorianLudwig/pdk8s/blob/e9b5903c4f8cf584fe60a4a84709a42f7e63b771/pdk8s/gen/io/k8s/api/networking/v1beta1.py#L12)

    Example 2:

    Generated code:

    from ...apimachinery.pkg.apis.meta import v1
    from ..core import v1 as v1_1
    

    (from: https://github.com/FlorianLudwig/pdk8s/blob/e9b5903c4f8cf584fe60a4a84709a42f7e63b771/pdk8s/gen/io/k8s/api/extensions/v1beta1.py)

    In this example, the second import is renamed to avoid the collision but the references are not. Resulting in code trying to access module members that are in v1_1 but refer to v1. (Example)

    Expected behavior

    The second example is a step in the right direction (or maybe import more of the package name, in this example meta.v1 instead of just v1). But the references must be updated.

    Version:

    • datamodel-code-generator: git master
    bug released 
    opened by FlorianLudwig 10
  • Exception: A Parser can not resolve classes when using `$ref` if references are nested

    Exception: A Parser can not resolve classes when using `$ref` if references are nested

    Describe the bug Parser can not resolve classes when using $ref if the path is nested even though the reference is a valid json pointer.

    File "c:\users\sonali.ingale\appdata\local\programs\python\python39\lib\site-packages\datamodel_code_generator\__main__.py", line 281, in main
        generate(
      File "c:\users\sonali.ingale\appdata\local\programs\python\python39\lib\site-packages\datamodel_code_generator\__init__.py", line 259, in generate
        results = parser.parse()
      File "c:\users\sonali.ingale\appdata\local\programs\python\python39\lib\site-packages\datamodel_code_generator\parser\base.py", line 332, in parse
        _, sorted_data_models, require_update_action_models = sort_data_models(
      File "c:\users\sonali.ingale\appdata\local\programs\python\python39\lib\site-packages\datamodel_code_generator\parser\base.py", line 110, in sort_data_models
        return sort_data_models(
      File "c:\users\sonali.ingale\appdata\local\programs\python\python39\lib\site-packages\datamodel_code_generator\parser\base.py", line 110, in sort_data_models
        return sort_data_models(
      File "c:\users\sonali.ingale\appdata\local\programs\python\python39\lib\site-packages\datamodel_code_generator\parser\base.py", line 110, in sort_data_models
        return sort_data_models(
      [Previous line repeated 97 more times]
      File "c:\users\sonali.ingale\appdata\local\programs\python\python39\lib\site-packages\datamodel_code_generator\parser\base.py", line 158, in sort_data_models
        raise Exception(f'A Parser can not resolve classes: {unresolved_classes}.')
    Exception: A Parser can not resolve classes: [class: Person references: {'Dog', 'Cat'}]
    

    To Reproduce

    Example schema:

    
    {
        "$schema": "http://json-schema.org/draft-04/schema#",
        "title": "Person",
        "type": "object",
        "properties": {
            "name": {
                "title": "name",
                "type": "string"
            },
            "pet": {
                "title": "pet",
                "type": "object",
                "oneOf": [
                    {
                        "$ref": "#/definitions/Pets/Cat"
                    },
                    {
                        "$ref": "#/definitions/Pets/Dog"
                    }
                ]
            }
        },
        "definitions": {
            "Pets": {
                "Cat": {
                    "title": "Cat",
                    "type": "object",
                    "required": [
                        "pet_type",
                        "hunts",
                        "age"
                    ],
                    "properties": {
                        "pet_type": {
                            "enum": [
                                "Cat"
                            ]
                        },
                        "hunts": {
                            "type": "boolean"
                        },
                        "age": {
                            "type": "string"
                        }
                    }
                },
                "Dog": {
                    "title": "Dog",
                    "type": "object",
                    "required": [
                        "pet_type",
                        "bark",
                        "breed"
                    ],
                    "properties": {
                        "pet_type": {
                            "enum": [
                                "Dog"
                            ]
                        },
                        "bark": {
                            "type": "boolean"
                        },
                        "breed": {
                            "type": "string"
                        }
                    }
                }
            }
        },
        "additionalProperties": false
    }
    
    

    Used commandline:

    $ datamodel-codegen --input pets.json --input-file-type=jsonschema --output pets.py
    

    Expected behavior I was expecting following things which is working when I do not encapsulate "Cat" and "Dogs" inside "Pet".

    • Create the classes "Cat" and "Dog"
    • Add "pet" attribute with Union of "Cat" and "Dog"

    Version:

    • windows
    • Python version: 3.9.0
    • datamodel-code-generator version:0.6.18

    Additional context I tried to pull the code and run this example but I am getting the same error. I have few large schemas which are encapsulating references for readability. After editing the schema according to datamodel-code-generator, it works wonderfully 👍 . Thanks for this module.

    released 
    opened by sonali686 9
  • Infinite loop in generating models from JSONSchema

    Infinite loop in generating models from JSONSchema

    Describe the bug

    I am trying to produce pydantic models from a JSONSchema file I have. When I try to do this, the process never finishes and just accumulates memory without end. I let it run for a while and it ended up taking up 8+GB of memory. The schema itself is a good handful of megabytes with probably over 10,000 discrete components, which could be a problem, but I believe it should stop eventually.

    Eventually this stack trace is produced with a RecursionError:

    Traceback (most recent call last):
      File "C:\Users\Spencer\repos\redacted\venv\lib\site-packages\datamodel_code_generator\__main__.py", line 626, in main
        generate(
      File "C:\Users\Spencer\repos\redacted\venv\lib\site-packages\datamodel_code_generator\__init__.py", line 384, in generate
        results = parser.parse()
      File "C:\Users\Spencer\repos\redacted\venv\lib\site-packages\datamodel_code_generator\parser\base.py", line 475, in parse
        self.parse_raw()
      File "C:\Users\Spencer\repos\redacted\venv\lib\site-packages\datamodel_code_generator\parser\jsonschema.py", line 1270, in parse_raw
        self._resolve_unparsed_json_pointer()
      File "C:\Users\Spencer\repos\redacted\venv\lib\site-packages\datamodel_code_generator\parser\jsonschema.py", line 1294, in _resolve_unparsed_json_pointer
        self._resolve_unparsed_json_pointer()
      File "C:\Users\Spencer\repos\redacted\venv\lib\site-packages\datamodel_code_generator\parser\jsonschema.py", line 1294, in _resolve_unparsed_json_pointer
        self._resolve_unparsed_json_pointer()
      File "C:\Users\Spencer\repos\redacted\venv\lib\site-packages\datamodel_code_generator\parser\jsonschema.py", line 1294, in _resolve_unparsed_json_pointer
        self._resolve_unparsed_json_pointer()
      [Previous line repeated 957 more times]
      File "C:\Users\Spencer\repos\redacted\venv\lib\site-packages\datamodel_code_generator\parser\jsonschema.py", line 1290, in _resolve_unparsed_json_pointer
        self.parse_json_pointer(self.raw_obj, reserved_ref, path_parts)
      File "C:\Users\Spencer\repos\redacted\venv\lib\site-packages\datamodel_code_generator\parser\jsonschema.py", line 1306, in parse_json_pointer
        self.parse_raw_obj(
      File "C:\Users\Spencer\repos\redacted\venv\lib\site-packages\datamodel_code_generator\parser\jsonschema.py", line 1213, in parse_raw_obj
        self.parse_obj(name, JsonSchemaObject.parse_obj(raw), path)
      File "pydantic\main.py", line 526, in pydantic.main.BaseModel.parse_obj
      File "C:\Users\Spencer\repos\redacted\venv\lib\site-packages\datamodel_code_generator\parser\jsonschema.py", line 208, in __init__
        super().__init__(**data)
      File "pydantic\main.py", line 340, in pydantic.main.BaseModel.__init__
      File "pydantic\main.py", line 1076, in pydantic.main.validate_model
      File "pydantic\fields.py", line 886, in pydantic.fields.ModelField.validate
      File "pydantic\fields.py", line 1021, in pydantic.fields.ModelField._validate_mapping_like
      File "pydantic\fields.py", line 1094, in pydantic.fields.ModelField._validate_singleton
      File "pydantic\fields.py", line 884, in pydantic.fields.ModelField.validate
      File "pydantic\fields.py", line 1094, in pydantic.fields.ModelField._validate_singleton
      File "pydantic\fields.py", line 884, in pydantic.fields.ModelField.validate
      File "pydantic\fields.py", line 1101, in pydantic.fields.ModelField._validate_singleton
      File "pydantic\fields.py", line 1148, in pydantic.fields.ModelField._apply_validators
      File "pydantic\class_validators.py", line 318, in pydantic.class_validators._generic_validator_basic.lambda13
      File "pydantic\main.py", line 711, in pydantic.main.BaseModel.validate
      File "C:\Users\Spencer\repos\redacted\venv\lib\site-packages\datamodel_code_generator\parser\jsonschema.py", line 208, in __init__
        super().__init__(**data)
      File "pydantic\main.py", line 340, in pydantic.main.BaseModel.__init__
      File "pydantic\main.py", line 1076, in pydantic.main.validate_model
      File "pydantic\fields.py", line 884, in pydantic.fields.ModelField.validate
      File "pydantic\fields.py", line 1101, in pydantic.fields.ModelField._validate_singleton
      File "pydantic\fields.py", line 1148, in pydantic.fields.ModelField._apply_validators
      File "pydantic\class_validators.py", line 318, in pydantic.class_validators._generic_validator_basic.lambda13
      File "pydantic\validators.py", line 61, in pydantic.validators.str_validator
    RecursionError: maximum recursion depth exceeded while calling a Python object
    
    **To Reproduce**

    The schema is too large to put in the issue, but it can be found in this gist.

    Used commandline:

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

    Expected behavior

    The expectation is that the model generation eventually completes.

    Version:

    • OS: Windows 10 22H2 (build 19045.2364)
    • Python version: 3.10.2
    • datamodel-code-generator version: 0.14.1

    Additional context

    The schema itself was created by dynamically generating pydantic models and dumping model.json_schema(). Not sure if that's relevant, but in my mind I guess it's not out of the realm of possibility that this could matter.

    opened by spyoungtech 0
  • Bump mkdocs-material from 8.5.11 to 9.0.0

    Bump mkdocs-material from 8.5.11 to 9.0.0

    Bumps mkdocs-material from 8.5.11 to 9.0.0.

    Release notes

    Sourced from mkdocs-material's releases.

    mkdocs-material-9.0.0

    Additions and improvements

    • Added support for rich search previews
    • Added support for tokenizer lookahead
    • Added support for better search highlighting
    • Added support for excluding content from search
    • Added support for configurable search pipeline
    • Added support for offline search via offline plugin
    • Added support for multiple instances of built-in tags plugin
    • Added support for removing copy-to-clipboard button
    • Added support for removing footer navigation
    • Added support for button to view the source of a page
    • Improved readability of query string for search sharing
    • Improved stability of search plugin when using --dirtyreload
    • Improved search result group button, now sticky and stable
    • Updated Norwegian translations
    • Updated MkDocs to 1.4.2

    Removals

    • Removed deprecated alternative admonition qualifiers
    • Removed :is() selectors (in output) for easier overriding
    • Removed .title suffix on translations
    • Removed legacy method for providing page title in feedback URL
    • Removed support for indexing only titles in search
    • Removed support for custom search transforms
    • Removed support for custom search workers
    • Removed temporary snow feature (easter egg)

    Fixes

    • Fixed Norwegian and Korean language code
    • Fixed detection of composition events in search interface
    • Fixed search plugin not using title set via front matter
    • Fixed search highlighting of tags
    • Fixed search sharing URL using post transformed string
    • Fixed theme-color meta tag getting out-of-sync with palette toggle
    • Fixed prev/next page keyboard navigation when footer is not present
    • Fixed overflowing navigation tabs not being scrollable
    • Fixed inclusion of code block line numbers from search

    mkdocs-material-9.0.0b4

    Note: this is a beta release – see #4714

    • Improved readability of search sharing link
    • Fixed search highlighting of occurrences found in tags
    • Fixed search sharing link using post transformed string (with wildcards etc.)
    • Fixed inability to query specific fields (e.g. tags:foo or title:bar)
    • Fixed inability to exclude search terms (e.g. -foo or -title:bar)

    ... (truncated)

    Changelog

    Sourced from mkdocs-material's changelog.

    mkdocs-material-9.x.x

    • Removed pipdeptree dependency for info plugin
    • Fixed appearance of linked tags when hovered (9.0.0 regression)
    • Fixed #4810: Abbreviations run out of screen on touch devices

    mkdocs-material-9.0.0 (2023-01-02)

    Additions and improvements

    • Added support for rich search previews
    • Added support for tokenizer lookahead
    • Added support for better search highlighting
    • Added support for excluding content from search
    • Added support for configurable search pipeline
    • Added support for offline search via offline plugin
    • Added support for multiple instances of built-in tags plugin
    • Added support for removing copy-to-clipboard button
    • Added support for removing footer navigation
    • Added support for button to view the source of a page
    • Improved readability of query string for search sharing
    • Improved stability of search plugin when using --dirtyreload
    • Improved search result group button, now sticky and stable
    • Updated Norwegian translations
    • Updated MkDocs to 1.4.2

    Removals

    • Removed deprecated alternative admonition qualifiers
    • Removed :is() selectors (in output) for easier overriding
    • Removed .title suffix on translations
    • Removed legacy method for providing page title in feedback URL
    • Removed support for indexing only titles in search
    • Removed support for custom search transforms
    • Removed support for custom search workers
    • Removed temporary snow feature (easter egg)

    Fixes

    • Fixed Norwegian and Korean language code
    • Fixed detection of composition events in search interface
    • Fixed search plugin not using title set via front matter
    • Fixed search highlighting of tags
    • Fixed search sharing URL using post transformed string
    • Fixed theme-color meta tag getting out-of-sync with palette toggle
    • Fixed prev/next page keyboard navigation when footer is not present
    • Fixed overflowing navigation tabs not being scrollable
    • Fixed inclusion of code block line numbers from search

    mkdocs-material-8.5.11+insiders-4.27.0 (2022-12-20)

    ... (truncated)

    Upgrade guide

    Sourced from mkdocs-material's upgrade guide.

    How to upgrade

    Upgrade to the latest version with:

    pip install --upgrade --force-reinstall mkdocs-material
    

    Show the currently installed version with:

    pip show mkdocs-material
    

    Upgrading from 8.x to 9.x

    This major release includes a brand new search implementation that is faster and allows for rich previews, advanced tokenization and better highlighting. It was available as part of Insiders for over a year, and now that the funding goal was hit, makes its way into the community edition.

    Changes to mkdocs.yml

    content.code.copy

    The copy-to-clipboard buttons are now opt-in and can be enabled or disabled per block. If you wish to enable them for all code blocks, add the following lines to mkdocs.yml:

    theme:
      features:
        - content.code.copy
    

    content.action.*

    A "view source" button can be shown next to the "edit this page" button, both of which must now be explicitly enabled. Add the following lines to mkdocs.yml:

    theme:
      features:
        - content.action.edit
        - content.action.view
    

    navigation.footer

    ... (truncated)

    Commits
    • b95dffa Removed level 1 headline hack in content partial
    • 3901324 Updated .gitignore
    • 3b921f7 Updated copyright year
    • d25326f Updated site description in mkdocs.yml
    • 1b08038 Removed patch-level version spec where not necessary
    • 01b25dd Improved platform information in info plugin
    • fc6a368 Fixed alternative fragments in Mermaid diagrams
    • 23730a1 Merge pull request #4628 from squidfunk/feature/material-v9
    • a8c8583 Fixed hatch
    • 1295539 Added back hatch for release management
    • Additional commits viewable in compare view

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    dependencies 
    opened by dependabot[bot] 1
  • Bump coverage from 7.0.1 to 7.0.2

    Bump coverage from 7.0.1 to 7.0.2

    Bumps coverage from 7.0.1 to 7.0.2.

    Changelog

    Sourced from coverage's changelog.

    Version 7.0.2 — 2023-01-02

    • Fix: when using the [run] relative_files = True setting, a relative [paths] pattern was still being made absolute. This is now fixed, closing issue 1519_.

    • Fix: if Python doesn't provide tomllib, then TOML configuration files can only be read if coverage.py is installed with the [toml] extra. Coverage.py will raise an error if TOML support is not installed when it sees your settings are in a .toml file. But it didn't understand that [tools.coverage] was a valid section header, so the error wasn't reported if you used that header, and settings were silently ignored. This is now fixed, closing issue 1516_.

    • Fix: adjusted how decorators are traced on PyPy 7.3.10, fixing issue 1515_.

    • Fix: the coverage lcov report did not properly implement the --fail-under=MIN option. This has been fixed.

    • Refactor: added many type annotations, including a number of refactorings. This should not affect outward behavior, but they were a bit invasive in some places, so keep your eyes peeled for oddities.

    • Refactor: removed the vestigial and long untested support for Jython and IronPython.

    .. _issue 1515: nedbat/coveragepy#1515 .. _issue 1516: nedbat/coveragepy#1516 .. _issue 1519: nedbat/coveragepy#1519

    .. _changes_7-0-1:

    Commits
    • 2f731e2 docs: sample HTML
    • dbbd5b7 docs: prep for 7.0.2
    • d08e6d0 fix: relative_files should keep relative path maps. #1519
    • 3f0bce2 mypy: partial debug.py and pytracer.py
    • ffc701a mypy: test_xml.py
    • 5580cf8 mypy: xmlreport.py
    • 0c9b5e0 mypy: check collector.py and plugin_support.py
    • 8f4d404 refactor: a better way to filter coverage debug pybehave
    • a3f3841 mypy: add cmdline.py and test_cmdline.py
    • 09f9188 mypy: add env.py
    • Additional commits viewable in compare view

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    dependencies 
    opened by dependabot[bot] 1
  • Add support for Discriminator Object

    Add support for Discriminator Object

    Is your feature request related to a problem? Please describe. We need to have correct support of discriminator object type. At the moment the behavior differs from the required one, instead of adding the discirminator attribute to the field, a dictionary with links to schemas is created:

    # wrong autogenerated code
    Field(
        ...,
        discriminator={
                    "propertyName": "type",
                    "mapping": {
                        "type1": "#/components/schemas/Schema1",
                        "type2": "#/components/schemas/Schema2",
                        "type3": "#/components/schemas/Schema3",
                    },
                },
    )
    

    Describe the solution you'd like As an example, take a look at a piece of the api specification and the resulting code:

    OpenAPI

        Schema:
          oneOf:
            - $ref: "#/components/schemas/Schema1"
            - $ref: "#/components/schemas/Schema2"
            - $ref: "#/components/schemas/Schema3"
          discriminator:
            propertyName: type
            mapping:
              type1: "#/components/schemas/Schema1"
              type2: "#/components/schemas/Schema2"
              type3: "#/components/schemas/Schema3"
    

    Generated pydantic model

    class OptimizationSimulationParametersSchema(BaseModel):
        __root__: Union[
            Schema1,
            Schema2,
            Schema3,
        ] = Field(..., discriminator="type")
    

    Additional info Link to specification https://spec.openapis.org/oas/v3.0.3#discriminator-object

    bug 
    opened by anton-petrov 0
  • patternProperties is broken when used by reference

    patternProperties is broken when used by reference

    Describe the bug When patternProperties is inside a reference object, the generated classes are wrongly generated.

    In this example, I created a json schema where:

    • KeyWithExplicitPatternProperties has explicit patternProperties
    • KeyWithPatternPropertiesByReference is the same as KeyWithExplicitPatternProperties, but it uses a $ref to define the same object as KeyWithExplicitPatternProperties
    • SomeOtherBoringReference is just a boring $ref with a trivial object that is correctly parsed.

    This way we can see that KeyWithPatternPropertiesByReference fails to correctly create the class. It looks related to the $ref invocation since everything else is the same.

    To exemplify, I created a patternProperty that makes a json valid when the key is one letter and one char, like so:

    
    {
    	"KeyWithExplicitPatternProperties": {
    		"a1": "foo"
    	},
    	"KeyWithPatternPropertiesByReference": {
    		"a2": "bar"
    	},
    	"SomeOtherBoringReference": {
    		"timeout": 42
    	}
    }
    

    To Reproduce

    Example schema:

    
    {
      "$defs": {
        "stt": {
          "additionalProperties": false,
          "description": "STT properties allows to configure how the user voice is converted to text",
          "properties": {
            "timeout": {
              "title": "STT Timeout",
              "type": "number"
            }
          },
          "title": "Speech to text Settings",
          "type": "object"
        },
        "textResponse": {
          "additionalProperties": false,
          "type": "object",
          "patternProperties": {
            "^[a-z]{1}[0-9]{1}$": {
              "phoneNumber": {
                "additionalProperties": false,
                "type": "number"
              }
            }
          }
        }
      },
      "$schema": "http://json-schema.org/draft-07/schema",
      "additionalProperties": false,
      "description": "The root schema comprises the entire JSON document",
      "properties": {
        "KeyWithExplicitPatternProperties": {
          "additionalProperties": false,
          "type": "object",
          "patternProperties": {
            "^[a-z]{1}[0-9]{1}$": {
              "phoneNumber": {
                "additionalProperties": false,
                "type": "number"
              }
            }
          }
        },
        "KeyWithPatternPropertiesByReference": {
          "$ref": "#/$defs/textResponse"
        },
        "SomeOtherBoringReference": {
          "$ref": "#/$defs/stt"
        }
      },
      "title": "SomeSchema Schema",
      "type": "object"
    }
    

    Used commandline:

    $ datamodel-codegen --use-double-quotes
    

    Expected behavior

    I would expect that KeyWithPatternPropertiesByReference is created the same way as KeyWithExplicitPatternProperties

    Version:

    • OS: Fedora release 37 (Thirty Seven)
    • Python version: 3.10.8
    • datamodel-code-generator version: 0.14.0

    Additional context

    Generated classes

    # generated by datamodel-codegen:
    #   filename:  v1.json
    #   timestamp: 2022-12-13T16:49:55+00:00
    
    from __future__ import annotations
    
    from typing import Any, Dict, Optional
    
    from pydantic import BaseModel, Extra, Field, constr
    
    
    class Stt(BaseModel):
        class Config:
            extra = Extra.forbid
    
        timeout: Optional[float] = Field(None, title="STT Timeout")
    
    
    class TextResponse(BaseModel):
        pass
    
        class Config:
            extra = Extra.forbid
    
    
    class ConversationV1(BaseModel):
        class Config:
            extra = Extra.forbid
    
        KeyWithExplicitPatternProperties: Optional[Dict[constr(regex=r"^[a-z]{1}[0-9]{1}$"), Any]] = None
        KeyWithPatternPropertiesByReference: Optional[TextResponse] = None
        SomeOtherBoringReference: Optional[Stt] = None
    

    To test, we can see that:

    
    valid_object1 = {"KeyWithExplicitPatternProperties": {"a1": "foo"}, "SomeOtherBoringReference": {"timeout": 42}}
    
    conv1 = ConversationV1.parse_obj(valid_object1)
    
    valid_object2 = {
        "KeyWithExplicitPatternProperties": {"a1": "foo"},
        "KeyWithPatternPropertiesByReference": {"a2": "bar"},
    }
    
    conv2 = ConversationV1.parse_obj(valid_object2)
    

    conv1 is correctly parsed, but conv2 throws an Exception:

      File "/home/luminoso/scotty/bitbucket/stagger/src/gendatamodels/v1_gen.py", line 44, in <module>
        conv2 = ConversationV1.parse_obj(valid_object2)
      File "pydantic/main.py", line 526, in pydantic.main.BaseModel.parse_obj
      File "pydantic/main.py", line 342, in pydantic.main.BaseModel.__init__
    pydantic.error_wrappers.ValidationError: 1 validation error for ConversationV1
    KeyWithPatternPropertiesByReference -> a2
      extra fields not permitted (type=value_error.extra)
    

    Which is expected for the generated classes, but not for the schema.

    I also validated the schema in https://www.jsonschemavalidator.net/

    bug 
    opened by luminoso 0
  • Field Argument 'discriminator' has incorrect type (expected str, got dict)

    Field Argument 'discriminator' has incorrect type (expected str, got dict)

    Thanks for a great project

    Describe the bug Argument 'discriminator' has incorrect type (expected str, got dict) The structure of dict generated and assigned to the discriminator :

    my_project/models/fhir.py:560: in Model
        ] = Field(
    E   TypeError: Argument 'discriminator' has incorrect type (expected str, got dict)
    

    To Reproduce

    
    wget https://build.fhir.org/fhir.schema.json.zip
    unzip fhir.schema.json.zip
    datamodel-codegen --input fhir.schema.json --input-file-type jsonschema --output fhir.py
    
    sed -n '556, 570 p' fhir.py 
    
    >>>
    
            Transport,
            ValueSet,
            VerificationResult,
            VisionPrescription,
        ] = Field(
            ...,
            description='see http://hl7.org/fhir/json.html#schema for information about the FHIR Json Schemas',
            discriminator={
                'propertyName': 'resourceType',
                'mapping': {
                    'Account': '#/definitions/Account',
                    'ActivityDefinition': '#/definitions/ActivityDefinition',
                    'ActorDefinition': '#/definitions/ActorDefinition',
                    'AdministrableProductDefinition': '#/definitions/AdministrableProductDefinition',
                    'AdverseEvent': '#/definitions/AdverseEvent',
    
    
    

    Version:

    $ pip freeze | grep code
    datamodel-code-generator==0.14.0
    $ pip freeze | grep pydantic
    pydantic==1.10.2
    $ python3 --version
    Python 3.9.12
    
    
    bug 
    opened by bwalsh 0
Releases(0.14.1)
  • 0.14.1(Dec 28, 2022)

    What's Changed

    • Fix deprecation warnings around "copy_on_model_validation" by @Dominic-Walther in https://github.com/koxudaxi/datamodel-code-generator/pull/927
    • Fix dev black version for macos by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/941
    • Add support for tags and include responses without content by @Aedial in https://github.com/koxudaxi/datamodel-code-generator/pull/924
    • Fix indents for multi-line docstrings by @Dominic-Walther in https://github.com/koxudaxi/datamodel-code-generator/pull/938
    • Allow to pass extra fields using --allow-extra-fields by @fgebhart in https://github.com/koxudaxi/datamodel-code-generator/pull/949
    • Fix resolving id by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/963
    • fix: template handling of extra template data by @auphofBSF in https://github.com/koxudaxi/datamodel-code-generator/pull/861
    • Avoid field name beginning with an underscore by @ronlib in https://github.com/koxudaxi/datamodel-code-generator/pull/962
    • Support --special-field-name-prefix option by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/966
    • Fix allOf with common prefix and $ref by @azatoth in https://github.com/koxudaxi/datamodel-code-generator/pull/968
    • Update poetry.lock by @fsecada01 in https://github.com/koxudaxi/datamodel-code-generator/pull/936
    • Add collapse root model feature by @i404788 in https://github.com/koxudaxi/datamodel-code-generator/pull/933
    • add --capitalise-enum-members option by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/970
    • Fix no generated enum in array by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/971

    New Contributors

    • @Aedial made their first contribution in https://github.com/koxudaxi/datamodel-code-generator/pull/924
    • @fgebhart made their first contribution in https://github.com/koxudaxi/datamodel-code-generator/pull/949
    • @lgtm-com made their first contribution in https://github.com/koxudaxi/datamodel-code-generator/pull/908
    • @auphofBSF made their first contribution in https://github.com/koxudaxi/datamodel-code-generator/pull/861
    • @ronlib made their first contribution in https://github.com/koxudaxi/datamodel-code-generator/pull/962
    • @azatoth made their first contribution in https://github.com/koxudaxi/datamodel-code-generator/pull/968
    • @fsecada01 made their first contribution in https://github.com/koxudaxi/datamodel-code-generator/pull/936
    • @i404788 made their first contribution in https://github.com/koxudaxi/datamodel-code-generator/pull/933

    Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.14.0...0.14.1

    Source code(tar.gz)
    Source code(zip)
  • 0.14.0(Nov 18, 2022)

    What's Changed

    • Drop python3.6 support by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/887
    • Support Python 3.11 by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/898
    • Show help when no input by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/911
    • Add docker image by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/919
    • Implement field descriptions as docstrings by @Dominic-Walther in https://github.com/koxudaxi/datamodel-code-generator/pull/918
    • Fix push docker flow by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/925

    New Contributors

    • @Dominic-Walther made their first contribution in https://github.com/koxudaxi/datamodel-code-generator/pull/918

    Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.13.5...0.14.0

    Source code(tar.gz)
    Source code(zip)
  • 0.13.5(Nov 6, 2022)

    What's Changed

    • Fix mro field on enum by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/891
    • Fix openapi definitions schema by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/897
    • Fix generating import statement code by @antxln in https://github.com/koxudaxi/datamodel-code-generator/pull/893

    New Contributors

    • @antxln made their first contribution in https://github.com/koxudaxi/datamodel-code-generator/pull/893

    Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.13.4...0.13.5

    Source code(tar.gz)
    Source code(zip)
  • 0.13.4(Oct 31, 2022)

    What's Changed

    • Fix alias modular default enum member by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/888

    Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.13.3...0.13.4

    Source code(tar.gz)
    Source code(zip)
  • 0.13.3(Oct 27, 2022)

    What's Changed

    • Fix modular default enum member by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/876
    • Use format of object if provided by @pn in https://github.com/koxudaxi/datamodel-code-generator/pull/874
    • Support union operator | by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/884

    New Contributors

    • @pn made their first contribution in https://github.com/koxudaxi/datamodel-code-generator/pull/874

    Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.13.2...0.13.3

    Source code(tar.gz)
    Source code(zip)
  • 0.13.2(Oct 17, 2022)

    What's Changed

    • Use default of $ref on enum by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/832
    • Fix class name generator by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/841
    • Replace exponential in name for FieldnameResolver by @PTank in https://github.com/koxudaxi/datamodel-code-generator/pull/833
    • Support discriminators by @bernardoVale in https://github.com/koxudaxi/datamodel-code-generator/pull/838
    • add pre-commit for black and isort by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/865
    • Support Boolean property by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/872
    • fix(format): Fix PythonVersion.has_literal_type for Python 3.10. by @pawelrubin in https://github.com/koxudaxi/datamodel-code-generator/pull/868

    New Contributors

    • @PTank made their first contribution in https://github.com/koxudaxi/datamodel-code-generator/pull/833
    • @bernardoVale made their first contribution in https://github.com/koxudaxi/datamodel-code-generator/pull/838
    • @pre-commit-ci made their first contribution in https://github.com/koxudaxi/datamodel-code-generator/pull/867
    • @pawelrubin made their first contribution in https://github.com/koxudaxi/datamodel-code-generator/pull/868

    Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.13.1...0.13.2

    Source code(tar.gz)
    Source code(zip)
  • 0.13.1(Aug 11, 2022)

    What's Changed

    • Added IPv4/IPv6Network support. by @ngaranko in https://github.com/koxudaxi/datamodel-code-generator/pull/789
    • added option --use-double-quotes by @nesb1 in https://github.com/koxudaxi/datamodel-code-generator/pull/818
    • Fix deep copy max recursion failure - pydantic 1.9.1 by @eyalmor-ent in https://github.com/koxudaxi/datamodel-code-generator/pull/819

    New Contributors

    • @ngaranko made their first contribution in https://github.com/koxudaxi/datamodel-code-generator/pull/789
    • @nesb1 made their first contribution in https://github.com/koxudaxi/datamodel-code-generator/pull/818
    • @eyalmor-ent made their first contribution in https://github.com/koxudaxi/datamodel-code-generator/pull/819

    Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.13.0...0.13.1

    Source code(tar.gz)
    Source code(zip)
  • 0.13.0(May 27, 2022)

    What's Changed

    • Fix --snake-case-field breaks class_name by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/777

    Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.12.3...0.13.0

    Source code(tar.gz)
    Source code(zip)
  • 0.12.3(May 27, 2022)

    What's Changed

    • Support --original-field-name-delimiter option by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/776

    Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.12.2...0.12.3

    Source code(tar.gz)
    Source code(zip)
  • 0.12.2(May 27, 2022)

    What's Changed

    • Support subclass enum by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/771

    Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.12.1...0.12.2

    Source code(tar.gz)
    Source code(zip)
  • 0.12.1(May 19, 2022)

    What's Changed

    • [FIX] inheritance update refs by @jdkent in https://github.com/koxudaxi/datamodel-code-generator/pull/767
    • Add Python 3.10 to PythonVersion by @sgaist in https://github.com/koxudaxi/datamodel-code-generator/pull/765

    New Contributors

    • @jdkent made their first contribution in https://github.com/koxudaxi/datamodel-code-generator/pull/767
    • @sgaist made their first contribution in https://github.com/koxudaxi/datamodel-code-generator/pull/765

    Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.12.0...0.12.1

    Source code(tar.gz)
    Source code(zip)
  • 0.12.0(Apr 18, 2022)

    What's Changed

    • Fix field constraint value by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/745
    • Correct typo in GitHub Actions black versions by @lafrenierejm in https://github.com/koxudaxi/datamodel-code-generator/pull/744
    • Support unique_items by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/746
    • Fix nested Enum by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/747

    New Contributors

    • @lafrenierejm made their first contribution in https://github.com/koxudaxi/datamodel-code-generator/pull/744

    Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.11.20...0.12.0

    Source code(tar.gz)
    Source code(zip)
  • 0.11.20(Mar 12, 2022)

    What's Changed

    • no use constr when field-constraints by @linshoK in https://github.com/koxudaxi/datamodel-code-generator/pull/726

    New Contributors

    • @linshoK made their first contribution in https://github.com/koxudaxi/datamodel-code-generator/pull/726

    Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.11.19...0.11.20

    Source code(tar.gz)
    Source code(zip)
  • 0.11.19(Feb 8, 2022)

    What's Changed

    • fix booleans literals being converted to int by @koonpeng in https://github.com/koxudaxi/datamodel-code-generator/pull/704
    • feat: Add option to disable tls verification in http request by @jtfidje in https://github.com/koxudaxi/datamodel-code-generator/pull/707

    New Contributors

    • @koonpeng made their first contribution in https://github.com/koxudaxi/datamodel-code-generator/pull/704
    • @jtfidje made their first contribution in https://github.com/koxudaxi/datamodel-code-generator/pull/707

    Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.11.18...0.11.19

    Source code(tar.gz)
    Source code(zip)
  • 0.11.18(Feb 2, 2022)

    What's Changed

    • [Docs] Fix typo by @ijrsvt in https://github.com/koxudaxi/datamodel-code-generator/pull/702
    • [Fix] Support Black 22.1.0 by @ijrsvt in https://github.com/koxudaxi/datamodel-code-generator/pull/701

    New Contributors

    • @ijrsvt made their first contribution in https://github.com/koxudaxi/datamodel-code-generator/pull/702

    Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.11.17...0.11.18

    Source code(tar.gz)
    Source code(zip)
  • 0.11.17(Jan 23, 2022)

    What's Changed

    • do not convert literal int to string for pydantic 1.9.0 or later by @duesenfranz in https://github.com/koxudaxi/datamodel-code-generator/pull/689

    Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.11.16...0.11.17

    Source code(tar.gz)
    Source code(zip)
  • 0.11.16(Jan 17, 2022)

    What's Changed

    • Fix json type form http by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/637
    • Support Python3.10 by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/668
    • GitHub Actions: Add Python 3.10 to the testing by @cclauss in https://github.com/koxudaxi/datamodel-code-generator/pull/605
    • Use Non{Positive,Negative}{Float,Int} in models by @duesenfranz in https://github.com/koxudaxi/datamodel-code-generator/pull/679

    New Contributors

    • @cclauss made their first contribution in https://github.com/koxudaxi/datamodel-code-generator/pull/605
    • @duesenfranz made their first contribution in https://github.com/koxudaxi/datamodel-code-generator/pull/679

    Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.11.15...0.11.16

    Source code(tar.gz)
    Source code(zip)
  • 0.11.15(Nov 29, 2021)

    What's Changed

    • Fix typed-ast by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/626
    • Fix typed_ast dependency with custom mypy by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/634
    • documented installation via pip by @adaamz in https://github.com/koxudaxi/datamodel-code-generator/pull/620
    • Fix typo in argument description by @jacobszpz in https://github.com/koxudaxi/datamodel-code-generator/pull/606
    • Fix parsing of absolute reference URLs by @vesajaaskelainen in https://github.com/koxudaxi/datamodel-code-generator/pull/594

    New Contributors

    • @adaamz made their first contribution in https://github.com/koxudaxi/datamodel-code-generator/pull/620
    • @jacobszpz made their first contribution in https://github.com/koxudaxi/datamodel-code-generator/pull/606
    • @vesajaaskelainen made their first contribution in https://github.com/koxudaxi/datamodel-code-generator/pull/594

    Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.11.14...0.11.15

    Source code(tar.gz)
    Source code(zip)
  • 0.11.14(Sep 30, 2021)

  • 0.11.13(Sep 15, 2021)

  • 0.11.12(Aug 27, 2021)

    • ignore broken regex version [#519]
    • Support --use-annotated [#516]
    • Support --http_headers for authorization [#511]
    • Add --use-title-as-name [#510]
    • Support patternProperties [#509]
    • Fix reuse_model for nested model [#505]
    • Improve supporting json_pointer [#503]
    Source code(tar.gz)
    Source code(zip)
  • 0.11.11(Aug 12, 2021)

  • 0.11.10(Aug 12, 2021)

  • 0.11.9(Jul 31, 2021)

    • Fix setup.py [#473]
    • Support false on additionalProperties [#472] by @reb00ter
    • Support jinja2 version3 [#468]
    • Support PEP-517 [#467]
    • Validate pydantic field name [#465]

    Improve OpenAPI Parser

    • Refactor parse_ref [#449]
    • Fix path objects in openapi [#459]
    • Fix path parameters [#460]
    • Improve resolving response model [#461]
    • Improve OpenAPI parser [#462]

    Thanks to @reb00ter

    Source code(tar.gz)
    Source code(zip)
  • 0.11.8(Jun 11, 2021)

  • 0.11.7(Jun 9, 2021)

  • 0.11.6(May 28, 2021)

  • 0.2.11+backport-1(May 29, 2021)

  • 0.11.5(May 16, 2021)

    • Don't generate enum models that have been swapped by a reused model [#430] by @shnups
    • Pass custom template dir when creating enums [#427] by @shnups

    Thanks to @shnups

    Source code(tar.gz)
    Source code(zip)
  • 0.11.4(May 5, 2021)

Owner
Koudai Aono
I'm a software engineer. I usually use Python, Kotlin, TypeScript, and AWS.
Koudai Aono
Pydocstringformatter - A tool to automatically format Python docstrings that tries to follow recommendations from PEP 8 and PEP 257.

Pydocstringformatter A tool to automatically format Python docstrings that tries to follow recommendations from PEP 8 and PEP 257. See What it does fo

Daniël van Noord 31 Dec 29, 2022
Crystal Smp plugin for show scoreboards

MCDR-CrystalScoreboards Crystal plugin for show scoreboards | Only 1.12 Usage !!s : Plugin help message !!s hide : Hide scoreboard !!s show : Show Sco

CristhianCd 3 Oct 12, 2021
pytorch_example

pytorch_examples machine learning site map 정리자료 Resnet https://wolfy.tistory.com/243 convolution 연산 정리 https://gaussian37.github.io/dl-concept-covolut

injae hwang 1 Nov 24, 2021
A Python validator for SHACL

pySHACL A Python validator for SHACL. This is a pure Python module which allows for the validation of RDF graphs against Shapes Constraint Language (S

RDFLib 187 Dec 29, 2022
This repository outlines deploying a local Kubeflow v1.3 instance on microk8s and deploying a simple MNIST classifier using KFServing.

Zero to Inference with Kubeflow Getting Started This repository houses all of the tools, utilities, and example pipeline implementations for exploring

Ed Henry 3 May 18, 2022
Swagger Documentation Generator for Django REST Framework: deprecated

Django REST Swagger: deprecated (2019-06-04) This project is no longer being maintained. Please consider drf-yasg as an alternative/successor. I haven

Marc Gibbons 2.6k Jan 03, 2023
Build documentation in multiple repos into one site.

mkdocs-multirepo-plugin Build documentation in multiple repos into one site. Setup Install plugin using pip: pip install git+https://github.com/jdoiro

Joseph Doiron 47 Dec 28, 2022
Markdown documentation generator from Google docstrings

mkgendocs A Python package for automatically generating documentation pages in markdown for Python source files by parsing Google style docstring. The

Davide Nunes 44 Dec 18, 2022
MkDocs plugin for setting revision date from git per markdown file

mkdocs-git-revision-date-plugin MkDocs plugin that displays the last revision date of the current page of the documentation based on Git. The revision

Terry Zhao 48 Jan 06, 2023
A curated list of awesome mathematics resources

A curated list of awesome mathematics resources

Cyrille Rossant 6.7k Jan 05, 2023
Openapi-core is a Python library that adds client-side and server-side support for the OpenAPI Specification v3.

Openapi-core is a Python library that adds client-side and server-side support for the OpenAPI Specification v3.

A 186 Dec 30, 2022
MkDocs Plugin allowing your visitors to *File > Print > Save as PDF* the entire site.

mkdocs-print-site-plugin MkDocs plugin that adds a page to your site combining all pages, allowing your site visitors to File Print Save as PDF th

Tim Vink 67 Jan 04, 2023
Automated generation of real Swagger/OpenAPI 2.0 schemas from Django REST Framework code.

drf-yasg - Yet another Swagger generator Generate real Swagger/OpenAPI 2.0 specifications from a Django Rest Framework API. Compatible with Django Res

Cristi Vîjdea 3k Dec 31, 2022
Ultimaker Cura 2 Mooraker Upload Plugin

Klipper & Cura - Cura2MoonrakerPlugin Allows you to upload Gcode directly from Cura to your Klipper-based 3D printer (Fluidd, Mainsailos etc.) using t

214 Jan 03, 2023
DataAnalysis: Some data analysis projects in charles_pikachu

DataAnalysis DataAnalysis: Some data analysis projects in charles_pikachu You can star this repository to keep track of the project if it's helpful fo

9 Nov 04, 2022
Mkdocs obsidian publish - Publish your obsidian vault through a python script

Mkdocs Obsidian Mkdocs Obsidian is an association between a python script and a

Mara 49 Jan 09, 2023
Version bêta d'un système pour suivre les prix des livres chez Books to Scrape,

Version bêta d'un système pour suivre les prix des livres chez Books to Scrape, un revendeur de livres en ligne. En pratique, dans cette version bêta, le programme n'effectuera pas une véritable surv

Mouhamed Dia 1 Jan 06, 2022
Bring RGB to life in Neovim

Bring RGB to life in Neovim Change your RGB devices' color depending on Neovim's mode. Fast and asynchronous plugin to live your vim-life to the fulle

Antoine 40 Oct 27, 2022
Collection of Summer 2022 tech internships!

Collection of Summer 2022 tech internships!

Pitt Computer Science Club (CSC) 15.6k Jan 03, 2023
A simple USI Shogi Engine written in python using python-shogi.

Revengeshogi My attempt at creating a USI Shogi Engine in python using python-shogi. Current State of Engine Currently only generating random moves us

1 Jan 06, 2022