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

好久不见. 提交于 2020-02-19 06:01:23

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/42287298/write-swagger-doc-that-consumes-multiple-content-types-e-g-application-json-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!