如何使用swagger/OpenAPI指定替代响应格式? [英] How to specify alternative response formats with swagger/OpenAPI?

查看:336
本文介绍了如何使用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):

Resource interpreted as Document but transferred with MIME type application/json

Resource interpreted as Document but transferred with MIME type 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指定替代响应格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆