【问题标题】:How to describe dynamic form data using OpenAPI (Swagger)?如何使用 OpenAPI (Swagger) 描述动态表单数据?
【发布时间】:2018-09-27 05:57:26
【问题描述】:

我正在尝试为此 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?

【问题讨论】:

    标签: swagger multipartform-data openapi


    【解决方案1】:

    可以使用 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 会将这些值作为单独的表单字段发送:

    【讨论】:

    • 有没有办法为 multipart/form-data 和 format: binary 表示任意键,以允许用户上传任意键控文件?我试过additionalProperties,但没有用。它只是认为它们是字符串。忽略了format: binary
    猜你喜欢
    • 1970-01-01
    • 2018-12-05
    • 2022-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多