对象数组作为招摇中的输入参数招摇、数组、对象、参数

2023-09-08 09:18:44 作者:如履薄冰 Gluttony

我正在尝试用 swagger 描述以下 post 参数:

I'm trying to describe the following post parameter in swagger:

{
    "sources": [
        {
            "id": 101,
            "parentId": 201
        },{
            "id": 102,
            "parentId": 201
        },{
            "id": 102,
            "parentId": 202
        }
    ],
    "destinationId": 301,
    "param1": "value 1",
    "param2": "value 2",
}

问题是 sources 是一个对象数组,swagger 似乎不支持.这是我尝试过的:

The issue is that the sources is an array of objects, that swagger does not seem to support. Here is what I tried:

paths:
    /bulk-action:
        post:
            parameters:
                - name: sources
                  in: formData
                  type: array
                  enum:
                      $ref: '#/definitions/BulkSource'
                - name: destinationId
                  in: formData
                  type: integer
                - name: param1
                  in: formData
                  type: string
                - name: param2
                  in: formData
                  type: string
definitions:
    BulkSource:
        type: object
        properties:
            id:
                type: integer
            parentId:
                type: integer

知道如何解决这个限制吗?

Any idea on how to work around this limitation?

推荐答案

如果我理解正确,您要发布的请求正文是 json 对象,而不是 form.在这种情况下,您的 swagger 文档需要进行如下修改:

If I understand correctly, your request body to post is a json object instead of form. In such case, your swagger document need to be modified as follows:

当请求体为json时,使用in:body的参数代替in:formData的多个参数.如果 inbody,则需要 schema 对象.在schema下定义了json属性.如果 type 属性为 array,则需要 items 对象. When request body is json, a parameter with in: body is used instead of multiple parameters of in: formData. If in is body, a schema object is required. Defined the json properties under schema. If the property type is array, items object is required.

以下是一个例子:

paths:
  /bulk-action:
    post:
      consumes:
        - application/json
      parameters:
        - name: body
          in: body
          schema:
            properties:
              sources:
                type: array
                items:
                  $ref: '#/definitions/BulkSource'
              destinationdId:
                type: integer
      responses:
        200:
          description: OK
definitions:
  BulkSource:
    type: object
    properties:
      id:
        type: integer
      parentId:
        type: integer