告诉Swagger请求主体可以是单个对象或对象列表 [英] Tell Swagger that the request body can be a single object or a list of objects

查看:365
本文介绍了告诉Swagger请求主体可以是单个对象或对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将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的varargs.

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模式的扩展子集来描述主体有效负载. JSON模式提供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.

这篇关于告诉Swagger请求主体可以是单个对象或对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆