Tell Swagger that the request body can be a single object or a list of objects

独自空忆成欢 提交于 2019-12-05 01:27:07
Mohsen

Is there a way to tell Swagger that a param is either a list of values of type A or a single value of type A?

This depends on whether you use OpenAPI 3.0 or OpenAPI (Swagger) 2.0.

OpenAPI uses an extended subset of JSON Schema to describe body payloads. JSON Schema provides the oneOf and anyOf keywords to define multiple possible schemas for an instance. However, different versions of OpenAPI support different sets of JSON Schema keywords.

OpenAPI 3.0 supports oneOf and anyOf, so you can describe such an object or array of object as follows:

openapi: 3.0.0
...

components:
  schemas:
    A:
      type: object
    Body:
      oneOf:
        - $ref: '#/components/schemas/A'
        - type: array
          items:
            $ref: '#/components/schemas/A'

In the example above, Body can be either object A or an array of objects A.

OpenAPI (Swagger) 2.0 does not support oneOf and anyOf. The most you can do is use a typeless schema:

swagger: '2.0'
...

definitions:
  A:
    type: object
  # Note that Body does not have a "type"
  Body:
    description: Can be object `A` or an array of `A`

This means the Body can be anything - an object (any object!), an array (containing any items!), also a primitive (string, number, etc.). There is no way to define the exact Body structure in this case. You can only describe this verbally in the description.

You'll need to use OpenAPI 3.0 to define your exact scenario.

I don't know if it's possible to annotate your API like that with Swagger. But my suggestion is to simplify/unify your API. If you think about it, if you're going to support bulk (meaning an array of objects) then there's no reason to have a special treatment of a single object. You should just change the API to always take an array and if someone wants to do a single object then thats just the case of a list with a single element object :: Nil.

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