Reputation: 420
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?
Upvotes: 0
Views: 1902
Reputation: 642
My suggestions:
Keep the ResponseCSV immutable, no setters, provide constructor !
Change the CSVExportSvc.exportCSV signature to be easier, don't return boolean:
Try to set content type to csv/text.
The interface may be like this:
public interface CSVExportSvc {
public ResponseCSV exportCSV(String sectionTypeName);
}
Upvotes: 1