javajsonspring-boothttpresponsespring-resttemplate

How to get the response of an API call using Rest Template when the response type is unknown


I have a requirement where I need to fetch the response of various company results. Each company will share a REST API with me (with all the details to invoke the API). I need to read a particular param from the response. The param will be known to me in advance and it might differ for every API.

Since the response for all the APIs will be different, I am looking for a generic method of calling the URL (always GET) and parsing the response in a JSON format and read the output param.

I tried doing the following:

String response = restTemplate.getForObject(URL,request,String.class);

But this fails to invoke the API. I also tried doing:

Object response = restTemplate.getForObject(URL,request,Object.class);

and

JsonNode response = restTemplate.getForObject(URL,request,JsonNode.class);

This also doesn't work. Is there any other way so that I can invoke the API and convert its response in a JSON object and read a particular property of the JSON.

I am not an expert but is this feasible in Java (I have done something similar with JS, but ofcourse it has much relaxed datatypes).

Thanks for any inputs.


Solution

  • This has always worked for me:

    String jsonStr = restTemplate.getForObject (
      "/search?keywords={keywords}",
      String.class,
      "my search string"
    );
    

    Note the match between the {keywords} placeholder and the Java third parameter.

    Your examples look suspect, for they have a request object in a getForObject() method. The latter sends a GET request and it's unusual to pass a request object in this kind of HTTP request. In fact, the method's signature is: getForObject(url, responseType, urlVariables) and other variants, where there isn't any request to be sent.

    So, either you don't actually have a request object (only URL parameters), or you have POST methods, which require restTemplate.postForObject(), or, unlikely, you have a GET method that accept a payload in the request.

    Spring doesn't have a getForObject() variant for the latter case, because, as said, that's unusual. If you really have such a method and you or others don't want to turn it into a POST method (but they should), you should be able to send such a weird request via RestTemplate.exchange() or .execute(), but I've never tried it.

    Once you have the correct method and invocation, the variant asking for a JsonNode should work too.