0

I am writing a Spring Boot Application in which for a GET API I need to return CSV file as the response. I am looking forward to suggestions on the design of the class(es) and interface to achieve the goal.

My REST controller is as follows.

@GetMapping(value="export")
public ResponseEntity<?> exportCSV(@RequestParam("sectionTypeName") String sectionTypeName) throws Exception {
}

Overall, I need to do the following

a) Fetch the data from the database for sectionTypeName

b) Prepare CSV data

c) Prepare Header

d) Construct ResponseEntity and respond

I am thinking of creating a class for CSV something like below.

public class ResponseCSV {
    @Getter
    private String responseHeader;

    @Getter
    private String response;

    public void ResponseCSV(String fileName) {
        // prepare responseHeader string with
        // file name as value of fileName
    }

    public void setCSVHeader(String header) {
        // Add the header
    }

    public void addCSVRow(String line) {
    }
}

Next, I am planning to write an interface which fetches the data from the database and prepares the CSV.

public interface CSVExportSvc {
    public Boolean exportCSV(ResponseCSV csv, String sectionTypeName);
}

public class CSVExportSvcImpl implements CSVExportSvc {
    public Boolean exportCSV(ResponseCSV csv, String sectionTypeName) {
        // Read all the data
        // Add the header - call csv.setCSVHeader()
        // Iterate over each row and call csv.addCSVRow()
    }
}

In the Rest Controller, based on the exportCSV call, I will call ResponseEntity as follows.

return ResponseEntity.accepted().headers(csv.getresponseHeader()).body(csv.getresponse());

Is this correct approach? Any suggestions?

1 Answer 1

1

My suggestions:

  1. Keep the ResponseCSV immutable, no setters, provide constructor !

  2. Change the CSVExportSvc.exportCSV signature to be easier, don't return boolean:

  3. Try to set content type to csv/text.

The interface may be like this:

public interface CSVExportSvc {
   public ResponseCSV exportCSV(String sectionTypeName);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Fully agree with points 2 and 3. One clarification - Assuming that I can still have methods setCSVHeader and addCSVRow in ResponseCSV.

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.