【问题标题】:Reusing a subset of an enum in OpenAPI (Swagger)在 OpenAPI (Swagger) 中重用枚举的子集
【发布时间】:2019-12-21 18:15:27
【问题描述】:

我正在尝试实现 OpenAPI 定义,其中我将允许值的共享完整列表定义为枚举,然后在不同位置使用值的子组来显示每种情况下允许的值。

使用the enum spec on Swagger.io 中的示例,如果我有这样的定义:

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

那么是否可以定义例如两个不同的路径,它们以颜色作为参数,但其中一个只接受 blackwhite 而另一个接受所有颜色?

【问题讨论】:

    标签: enums swagger openapi


    【解决方案1】:

    没有很好的方法来重用枚举的一部分。最好的方法是定义单独的枚举。


    一种可能的解决方法是使用oneOf 将部分枚举“组合”到完整枚举中作为suggested here。但是,oneOf 枚举模式可能无法在 Swagger UI 和代码生成器中用作枚举。

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


    使用 YAML &anchorsmerge keys << 将不起作用的技巧,因为 YAML 仅支持映射(对象)but not in sequences(数组)中的合并键。

    # 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
    

    【讨论】:

    • 谢谢。这证实了我的猜想。我尝试使用 refs 和 anchors,但没有成功。我目前在不同的路径中有单独的枚举,它在技术上有效,但在生成的代码path1.BLACK != path2.BLACK 中不是最佳的。但我想我必须在路径处理程序中编写一些功能来将给定值映射到一个公共共享枚举(在我自己的“手写”代码中定义)。
    • 您可能对 OpenAPI 规范存储库中的此讨论感兴趣:github.com/OAI/OpenAPI-Specification/issues/1552
    猜你喜欢
    • 2015-02-20
    • 1970-01-01
    • 2021-09-15
    • 2022-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多