I want to hit a JSON to CSV API after grabbing a JSON from my own API. The JSON to CSV API requires email and JSON passed in a POST request. Now I am able to store JSON locally but, how do I pass in both the email and JSON in the request and how do I handle the CSV from the response?
Controller
@PostMapping("/generateExcel")
public String getEmployeeCsv(@RequestBody String email) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>(headers);
String json = restTemplate.exchange("http://localhost:8080/SwaggerTest/employees", HttpMethod.GET, entity, String.class).getBody();
entity = new HttpEntity<String>(json, email, headers);
return restTemplate.exchange("https://json-csv.com/api/getcsv", HttpMethod.POST, entity, String.class).getBody();
}
Update:
I created a EmployeeCsvParams
class with email and json String fields as suggested by @Adrien but I still need to handle the CSV from the response.
@PostMapping("/generateExcel")
public String getEmployeeCsv(@RequestBody String email) {
HttpHeaders headers = new HttpHeaders();
EmployeeCsvParams params = new EmployeeCsvParams();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>(headers);
String json = restTemplate.exchange("http://localhost:8080/SwaggerTest/employees", HttpMethod.GET, entity, String.class).getBody();
params.setEmail(email);
params.setJson(json);
HttpEntity<EmployeeCsvParams> entity2 = new HttpEntity<EmployeeCsvParams>(params, headers);
return restTemplate.exchange("https://json-csv.com/api/getcsv", HttpMethod.POST, entity2, String.class).getBody();
}
From spring docs @RequestBody "You can use the @RequestBody annotation to have the request body read and deserialized into an Object through an HttpMessageConverter. ..."
So i assume you can create the object bellow and use it as argument in your endpoint.