如何在 swagger 的成功 GET 响应中记录多种内容类型

Paw*_*ski 2 json swagger swagger-ui

假设我们有一个示例 json swagger 规范:

{
"swagger": "2.0",
"info": {
    "version": "1.0.0",
    "title": "Some API"
},
"basePath": "/api/v1",
"consumes": [
    "application/json"
],
"produces": [
    "application/json",
    "text/csv"
],
"paths": {
    "/some/endpoint": {
        "get": {
            "parameters": [
                {
                    "in": "body",
                    "name": "body",
                    "required": false,
                    "schema": {
                      "$ref": "#/definitions/BodyParamsDefinition"
                    }
                }
            ],
            "responses": {
                "200": { ?? } ...
Run Code Online (Sandbox Code Playgroud)

可以生成两种内容类型:

  • 应用程序/json
  • 文本/csv

默认响应GET /some/endpoint是一个 csv 文件,但如果这样使用format查询参数/some/endpoint?format=json,则响应将采用 json 格式。

我很难找到如何以正确的响应完成我的规范。当我使用这种方法时:https : //swagger.io/docs/specification/describing-responses/我收到一个验证错误:...get.responses['200'] should NOT have additional properties

Hel*_*len 5

你快到了,你只需要schema为响应定义一个。这schema定义了与此状态代码关联的所有内容类型的响应结构。

例如,如果操作返回此 JSON:

[
  {
    "petType": "dog",
    "name": "Fluffy"
  },
  {
    "petType": "cat",
    "name": "Crookshanks"
  }
]
Run Code Online (Sandbox Code Playgroud)

和这个CSV:

[
  {
    "petType": "dog",
    "name": "Fluffy"
  },
  {
    "petType": "cat",
    "name": "Crookshanks"
  }
]
Run Code Online (Sandbox Code Playgroud)

你会使用:

petType,name
dog,Fluffy
cat,Crookshanks
Run Code Online (Sandbox Code Playgroud)

更多信息:描述响应


在 OpenAPI 3.0 中,改进了内容类型定义,并且架构可以因内容类型而异:

# YAML
responses:
  200:
    description: OK
    schema:
      type: array
      items:
        type: object
        properties:
          petType:
            type: string
          name:
            type: string
Run Code Online (Sandbox Code Playgroud)


默认响应GET /some/endpoint是一个 csv 文件,但如果这样使用format查询参数/some/endpoint?format=json,则响应将采用 json 格式。

目前无法将特定响应映射到特定操作参数,但 OpenAPI 规范存储库中有几个相关的建议: