Swagger 響應數據 response 里包含動態變化的對象 key 的方法


先說遇到的問題,API 響應數據里的對象 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 是 * 符號。

參考文章:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM