Create a swagger/open API response with array of un-named objects

梦想的初衷 提交于 2019-12-11 02:59:22

问题


I get the response from an http request in the following form: it is an array of un-named array(s) and object(s). I cannot figure out the proper Swagger (Open API) specification for this case.

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

回答1:


The answer depends on which version of OpenAPI you use.

OpenAPI 3.0 supports oneOf, so it's possible to define multiple schemas for array items:

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 does not support oneOf or mixed types. The most you can do is use the typeless schema, which means the array items can be anything - objects, arrays or primitives - but you can't specify the exact types.

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



回答2:


I found a way, thanks:

"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"
              }
            }
          }]
        }
      }
    }
  }


来源:https://stackoverflow.com/questions/47747563/create-a-swagger-open-api-response-with-array-of-un-named-objects

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