Skip to content

  • Home
    • Featured Questions
    • Latest Updates
  • Subjects
    • Mathematics
    • Science
    • Computers
    • English
    • General Knowledge
    • History
  • Tips & Strategies
    • Test taking strategy
    • Stress Management
    • Time Management
  • Tools & Utilities
    • Generate Speech From Text
    • Change Your Voice
    • Generate Image From Text
    • Compress Your Images
  • Contact
    • Privacy Policy
    • Mission & Vision
  • Toggle search form

How can I call 2 apis in parallel in spring boot and then work on the combined response

Posted on February 2, 2024February 6, 2024 By allexamprep.com No Comments on How can I call 2 apis in parallel in spring boot and then work on the combined response

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:

  1. Create a Service to Call APIs: Create a service class that will be responsible for calling the APIs. You can use RestTemplate or WebClient 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.

Computer QnA Tags:spring boot

Post navigation

Previous Post: LeetCode Hard — Trapping Rain Water
Next Post: Air Pollution MCQ

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Seminar Topic: “Adversarial Machine Learning: Challenges, Defense Mechanisms, and Real-World Implications”
  • Title: Exploring Explainable Artificial Intelligence (XAI) in Deep Learning
  • Project: Simple Weather App with OpenWeatherMap API
  • Project: Web Scraping Quotes with BeautifulSoup
  • Project: Automated Document Summarization with Gensim

Recent Comments

  1. Mystic Knightt on How to get generated id in spring batch template insert
  2. Sachin on How to get generated id in spring batch template insert

Archives

  • February 2024
  • January 2024

Categories

  • Biology
  • Blog
  • Computer QnA
  • LEETCode
  • Projects
  • Privacy Policy
  • Terms Of Service
  • Contact
  • About Us

Copyright © 2025 .

AllExamPrep