如何在Swagger规范中定义不同示例的数组?

时间:2015-06-19 16:17:47

标签: swagger swagger-ui swagger-2.0 swagger-editor

我尝试使用静态swagger文件来记录API,该文件可以返回一些包含如下所示数组的JSON:

[
  {
    "type": "type A",
    "field A": "this field is specific to type A"
  },
  {
    "type": "type B",
    "field B": "this field is specific to type B"
  }
]

我尝试了几种使用多态或明确定义多个示例来定义规范的方法。这些例子总是看起来像:

[
  {
    "type": "type A",
    "field A": "this field is specific to type A",
    "field B": "this field is specific to type B"
  }
]

或只是:

[
  {
    "type": "type A",
    "field A": "this field is specific to type A"
  }
]

有没有办法在我的swagger规范中定义一个示例,以便swagger-ui显示的示例有效内容将包含一个包含Type A示例的数组和一个B类示例,就像我写的第一个JSON一样?

2 个答案:

答案 0 :(得分:6)

实际上,你可以。在response对象中,将带有数组的examples对象作为mime类型的值。像这样:

    400:
      description: Bad Request
      examples:
        application/json:
          [
            {
              code:10000,
              message:"Missing Input Parameters",
              fieldA: "AAAAA"
            },{
              code:42,
              message:"Ask the question",
              fieldB: "BBBBBB"
            }
          ]
    default:
      description: Unexpected error
      schema:
        $ref: '#/definitions/Error'

答案 1 :(得分:1)

你不能。

每个响应每个mime类型只能定义一个示例:

{
  "description": "A response",
  "schema": {
    "type": "string"
    }
  },
  "examples": {
    "application/json": {
      "name": "Dog"
    },
    "application/xml": {
      "name": "Cat"
    }
  }
}

如果您想要添加完整方案,我建议您在HTML页面中编写(或生成)完整方案示例,并将其与externalDocs相关联。您可以在根,操作,标记和模式中定义externalDoc。