Skip to content

Enum as separate model #1173

@ghost

Description

Question

Hello. I use the FastAPI framework. Can I extract the enum field as a separate component(with '$ref' in models schema)? I need it because I use the OpenAPI client generator and it generates several enums for each model.

Output of python -c "import pydantic.utils; print(pydantic.utils.version_info())":

             pydantic version: 1.3
            pydantic compiled: False
                 install path: /Users/viktor/.pyenv/versions/3.7.4/envs/orc/lib/python3.7/site-packages/pydantic
               python version: 3.7.4 (default, Oct 23 2019, 14:30:05)  [Clang 11.0.0 (clang-1100.0.33.8)]
                     platform: Darwin-19.2.0-x86_64-i386-64bit
     optional deps. installed: []

Models example:

import pydantic
import enum
import json


class StrEnum(str, enum.Enum):
    A = 'A'
    B = 'B'


class Foo(pydantic.BaseModel):
    int_field: int
    enum_field: StrEnum


class Bar(Foo):
    another_field: str


print(json.dumps({
    'components': {
        'Foo': Foo.schema(),
        'Bar': Bar.schema(),
    }
}))
'''
{
  "components": {
    "Foo": {
      "title": "Foo",
      "type": "object",
      "properties": {
        "int_field": {
          "title": "Int Field",
          "type": "integer"
        },
        "enum_field": {
          "title": "Enum Field",
          "enum": [
            "A",
            "B"
          ],
          "type": "string"
        }
      },
      "required": [
        "int_field",
        "enum_field"
      ]
    },
    "Bar": {
      "title": "Bar",
      "type": "object",
      "properties": {
        "int_field": {
          "title": "Int Field",
          "type": "integer"
        },
        "enum_field": {
          "title": "Enum Field",
          "enum": [
            "A",
            "B"
          ],
          "type": "string"
        },
        "another_field": {
          "title": "Another Field",
          "type": "string"
        }
      },
      "required": [
        "int_field",
        "enum_field",
        "another_field"
      ]
    }
  }
}
'''

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions