1

Can we provide both Json response as well as a csv file as attachment in a Rest Service?

I have written a code like below, but I am also sure its not going to work.

            ResponseBuilder responseBuilder = null;
        responseBuilder = Response.status(200).type(MediaType.APPLICATION_JSON)
                .entity(parseOrganizations(getOrganizationsResponseMashery(limit, offset)));
         responseBuilder.type(MediaType.TEXT_PLAIN).entity(file).header("Content-Disposition", "attachment; filename=Organizations.csv");
        return responseBuilder.build();

The second setter for entity with file, basically over writes the json content that I had inserted earlier as entity. So please suggest.

Anil Kumar P
  • 541
  • 1
  • 9
  • 27
  • I think the following [solution](https://stackoverflow.com/a/68641098/4507034) is what you are looking for. – Radu Linu Aug 03 '21 at 18:34

1 Answers1

1

Yes, that's right, an HTTP response should be of a single type. If you are telling you return JSON, then the client will be expecting a JSON object, not a file. And similarly, if you say you return a file, it will be expecting a file.

The client will be taking an action based on the return type stated in the response headers (Eg: Mapping a JSON object to a class instance, etc.), so it is important this is unambiguous.

In the case of springboot, it appears the last call to the type method overwrites an previous one.

MrD
  • 4,986
  • 11
  • 48
  • 90
  • HTTP response type also has "multipart_mixed" right? so is there anyway we can achieve this scenario using that. – Anil Kumar P Dec 19 '19 at 10:45
  • 1
    It is, but as pointed out not all clients will handle it. I was under the impression it was discouraged because of that. See https://stackoverflow.com/questions/50188321/can-i-send-an-excel-file-and-json-body-with-a-description-of-file-in-same-rest-a – MrD Dec 19 '19 at 11:05