How to specify alternative response formats with swagger/OpenAPI?

邮差的信 提交于 2019-12-22 04:49:38

问题


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: ?

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?


回答1:


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          

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

The actual response header for the csv endpoint is:

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

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

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, or

Resource interpreted as Document but transferred with MIME type text/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.



来源:https://stackoverflow.com/questions/39136565/how-to-specify-alternative-response-formats-with-swagger-openapi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!