Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swagger parameters in query and/or body

Our API has such endpoints that support parameters both from the query and from the body at the same time, by merging those two sets of parameters.

For example:

/foo?param1=value1
body: {
    param2=value2
}

The resulting set of parameters would contain two, param1 and param2.

This endpoint could be used as:

/foo?param1=value1&param2=value2

OR

/foo
body: {
    param1=value1,
    param2=value2
}

Is there a way how to specify this 'duality' in Swagger?

UPD
I suppose I should define parameter as both: body and query

in:
  - body
  - query
like image 739
igr Avatar asked Feb 27 '18 16:02

igr


1 Answers

You'll need to define both query parameters and body parameters but mark all of them as optional. Use the operation description to explain that the client can send the parameters in either query string or body.

swagger: '2.0'
...
paths:
  /foo:
    post:
      consumes:
        - application/json
      parameters:
        - in: query
          name: param1
          type: string
          required: false
        - in: query
          name: param2
          type: string
          required: false
        - in: body
          name: body
          required: false
          schema:
            type: object
            properties:
              param1:
                type: string
              param2:
                type: string

Using OpenAPI 3.0, it's a bit more elegant in that you can reuse the same schema for the query string and the request body:

openapi: 3.0.0
...
paths:
  /foo:
    post:
      parameters:
        # This expands into ?param1=value1&param2=value2&...
        - in: query
          name: parameters
          required: false
          schema:
            $ref: '#/components/schemas/Parameters'
          style: form
          explode: true
      requestBody:
        required: false
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/Parameters'
      responses:
        '200':
          description: OK

components:
  schemas:
    Parameters:
      type: object
      properties:
        param1:
          type: string
        param2:
          type: string

Note for Swagger UI users: Serialization of objects into query string seems to be not supported yet as of UI v. 3.11.0.

like image 147
Helen Avatar answered Oct 29 '22 12:10

Helen