如何使用 swagger/OpenAPI 指定替代响应格式?

编程入门 行业动态 更新时间:2024-10-16 00:24:32
本文介绍了如何使用 swagger/OpenAPI 指定替代响应格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个 swagger.yaml 是这样的:

I have a swagger.yaml something like this:

swagger: "2.0" paths: /something: get: parameters: - name: format in: query type: string pattern: '^(csv|json|xml)$' responses: 200: schema: type: ?

我想根据 format 查询参数的值(例如 localhost/api/something?format=csv)返回不同的格式(csv、json、xml).

And I want to return different formats (csv, json, xml) depending on the value of the format query parameter (eg. localhost/api/something?format=csv).

如何在规范中指定不同的响应格式?

How can I specify the different response formats in the spec?

推荐答案

我找到了一种解决方法,通过提供不同的端点:

I found a workaround, by providing different endpoints:

swagger: "2.0" paths: /something/json: get: produces: - application/json responses: 200: schema: type: object properties: ... /something/csv: get: produces: - text/csv responses: 200: schema: type: string

注意每个 get 内部的不同 produces:,而顶层没有.

Note the different produces: inside each get, and none at the top level.

csv 端点的实际响应标头是:

The actual response header for the csv endpoint is:

Content-Length:64 Content-Type:text/csv; charset=utf-8 Date:Fri, 26 Aug 2016

我也尝试在 yaml 中添加标头(直接在上面的代码之后),但它不会更改实际的响应标头:

I have also tried adding headers to the yaml (straight after the code above), but it doesn't change the actual response header:

headers: Content-type: type: string description: text/csv; charset=utf-8 Content-Disposition: type: string description: attachment; filename=data.csv

在任一端点我都会收到一条控制台消息(我正在使用 connexion 构建它):

At either endpoint I get a console message (I am building this using connexion):

资源解释为 Document,但使用 MIME 类型 application/json 传输,或

资源被解释为 Document,但使用 MIME 类型 text/csv 传输

此外,csv 被解释为要下载的文件,不会显示在浏览器中.

Also, the csv is interpreted as a file to download, not displayed in the browser.

...所以我怀疑我还没有完全正确.

...so I suspect I haven't quite got it right yet.

更多推荐

如何使用 swagger/OpenAPI 指定替代响应格式?

本文发布于:2023-05-23 15:06:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1326442.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   格式   swagger   OpenAPI

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!