Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write swagger doc that consumes multiple content types e.g. application/json AND application/x-www-form-urlencoded (w/o duplication)

I'm looking for an elegant way to define an api that can consume JSON data as well as form data. The following snippet works, but it's not elegant and requires all kind of ugly code in the backend. Is there a better way to define this?

What works right now:

paths:
  /pets:
    post:
      consumes:
      - application/x-www-form-urlencoded
      - application/json
      parameters:
      - name: nameFormData
        in: formData
        description: Updated name of the pet
        required: false
        type: string
      - name: nameJSON
        in: body
        description: Updated name of the pet
        required: false
        type: string

Basic idea of how I'd like it to work:

paths:
  /pets:
    post:
      consumes:
      - application/x-www-form-urlencoded
      - application/json
      parameters:
      - name: name
        in: 
        - formData
        - body
        description: Updated name of the pet
        required: true
        type: string

But this doesn't work because the in value must be a string, not an array.

Any good ideas?

like image 331
Scottmas Avatar asked Feb 17 '17 00:02

Scottmas


1 Answers

OpenAPI 2.0

In OpenAPI 2.0, there's no way to describe that. Form and body parameters are mutually exclusive, so an operation can have either form data OR JSON body but not both. A possible workaround is to have two separate endpoints - one for form data and another one for JSON - if that is acceptable in your scenario.

OpenAPI 3.0

Your scenario can be described using OpenAPI 3.0. The requestBody.content.<media-type> keyword is used to define various media types accepted by the operation, such as application/json and application/x-www-form-urlencoded, and their schemas. Media types can have the same schema or different schemas.

openapi: 3.0.0
...
paths:
  /pets:
    post:
      requestBody:
        required: true
        content:

          application/json:
            schema:
              $ref: '#/components/schemas/Pet'

          application/x-www-form-urlencoded:
            schema:
              $ref: '#/components/schemas/Pet'

       responses:
         '200':
            description: OK

components:
  schemas:
    Pet:
      type: object
      properties:
        name:
          type: string
          description: Updated name of the pet
      required:
        - name

Further info:

  • OAS3: Describing Request Body
  • https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#support-for-x-www-form-urlencoded-request-bodies
  • https://blog.readme.io/an-example-filled-guide-to-swagger-3-2/#requestformat
like image 163
Helen Avatar answered Nov 11 '22 11:11

Helen