Junior — Middle
How to implement an external service call in a Spring application?
sobes.tech AI
Answer from AI
In a Spring application, to call an external service, the RestTemplate class or the more modern WebClient from Spring WebFlux are usually used.
Example using RestTemplate:
@Autowired
private RestTemplate restTemplate;
public String callExternalService() {
String url = "https://api.example.com/data";
return restTemplate.getForObject(url, String.class);
}
For this, you need to declare a RestTemplate bean in the configuration:
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
If using WebClient (reactive client):
@Autowired
private WebClient webClient;
public Mono<String> callExternalService() {
return webClient.get()
.uri("https://api.example.com/data")
.retrieve()
.bodyToMono(String.class);
}
And the bean:
@Bean
public WebClient webClient() {
return WebClient.create();
}
Thus, for calling an external REST service in a Spring application, it is convenient to use RestTemplate or WebClient.