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 是 *
符号。
参考文章:
本文来自博客园,作者:imzhi,转载请注明原文链接:https://www.cnblogs.com/imzhi/p/swagger-response-dynamic-key.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)