How to describe a multipart response using OpenAPI

2020-03-24 04:47发布

问题:

I have a service that creates a multipart file containing:

  • a data byte array that represents an image buffer
  • a JSON that represents information about the image (coord, format, etc.)

Is it possible to model this custom response in an OpenAPI (Swagger) definition, using YAML?

回答1:

Multipart responses can be described using OpenAPI 3.0, but not OpenAPI 2.0 (fka Swagger 2.0).

openapi: 3.0.0
...
paths:
  /something:
    get:
      responses:
        '200':
          description: OK
          content:
            multipart/mixed: # <-- Content-Type of the response
              schema:
                type: object
                properties:
                  # Part 1 - application/octet-stream
                  file:  # <-- part name
                    type: string
                    format: binary
                  # Part 2 - application/json
                  metadata:  # <-- part name
                    type: object
                    properties:
                      foo:
                        type: string
                        example: bar
                    required:
                      - foo

              # Optional, see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#encoding-object
              encoding:
                file:
                  ...
                metadata:
                  ... 

The optional encoding key can be used to override the Content-Type for subparts or add headers for subparts (e.g. Content-Disposition).