JSON to CSV API with Spring RestTemplate

591 views Asked by At

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();
    }
1

There are 1 answers

1
Adrien Villalonga On

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.

public class EmployeeCsvParams {

    /* Fields */
    
    private String email;
    private String json;

    /* Getters and Setters */

    public String getEmail() { return this.email; }
    public void setEmail(String email) { this.email = email; }

    public String getJson() { return this.json; }
    public void setJson(String json) { this.json = json; }

}
@PostMapping("/generateExcel")
public String getEmployeeCsv(@RequestBody EmployeeCsvParams employeeCsvParams) 
{
    /* ... */ 
}