Reusing a subset of an enum in OpenAPI (Swagger)

╄→гoц情女王★ 提交于 2020-11-29 10:57:44

问题


I'm trying to achieve an OpenAPI definition where I define a shared, complete list of allowed values as an enum and then use subgroups of the values in different places to show which values are allowed in each case.

Using the example from the enum spec on Swagger.io, if I have a definition like this:

paths:
  /products:
    get:
      parameters:
      - in: query
        name: color
        required: true
        schema:
          $ref: '#/components/schemas/Color'
      responses:
        '200':
          description: OK
components:
  schemas:
    Color:
      type: string
      enum:
        - black
        - white
        - red
        - green
        - blue

then is it possible to define e.g. two different paths that take a color as a parameter, but one of them only accepts black or white whereas the other accepts all colors?


回答1:


There's no good way to reuse a part of an enum. The best way is to define separate enums.


A possible workaround is to use oneOf to "combine" partial enums into the full enum as suggested here. However, oneOf enum schemas probably won't work as enums in Swagger UI and code generators.

components:
  schemas:
    BlackOrWhite:
      type: string
      enum:
        - black
        - white
    Color:
      oneOf:
        - $ref: '#/components/schemas/BlackOrWhite'
        - type: string
          enum:
            - red
            - green
            - blue


Tricks with YAML &anchors and merge keys << will NOT work because YAML only supports merge keys in mappings (objects) but not in sequences (arrays).

# This will NOT work in YAML

components:
  schemas:
    BlackOrWhite:
      type: string
      enum: &BLACK_WHITE
        - black
        - white
    Color:
      type: string
      enum:
        << : *BLACK_WHITE
        - red
        - green
        - blue


来源:https://stackoverflow.com/questions/57507396/reusing-a-subset-of-an-enum-in-openapi-swagger

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!