8

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?

Helen
  • 87,344
  • 17
  • 243
  • 314
MJV
  • 1,782
  • 2
  • 21
  • 33

1 Answers1

8

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
Helen
  • 87,344
  • 17
  • 243
  • 314
  • Thank you. This confirms my suspicions. I tried using refs and anchors but came up short. I currently have separate enums in different paths and it technically works but in the generated code `path1.BLACK != path2.BLACK` which is not optimal. But I guess I'll have to write some functionality in the path handlers to map the given values to a common shared enum (defined in my own "hand-written" code). – MJV Aug 15 '19 at 11:04
  • 1
    You might be interested in this discussion in the OpenAPI Specification repository: https://github.com/OAI/OpenAPI-Specification/issues/1552 – Helen Aug 15 '19 at 11:15