3

How can I download a file using Swagger OpenAPI v3 implementation?

I am not able to figure out how to return the actual file content back in the response through my controller. Its literally straightforward without the use of OpenAPI, but here I must use the override method generated through the OpenAPI Interface.

When I hit the endpoint, the file is getting downloaded, but there is no content in that.

Swagger yaml file:

 responses:
        '200':
          description: OK
          content:
            application/octet-stream:
              schema:
                type: string
                format: base64

Spring Boot Controller:

 @Override
    public ResponseEntity<String> getFile(String storageIdentifier) throws IOException {

        return ResponseEntity.ok().contentType(contentType(extension.get().toString()))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
                .body(new String(bytearray));
    }  

When I see the Swagger API documentation, it suggests to use type: string and format: binary (to return a file) or type: string and format: base64 (to return a string)

bad_coder
  • 11,289
  • 20
  • 44
  • 72
Kishore
  • 31
  • 1
  • 4

1 Answers1

1

You need to implement a method or service that will provide the file from storage (I use AWS bucket for example).

Here is how my controller is looking now:

    @Operation(summary = "Download an image.")
  @ApiResponses(value = {
    @ApiResponse(responseCode = "200",
      description = "Successfully downloaded the image",
      content = @Content(mediaType = "application/json",
        schema = @Schema(type = "String", format = "byte")))
  })
  @GetMapping(value = PREFIX + "{articleId}/{fileName}")
  public byte[] download(@PathVariable String articleId, @PathVariable String fileName) {
    return imageService.get(articleId, fileName);
  }

The specfile in Json format (https://stackoverflow.com/a/61334534/3595831). Should look like this:

responses:
    "200":
      description: Successfully downloaded the image
      content:
        application/json:
          schema:
            type: String
            format: byte