In Spring Boot, you can call multiple APIs in parallel and then work on the combined response using CompletableFuture
and CompletableFuture.allOf()
. Here’s an example of how you can achieve this:
- Create a Service to Call APIs: Create a service class that will be responsible for calling the APIs. You can use
RestTemplate
orWebClient
for making HTTP requests.
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class ApiService {
private final RestTemplate restTemplate;
public ApiService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public String callApi1() {
// Make HTTP request for API 1
return restTemplate.getForObject("API_1_URL", String.class);
}
public String callApi2() {
// Make HTTP request for API 2
return restTemplate.getForObject("API_2_URL", String.class);
}
}
2. Create a Controller to Trigger Parallel API Calls: Create a controller class that will trigger parallel API calls and work on the combined response.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.CompletableFuture;
@RestController
@RequestMapping("/api")
public class ApiController {
@Autowired
private ApiService apiService;
@GetMapping("/combinedResponse")
public String getCombinedResponse() {
// Start two asynchronous API calls
CompletableFuture<String> api1Response = CompletableFuture.supplyAsync(() -> apiService.callApi1());
CompletableFuture<String> api2Response = CompletableFuture.supplyAsync(() -> apiService.callApi2());
// Combine responses when both are completed
CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(api1Response, api2Response);
// Wait for both API calls to complete
combinedFuture.join();
// Get results from both CompletableFuture
String api1Result = api1Response.join();
String api2Result = api2Response.join();
// Work on the combined response
String combinedResponse = api1Result + api2Result;
return combinedResponse;
}
}
3. Configure RestTemplate: Make sure to configure RestTemplate
in your application. You can do this by adding @
Bean
in a configuration class:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class AppConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
Make sure you have the necessary dependencies in your project, including Spring Web.
This example demonstrates how to call two APIs in parallel and work on the combined response. Adjust the code according to your specific requirements and handle exceptions appropriately.