使用未命名对象数组创建一个swagger / open API响应

时间:2017-12-11 06:32:08

标签: swagger openapi

我从以下形式的http请求中获得响应:它是一个未命名的数组和对象的数组。对于这种情况,我无法弄清楚正确的Swagger(Open API)规范。

[
  [
    {
      "prop1": "hello",
      "prop2": "hello again"
    },
    {
      "prop1": "bye",
      "prop2": "bye again"
    }
  ],
  {
    "key": 123
  }
]

2 个答案:

答案 0 :(得分:3)

答案取决于您使用的OpenAPI版本。

OpenAPI 3.0 支持oneOf,因此可以为数组项定义多个模式:

openapi: 3.0.0
...

paths:
  /something:
    get:
      responses:
        '200':
          description: success
          content:
            application/json:
              schema:
                type: array
                items:
                  oneOf:   # <---------
                    - type: array
                      items:
                        type: object
                        properties:
                          prop1:
                            type: string
                          prop2:
                            type: string
                    - type: object
                      properties:
                        key:
                          type: integer
                      required:
                        - key

OpenAPI 2.0 不支持oneOf或混合类型。你能做的最多就是使用typeless schema,这意味着数组项可以是任何东西 - 对象,数组或基元 - 但是你不能指定确切的类型。

swagger: '2.0'
...
paths:
  /:
    get:
      produces:
        - application/json
      responses:
        '200':
          description: success
          schema:
            type: array
            items: {}   # <---------

            # Example to display in Swagger UI:
            example:
              - - prop1: hello
                  prop2: hello again
                - prop1: bye
                  prop2: bye again
              - key: 123

答案 1 :(得分:-1)

我找到了办法,谢谢:

"responses": {
      "200": {
        "description": "success",
        "schema": {
          "type": "array",
          "items": [{
           "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "prop1": {
                  "type": "string",
                },
                "prop2": {
                  "type": "string",
                }
              }
            }
          },
          {
            "type": "object",
            "properties": {
              "key": {
                "type": "number"
              }
            }
          }]
        }
      }
    }
  }