Issue
I have a Spring Boot backend that uses WebClient.Builder to make some third party API calls. The problem I'm having is that I don't know the common/best way to retrieve this data. I make several different API requests, but I have a general helper function makeApiRequest
for handling the WebClient.Builder stuff. My code looks something like this:
@Service
public class DataScraperService{
@Autowired
private WebClient.Builder builder;
private Object makeApiRequest(String apiKey, String uri){
return builder.build()
.get(uri)
.header("API-Key", apiKey)
.retrieve()
.bodyToMono(Object.class)
.block();
}
}
What is the common practice for retrieving the data from the return value of makeApiRequest()? Should I make a POJO for each different API call I'll be making and cast it to that? Or just cast everything to a LinkedHashMap? Or is there something I can do with Spring annotations for this?
Solution
The signature of your helper function shall be like this:
<T> makeApiRequest(String apiKey, String uri, Class<T> respType);
Passing respType to bodyToMono() and you'll get a respType returned.
Answered By - Simon Wong
Answer Checked By - Clifford M. (JavaFixing Volunteer)