问题
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