Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am using Swagger with Scala to document my REST API. I want to enable bulk operations for POST, PUT and DELETE and want the same route to accept either a single object or a collection of objects as body content.

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?

Something like varargs for REST.

like image 372
bennidi Avatar asked Jul 31 '15 09:07

bennidi


People also ask

How do you pass multiple parameters in Swagger?

A URL can have several path parameters, each denoted with curly braces { } . Each path parameter must be substituted with an actual value when the client makes an API call. In OpenAPI, a path parameter is defined using in: path . The parameter name must be the same as specified in the path.


1 Answers

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.

like image 193
Mohsen Avatar answered Sep 20 '22 17:09

Mohsen