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 co
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
.
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.