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

Dea*_*ean 5 multipartform-data swagger openapi

我正在尝试为此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
  ...
Run Code Online (Sandbox Code Playgroud)

我的API定义是这样的:

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
  ...
Run Code Online (Sandbox Code Playgroud)

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

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

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

post:
  consumes:
    - multipart/form-data
  produces:
    - application/json
  parameters:
    - in: formData
      name: item1
      type: string
    - in: formData
      name: item2
      type: string
Run Code Online (Sandbox Code Playgroud)

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

Hel*_*len 3

动态表单数据可以使用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
Run Code Online (Sandbox Code Playgroud)


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

{
  "field1": "value1",
  "field2": "value2",
  "field3": "value3"
}
Run Code Online (Sandbox Code Playgroud)

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

在 Swagger UI 中发送动态表单数据