Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm trying to create an OpenAPI definition for this multipart/form-data request:

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
  ...

My API definition is like this:

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

It works fine with fixed fields in formData.

However, my form data will be dynamic, and I need to be able to send arbitrary keys and values.

I tried changing form parameters to use an array and additionalProperties, but it does not produce the desired result:

- in: formData
  schema:
  additionalProperties:
    type: object

...

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

Is it possible to define dynamic formData with different keys and values?

like image 853
Dean Avatar asked Nov 07 '22 08:11

Dean


1 Answers

Dynamic form data can be defined using OpenAPI 3.0 but not OpenAPI 2.0 (Swagger 2.0). OpenAPI 2.0 only supports fixed key names in form data.

In OpenAPI 3.0, you can describe dynamic form data using a schema with 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


When testing the request in Swagger UI, enter the fields names and values in the JSON format:

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

Swagger UI will send these values as individual form fields:

Sending dynamic form data in Swagger UI

like image 76
Helen Avatar answered Nov 14 '22 09:11

Helen