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.

1
  • I think the following solution is what you are looking for. Commented Aug 3, 2021 at 18:34

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

HTTP response type also has "multipart_mixed" right? so is there anyway we can achieve this scenario using that.
It is, but as pointed out not all clients will handle it. I was under the impression it was discouraged because of that. See stackoverflow.com/questions/50188321/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.