In a Spring Boot application, calling an external REST API is a common task. Depending on whether your application is synchronous or reactive, Spring provides two main tools for this: RestTemplate and WebClient. Hereβs a comprehensive guide to both, with examples.
π₯ Option 1: Using RestTemplate
(Synchronous, Legacy-Friendly)
β
When to Use:
- For simple, blocking HTTP requests
- In traditional Spring MVC applications
π§ Step 1: Add Dependency
Include the Spring Web dependency in your pom.xml
:
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
π§± Step 2: Define a RestTemplate
Bean
java
@Configuration
public class AppConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
π‘ Step 3: Call the API
java
@Service
public class ApiService {
@Autowired
private RestTemplate restTemplate;
public String getDataFromApi() {
String url = "https://api.example.com/data";
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
return response.getBody();
}
}
getForEntity()
performs a GET requestgetBody()
extracts the actual response
π Option 2: Using WebClient
(Asynchronous & Reactive)
β
When to Use:
- In modern apps with non-blocking, asynchronous communication
- If you're using Spring WebFlux
π§ Step 1: Add WebFlux Dependency
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
π§± Step 2: Define a WebClient
Bean
java
@Configuration
public class AppConfig {
@Bean
public WebClient.Builder webClientBuilder() {
return WebClient.builder();
}
}
π‘ Step 3: Call the API
java
@Service
public class ApiService {
@Autowired
private WebClient.Builder webClientBuilder;
public Mono<String> getDataFromApi() {
String url = "https://api.example.com/data";
return webClientBuilder.build()
.get()
.uri(url)
.retrieve()
.bodyToMono(String.class);
}
}
.retrieve()
initiates the call.bodyToMono()
returns a Mono<String>
(a reactive container)
πΉοΈ Use It in a Controller
java
@RestController
@RequestMapping("/api")
public class ApiController {
@Autowired
private ApiService apiService;
@GetMapping("/data")
public Mono<String> getData() {
return apiService.getDataFromApi();
}
}
π§ Summary: RestTemplate vs WebClient
FeatureRestTemplateWebClientTypeSynchronous / BlockingAsynchronous / Non-blockingSuitabilityLegacy / Simple use-casesModern / Reactive appsProject TypeSpring MVCSpring WebFlux / modern MVCPerformanceLess scalableHighly scalableRecommended forOlder or simpler appsNew applications
β
Recommendation:
Use RestTemplate
for simple synchronous tasks or legacy projects.
Use WebClient
for scalable, modern, and non-blocking applications.