如何使用 OpenAPI (Swagger) 描述动态表单数据?

How to describe dynamic form data using OpenAPI (Swagger)?

我正在尝试为此 multipart/form-data 请求创建一个 OpenAPI 定义:

curl -X POST \
  http://localhost:1234/api/v1/Submit \
  -H 'cache-control: no-cache' \
  -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \
  -H 'sessionkey: kjYgfORsZ0GeiCls0FcR7w==' \
  -F item1=abc \
  -F item2=def
  -F item3=ghi
  ...

我的API定义是这样的:

post:
  consumes:
    - multipart/form-data
  produces:
    - application/json
  parameters:
    - in: formData
      name: item1
      type: string
    - in: formData
      name: item2
      type: string

它适用于 formData 中的固定字段。

但是,我的表单数据是动态的,我需要能够发送任意键和值。

我尝试更改表单参数以使用数组和 additionalProperties,但它没有产生预期的结果:

- in: formData
  schema:
  additionalProperties:
    type: object

...

- in: formData
  type: array
  items:
    type: string

是否可以使用不同的键和值定义动态 formData?

动态表单数据可以使用 OpenAPI 3.0 定义,但不能使用 OpenAPI 2.0 (Swagger 2.0)。 OpenAPI 2.0 仅支持表单数据中的固定键名称。

在 OpenAPI 3.0 中,您可以使用具有 additionalProperties:

的架构来描述动态表单数据
openapi: 3.0.2
...
servers:
  - url: 'http://localhost:1234/api/v1'
paths:
  /Submit:
    post:
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              # Object properties correspond to form fields
              type: object
              additionalProperties:
                type: string
      responses:
        '200':
          description: OK


在 Swagger UI 中测试请求时,以 JSON 格式输入字段名称和值:

{
  "field1": "value1",
  "field2": "value2",
  "field3": "value3"
}

Swagger UI 会将这些值作为单独的表单字段发送: