【问题标题】:How can excluding types for array items be defined with OpenAPI/Swagger?如何使用 OpenAPI/Swagger 定义数组项的排除类型?
【发布时间】:2019-06-20 08:00:56
【问题描述】:

Swagger documentation explains how to define arrays that contain mixed types,如["foo", 5, -2, "bar"]。但是,我如何定义一个数组必须包含一个一种类型的项目(字符串,["foo", "bar"])或另一种(整数,[5, -2])?

这个我试过了,但是Swagger UI不能渲染,所以我猜是错的:

      oneOf:
        - items:
          - $ref: '#/components/schemas/SchemaA'
        - items:
          - $ref: '#/components/schemas/SchemaB'

【问题讨论】:

    标签: swagger swagger-ui openapi


    【解决方案1】:

    首先,请记住 oneOf 仅在 OpenAPI 3.0 (openapi: 3.0.0) 中受支持,而在 OpenAPI 2.0 (swagger: '2.0') 中不支持。

    您的场景可以使用oneOf 来定义,如下所示:

    oneOf:
      - type: array
        items:
          type: string
      - type: array
        items:
          type: integer
      - type: array
        items:
          $ref: '#/components/schemas/SchemaA'
    

    在 vanilla JSON Schema 中,type: array 可以从oneOf 中移出并放在oneOf 旁边,但我不确定 OpenAPI 是否允许这样做(OpenAPI 规范对此并不清楚)。

    type: array
    oneOf:
      - items:
          type: string
      - items:
          type: integer
      - items:
          $ref: '#/components/schemas/SchemaA'
    


    我试过了,但是 Swagger UI 不能渲染它

    目前,Swagger UI 不会自动为 oneOfanyOf 模式生成示例(请参阅 this issue)。解决方法是在oneOf 旁边手动添加example

    example: [1, 2, 3]  # <------
    oneOf:
      - type: array
        items:
          type: string
      - type: array
        items:
          type: integer
      - type: array
        items:
          $ref: '#/components/schemas/SchemaA'
    

    【讨论】:

    • 我忘了提到数组是一个对象的属性({my_property: one-of-array}),oneOf 应该在那里工作吗?有了这个,问题不仅是例子。架构选项卡在花括号内显示“oneOf”,因此它看起来像一个对象,而不是数组。
    • 1) 是的,oneOf 可以用作属性架构。只需将oneOf 放置在您通常放置type: ... 的位置即可。 2) “模式选项卡在花括号内显示“oneOf”,因此它看起来像一个对象,而不是数组” - 这就是 Swagger UI 当前显示oneOf/anyOf 模式的方式。有一个现有的功能请求来改进 oneOf/anyOf 渲染 - github.com/swagger-api/swagger-ui/issues/4088
    • 我认为这个问题在最新的 Swagger UI 版本中已经解决了。
    猜你喜欢
    • 1970-01-01
    • 2021-11-14
    • 2016-08-20
    • 2021-02-25
    • 1970-01-01
    • 1970-01-01
    • 2017-05-15
    • 2015-02-20
    • 2019-10-04
    相关资源
    最近更新 更多