Dean
Dean

Reputation: 678

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?

Upvotes: 7

Views: 9177

Answers (1)

Helen
Helen

Reputation: 97540

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

Upvotes: 3

Related Questions