Swagger annotations for API that allows downloading files as zip

Swagger annotations for API that allows downloading files as zip
Photo by Asa Akmelia / Unsplash

I have built out an API that allows you downloading log files as zip in a sprint boot app. The app also integrated with Swagger 3, so I also want this API can be hit in the Swagger UI. In this post, I will demonstrate how to use @ApiOperation annotation to tell Swagger UI download the response as a zip file.

use @ApiOperation for your method

The key is set media type to "application/octet-stream" which can be recognized by Swagger UI. By doing so, you are set "accept":"application/octet-stream" in the request header. Put below annotation section on top of your API's controller method.

    		summary = "",
    		description = "",
    		responses = {
                    @ApiResponse(responseCode = "200", description = "", content = {
                                    mediaType = "application/octet-stream"

You also need to set 'produces = {"application/octet-stream"}' in the Mapping annotation. This is to set the response's header with "Content-Type":"application/octet-stream".

@GetMapping(value = "/yourpath", produces = {"application/octet-stream"})

set response Header, "content-disposition": "attachment; filename=xxx.zip"

In a regular HTTP response, the Content-Disposition response header is a header indicating if the content is expected to be displayed inline in the browser, that is, as a Web page or as part of a Web page, or as an attachment, that is downloaded and saved locally.

@GetMapping(value = "/yourpath", produces = {"application/octet-stream"})
public void method(HttpServletResponse response) {
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment; filename=%s.zip", transactionId));

Try it out in Swagger UI

You will be able to see a 'Download file' anchor once the api successfully response you the zip file.
You also be able find in the response headers:
content-disposition: attachment; filename=xxx.zip