告诉 Swagger 请求正文可以是单个对象或对象列表对象、列表、正文、Swagger

2023-09-07 14:26:19 作者:情能自控

我正在使用 Swagger 和 Scala 来记录我的 REST API.我想为 POST、PUT 和 DELETE 启用批量操作,并希望相同的路由接受单个对象或对象集合作为正文内容.

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.

有没有办法告诉 Swagger 参数是 A 类型值的列表或 A 类型的单个值?

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?

类似于 REST 的可变参数.

Something like varargs for REST.

推荐答案

有没有办法告诉 Swagger 参数是 A 类型值的列表或 A 类型的单个值?

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?

这取决于您使用的是 OpenAPI 3.0 还是 OpenAPI (Swagger) 2.0.

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

OpenAPI 使用 JSON Schema 的扩展子集来描述正文负载.JSON Schema 提供了 oneOfanyOf 关键字来为一个实例定义多个可能的模式.但是,不同版本的 OpenAPI 支持不同的 JSON Schema 关键字集.

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 支持 oneOfanyOf,因此您可以如下描述这样的对象或对象数组:

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'

在上面的示例中,Body 可以是对象 A 或对象数组 A.

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

OpenAPI (Swagger) 2.0 不支持oneOfanyOf.您最多可以使用 无类型架构:

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`

这意味着 Body 可以是任何东西 - 一个对象(任何对象!)、一个数组(包含任何项目!),也可以是一个基元(字符串、数字等).在这种情况下,无法定义确切的 Body 结构.您只能在 description 中口头描述.

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.

您需要使用 OpenAPI 3.0 来定义您的确切场景.

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