如何用OpenAPI/Swagger定义服务器提供URL的二级资源关联?
OpenAPI 关联动态二级资源的实现方式
你可以用**链接对象(Link Object)**来搞定这个需求,不用硬写固定的二级资源路径。具体操作如下:
- 先把二级资源的响应结构抽出来,放到
components/schemas里复用 - 在第一个接口的200响应里添加
links字段,把返回的RefToSecond和二级资源的请求操作关联起来
修改后的示例代码如下:
openapi: 3.0.3 info: title: Minimal Spec for Question. version: 0.0.0 components: schemas: SecondResource: type: object properties: Data: type: integer description: 二级资源返回的数据 example: 12 paths: /firstRefToSecond: get: description: 获取包含二级资源引用的数据集 responses: '200': description: 请求成功 content: application/json: schema: type: object properties: RefToSecond: type: string description: 指向二级资源的URL example: "http://example.org/second" links: GetLinkedSecondResource: description: 通过返回的URL获取对应的二级资源 operationId: fetchSecondResource # 用表达式引用当前响应里的RefToSecond字段值作为请求地址 url: '{ $response.body#/RefToSecond }' # 用动态路径参数表示二级资源的URL不固定 '/{dynamicSecondResourceUrl}': get: operationId: fetchSecondResource description: 通过动态URL访问的二级资源 responses: '200': description: 请求成功 content: application/json: schema: $ref: '#/components/schemas/SecondResource'
核心逻辑是用OpenAPI的表达式语法($response.body#/RefToSecond)引用第一个接口返回的URL,把它作为二级资源请求的地址,这样就不用预先写死二级资源的固定路径,完全通过接口返回的动态URL来关联两者的交互关系。
如果觉得/{dynamicSecondResourceUrl}这个路径占位还是多余,也可以把二级资源的操作定义在components/links里,但上面的方式更符合OpenAPI的规范,能清晰体现二级资源的请求方式和响应结构。
内容的提问来源于stack exchange,提问作者billpg
相关产品推荐
相关产品推荐

