【问题标题】:Creating reusable array definitions in swagger在 swagger 中创建可重用的数组定义
【发布时间】:2017-09-07 10:27:13
【问题描述】:

我正在使用 Swagger 2.0 制定 API 的定义/文档优先规范。我已经设法将大多数可重用组件分解为定义部分,但是我无法弄清楚如何为常量数组创建可重用定义。

例如,我有一些会返回图像的路径,比如这个:

paths:
  /resource/{imageId}:
    get:
      produces:
        - image/jpeg
        - image/png
        - image/gif
      parameters: 
        - in: path
          name: imageId
          type: string
          required: true
      responses: 
        200:
          description: Success
          schema:
            type: file

这很好用,但我希望能够为“produces”元素定义一个可重复使用的值数组,这样我就可以为任何会生成图像的路径重复使用相同的列表。

以下似乎是直观的方法,但 swagger 报告 imageMimeTypes 的定义无效:

paths:
  /resource/{imageId}:
    get:
      produces:
        $ref: "#/definitions/imageMimeTypes"
      parameters: 
        - in: path
          name: imageId
          type: string
          required: true
      responses: 
        200:
          description: Success
          schema:
            type: file
definitions:
  imageMimeTypes:
    - image/jpeg
    - image/png
    - image/gif

是否可以为这样的数组创建定义?如果是,应该使用什么语法?

【问题讨论】:

    标签: arrays yaml swagger swagger-2.0


    【解决方案1】:

    首先,如果这些produces 值在大多数 操作中使用,您可以将它们定义为全局produces 并在需要的地方覆盖。

    produces:
      - image/jpeg
      - image/png
      - image/gif
    
    paths:
      /resource/{imageId}:
        get:
          # Inherits global "produces"
          ...
      /something:
        get:
          # Overrides global "produces"
          produces:
            - application/json
          ...
    

    您的第二个示例无效,因为 produces 不能有 $ref 值。但是您可以使用 YAML 锚点来实现类似的效果。请注意,锚点必须在使用前定义,因此您需要将列表放在路径定义的上方。

    x-types:
      imageMimeTypes: &IMAGE-MIME-TYPES
        - image/jpeg
        - image/png
        - image/gif
    
    paths:
      /resource/{imageId}:
        get:
          produces: *IMAGE-MIME-TYPES
          parameters: 
            - in: path
              name: imageId
              type: string
              required: true
          responses: 
            200:
              description: Success
              schema:
                type: file
    

    我将列表放在扩展键 x-types 而不是 definitions 下 1) 因为 definitions 用于输入和输出模型而不是随机列表,以及 2) 防止在大摇大摆的编辑器。

    这适用于(至少)Swagger Editor 和 Swagger UI。

    【讨论】:

    • 谢谢你的回答海伦。看起来使用 YAML 锚对于我们的目的来说很有效。关于指定全局 produces 定义,我应该提到我已经将 application/json 指定为 produces 的全局值,因为这是我的大多数 API 将产生的,但我会有一些路径,像这个,它将返回图像。
    • 另外,感谢您指出这些应该在 x-types 而不是定义中定义。
    猜你喜欢
    • 2015-12-06
    • 2022-08-07
    • 1970-01-01
    • 1970-01-01
    • 2020-10-06
    • 1970-01-01
    • 2015-01-16
    • 2021-07-07
    • 1970-01-01
    相关资源
    最近更新 更多