Swagger 响应数据 response 里包含动态变化的对象 key 的方法

先说遇到的问题,API 响应数据里的对象 key 是动态变化的:

Swagger 响应数据 response 里包含动态变化的对象 key 的方法

如上图,响应数据里的对象 key 就是某条数据的唯一标识,根据查询参数,返回的响应数据是不同的,所以红框的 key 不是固定的。

大多数情况下,我们只要求 Swagger 数据模型对象 key 是「固定不变」的,下面是「固定不变」的参考写法:

responses:
  200:
    description: 响应成功
    schema:
      type: object
      properties:
        code:
          type: integer
          description: 响应码
        msg:
          type: string
          description: 响应描述
        data:
          type: object
          description: 响应数据
          properties:
            id:
              type: integer
              description: 下载任务id
            task_code:
              type: string
              description: 下载任务唯一标识
            url:
              type: string
              description: 下载任务的下载url
            dir:
              type: string
              description: 下载任务的存储目录
            out:
              type: string
              description: 下载任务的存储文件名
            aria2_status:
              type: string
              description: |
                aria2的状态(<https://aria2.github.io/manual/en/html/aria2c.html#aria2.tellStatus>)
            aria2_gid:
              type: string
              description: aria2的gid
            down_node_server:
              type: string
              description: 下载节点uri

要让 Swagger 的数据模型允许动态变化的对象 key,可以使用 OpenAPI 规范里的 additionalProperties 属性:

responses:
  200:
    description: 响应成功
    schema:
      type: object
      properties:
        code:
          type: integer
          description: 响应码
        msg:
          type: string
          description: 响应描述
        data:
          type: object
          description: 响应数据
          additionalProperties:
            type: object
            description: 下载任务唯一标识
            properties:
              id:
                type: integer
                description: 下载任务id
              task_code:
                type: string
                description: 下载任务唯一标识
              url:
                type: string
                description: 下载任务的下载url
              dir:
                type: string
                description: 下载任务的存储目录
              out:
                type: string
                description: 下载任务的存储文件名
              aria2_status:
                type: string
                description: |
                  aria2的状态(<https://aria2.github.io/manual/en/html/aria2c.html#aria2.tellStatus>)
              aria2_gid:
                type: string
                description: aria2的gid
              down_node_server:
                type: string
                description: 下载节点uri

additionalProperties 属性的用法在我看来和 properties 是一样一样的,只是在 OpenAPI 规范里,使用 additionalProperties 就表示对象的 key 是动态可变的字符串。

使用了 additionalProperties 属性之后,Swagger UI 里的 Model 截图,可以看到对象 key 是 * 符号。

Swagger 响应数据 response 里包含动态变化的对象 key 的方法

参考文章:

本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!