GetMapping to produce CSV file using Spring Boot

12,503

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.

Share:
12,503
user2632905
Author by

user2632905

Updated on June 16, 2022

Comments

  • user2632905
    user2632905 almost 2 years

    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.