Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetMapping to produce CSV file using Spring Boot

I'm writing a spring rest method to get details from database and set it in a response POJO and then return it. Currently I need to produce this response in CSV instead of default json when the URL is hit using POSTMAN or RC like a downloadable CSV file with data. I googled many sites but am not sure of few logics.

  1. Do we need to write business logic to convert pojo class values to csv format or does spring has any conversion mechanism ?
  2. Produces = "text/csv" is being mentioned on many places, does this convert response properly ?

Currently I haven't written any code for CSV conversion.

@GetMapping("/batch/export" , produces="text/csv")
public ResponseEntity<ApplicationResponse> getBatchDetails(
        HttpServletRequest request) {

    ApplicationRequest appRequest = ApplicationServiceMapper.mapRequestFromHttpRequest(request);
    ApplicationResponse response = appService.getDBDetails(appRequest);
    return new ResponseEntity<>(response, HttpStatus.OK);

}

Here response is the one that service returns with all the data in its pojo format and if we do not give produces in annotation then by default spring will return response json. Can someone guide me? Thanks in advance.

like image 808
user2632905 Avatar asked Aug 17 '17 07:08

user2632905


1 Answers

Just using the @GetMapping with produces="text/csv" is not enough. It is only responsible for setting the response header Content-Type: text/csv.

You'll need to add the response as a parameter HttpServletResponse response, convert your POJO into a valid csv file, and only then, write the csv file into the HttpServletResponse.

like image 136
Pedro Tavares Avatar answered Oct 31 '22 12:10

Pedro Tavares