Swagger:两个不同对象的模式定义

时间:2017-10-26 09:50:48

标签: json swagger

我必须创建一个API,它可以根据输入参数以两种不同的格式返回JSON对象。假设我们通过" report = monthly"在查询字符串中,输出将如下:

[{
    "Month": "Jan",
    "Details": [{
        "userId": 12345,
        "userName": "ABC"
    }]
}, {
    "Month": "Feb",
    "Details": [{
        "userId": 12346,
        "userName": "ABD"
    }]
}]

如果未传递上述参数,则输出将如下:

{
    "Details": [{
        "userId": 12345,
        "userName": "ABC"
    }, {
        "userId": 12346,
        "userName": "ABD"
    }]
}

如何定义单个API的模式以返回上述格式的JSON?我无法创建2个端点。

1 个答案:

答案 0 :(得分:0)

更简单的方法是将Month定义为可选属性。

paths:
  /report:
    parameters:
      ...
    get:
      responses:
        200:
          description: OK
          schema:
            type: array
            items:
              $ref: '#/definitions/ReportEntry'

definitions:
  ReportEntry:
    type: object
    properties:
      Month:
        type: string
        example: Jan
      Details:
        type: array
        items:
          $ref: '#/definitions/UserInfo'
    required:
      - Details     # <---- "Details" is required, "Month" is optional

  UserInfo:
    type: object
    properties:
      userId:
        type: integer
        example: 12345
      userName:
        type: string
        example: ABC
    required:
      - userId
      - userName