Swagger发送body和formData参数

Joh*_*ohn 16 rest multipartform-data swagger

我正在使用Swagger 2.0,我有一个问题是发送多个帖子参数.我有一个招摇错误Operation cannot have a body parameter and a formData parameter,我不知道如何解决它.在我的定义中,我有一个body参数,这个参数需要一个JSON格式,但是我还有其他参数,比如要上传的文件和文件名.

如何发送body和formData参数呢?

这是Web服务定义:

  /updateDatas:
    post:
      summary: Upadate datas
      description: |
        Update datas
      consumes:
        - multipart/form-data
      produces:
          - application/json
      parameters:
        - name: firstFileName
          in: formData
          description: First file name.
          required: true
          type: string
        - name: secondFileName
          in: formData
          description: Second file name.
          required: true
          type: string
        - name: datas
          in: body
          description: Json object informations.
          required: true
          schema:
            $ref: '#/definitions/Datas'
        - name: firstFile
          in: formData
          description: First file .jpg
          required: true
          type: file
        - name: clientFile
          in: formData
          description: Second file .jpg
          required: true
          type: file
      tags:
        - Application
      responses:
        '200':
          description: Uploaded
          schema:
            $ref: '#/definitions/Upload'
        '401':
          description: Unauthorized Bad Token
Run Code Online (Sandbox Code Playgroud)

小智 10

根据swagger规范,type:bodytype:formData不能同时存在于同一操作中.

  • 那么Open API 3.0.0呢?https://swagger.io/docs/specification/describing-request-body/现在可以使用带有Formdata的JSON吗? (3认同)

Wil*_*eng 8

解决此问题的一种方法是将"datas"设置为带有"file"类型的表单参数.这是一个例子:

  parameters:
    - name: petId
      in: path
      description: ID of pet to update
      required: true
      type: integer
      format: int64
    - name: additionalMetadata
      in: formData
      description: Additional data to pass to server
      required: false
      type: string
    - name: file
      in: formData
      description: file to upload
      required: false
      type: file
Run Code Online (Sandbox Code Playgroud)

参考:https://github.com/swagger-api/swagger-codegen/blob/master/modules/swagger-codegen/src/test/resources/2_0/petstore.yaml#L257

更新:正文参数和表单参数不能共存:https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#parameterObject

Body - 附加到HTTP请求的有效负载.由于只能有一个有效负载,因此只能有一个主体参数.body参数的名称对参数本身没有影响,仅用于文档目的.由于Form参数也在有效负载中,因此对于相同的操作,body和form参数不能一起存在.

  • "文件"类型没有其他办法吗?因为我不想使用文件来传递JSON数据 (2认同)