This website uses cookies to ensure you get the best experience on our website.

Skip to content
LOGO
  • Company

    About IGNEK

    Learn about our story and our mission.

    Careers

    We're hiring!

    We always looking for talented peoples. Join our team!

    Blogs

    The latest industry news, updates and info.

    Case Studies

    Take a closer look at the projects we've delivered

    Webinar

    Watch our latest organized webinar

    Get in touch with our HR team

    • hr@ignek.com
    • +91 93284 95160
    • Ahmedabad, Gujarat, India – 382470
  • Services

    Enterprise Portal Development

    Custom Enterprise Portal Development for flawless Solutions

    Dedicated Development Team

    Expand Teams, Optimize Development with Our Expertise

    Back-end Development

    Empowering your digital presence with robust backend development expertise

    Front-end Development

    Crafting engaging user experiences through expert frontend development

    Digital Transformation

    Embrace digital transformation by modernizing process

    SaaS Development

    Transform your business with SaaS Innovative Solutions

    Technologies

    Liferay Services

    Development & Customization

    Theme

    Upgradation

    Migration

    Proof of Concept

    Performance Tunning

    Architecture

    Support & Maintenance

    E-commerce

    Expert Advice

    React Services

    Enterprise Development

    Custom Application

    Single Page Application

    Architecture

    API Integration

    Migration

    Consulting

    Maintenance & Support

    Spring Boot Services

    Web Service

    MVC Web Development

    API Integration

    Security

    Migration

    Microservices

    Support & Maintenance

    AEM Services

    Consulting Service

    Site Development

    Migration & Upgradation

    Integration

    Maintenance & Support

    Custom Solutions

    Content Management

    Team Augementation

  • Solution

    Ready for digital excellence

    In our rapidly evolving world, businesses are always on the lookout for fresh ways to improve their operations and connect with their audiences.

    Contact US

    Solutions

    SaaS : Software As A Service

    Transforming industries through cutting edge SaaS solutions.

    Customer Portal : Boost Business Productivity

    Streamline operations and enhance productivity with our Customer Portal solution.

    Liferay Based Intranet Portal

    Internal portal for company communication, collaboration and resources

    Integration

    Matomo Integration with Liferay

    Integrate Matomo to enable user interactions seamlessly.

    Microsoft Teams integration with Liferay

    Integrate to enable seamless collaboration, messaging within your portal.

    Jira Integration With Liferay

    Optimizes business operations by integrating with Jira.

  • Hire Us

    Liferay

    Get expert Liferay developers for seamless portal solutions.

    React JS

    Get expert ReactJS developers for dynamic web solutions.

    Web Developer

    Get custom web solutions from IGNEK's expert developers.

    Spring Boot

    Get top-notch Spring Boot developers for your project success!

    Healthcare

    Get top Healthcare Developers for cutting-edge medical software.

    MERN Stack

    Get expert MERN developers from IGNEK for custom, innovative project solutions.

    Why Hire Developers From IGNEK ?

    • Certified Developer
    • Transparent Communication
    • Flexible Hiring Modals
    • Fully Signed NDA
    • Cost Effective
    • Easy Exit Policy

    Get in touch with our Sales team

    • sales@ignek.com
    • +91 6351576580
    • info@ignek.com
    • Ahmedabad, Gujarat, India – 382470
SCHEDULE CALL
  • COMPANY
    • About
    • Case Studies
    • Blogs
    • Career
    • Webinar
  • SERVICES
    • Enterprise Portal Development
    • Dedicated Development Team
    • Back-end Development
    • Front-end Development
    • Digital Transformation
    • SaaS Development
  • SOLUTION
    • Customer Portal:  Boost Business Productivity
    • SaaS : Software as a Service
    • Liferay Based Employee Intranet Portal
  • TECHNOLOGY
    • Liferay Services
      • Liferay Development and Customization
      • Liferay Theme Development Service
      • Liferay DXP 7.4 Upgrade
      • Liferay Migration
      • Liferay Proof Of Concept
      • Liferay Performance Tuning
      • Liferay Architecture Design Service
      • Liferay Support And Maintenance Service
      • Liferay Ecommerce Development
      • Liferay Expert Advice
    • ReactJS Services
      • ReactJS Enterprise Application Development
      • ReactJS Custom Application Development
      • ReactJS Single Page Application Development (SPA)
      • ReactJS Applications Architecture
      • ReactJS API Integration
      • ReactJS Migration
      • ReactJS Consulting
      • ReactJS Maintenance and Support
    • Spring Boot Services
      • Spring Boot Web Development Service
      • Spring MVC Web Development
      • Spring Boot API Integration Service
      • Spring Boot Security
      • Spring Boot Migration Service
      • Spring Boot Microservices
      • Spring Boot Support & Maintenance Service
    • AEM Development Services
      • AEM Consulting Services
      • AEM Site Development
      • AEM Migration & Upgradation
      • AEM Integration Services
      • AEM Maintenance & Support
      • AEM Content Management
      • Custom AEM Solutions
      • AEM Team Augmentation
  • INTEGRATION
  • HIRE US
    • Hire Liferay Developer
    • Hire ReactJS Developer
    • Hire Spring Boot Developer
    • Hire Healthcare Developer
    • Hire Web Developer
    • Hire MERN Stack Developer
  • CONTACT US
  • Company

    About IGNEK

    Careers

    We're hiring!

    Blogs

    Case Studies

    Webinar

    Get in touch with our HR team

    • hr@ignek.com
    • +91 93284 95160
    • Ahmedabad, Gujarat, India – 382470
  • Services

    Enterprise Portal Development

    Dedicated Development Team

    Back-end Development

    Front-end Development

    Digital Transformation

    SaaS Development

    Technologies

    Liferay Liferay Services
    • Development & Customization
    • Theme
    • Upgradation
    • Migration
    • Proof of Concept
    • Performance Tuning
    • Architecture
    • Support & Maintenance
    • E-commerce
    • Expert Advice
    React React Services
    • Enterprise Development
    • Custom Application
    • Single Page Application
    • Architecture
    • API Integration
    • Migration
    • Consulting
    • Maintenance & Support
    Spring Boot Spring Boot Services
    • Web Service
    • MVC Web Development
    • API Integration
    • Security
    • Migration
    • Microservices
    • Support & Maintenance
    AEM AEM Services
    • Consulting Service
    • Site Development
    • Migration & Upgradation
    • Integration
    • Maintenance & Support
    • Custom Solutions
    • Content Management
    • Team Augmentation
  • Solution

    Ready for digital excellence

    In our rapidly evolving world, businesses are always on the lookout for fresh ways to improve their operations and connect with their audiences.

    Contact US

    Solutions

    SaaS : Software As A Service

    Customer Portal : Boost Business Productivity

    Liferay Based Intranet Portal

    Integration

    Matomo Integration with Liferay

    Microsoft Teams integration with Liferay

    Jira Integration With Liferay

  • Hire Us

    Liferay

    React JS

    Web Developer

    Spring Boot

    Healthcare

    MERN Stack

    Why Hire Developers From IGNEK ?

    • Certified Developer
    • Transparent Communication
    • Flexible Hiring Modals
    • Fully Signed NDA
    • Cost Effective
    • Easy Exit Policy

    Get in touch with our Sales team

    • sales@ignek.com
    • +91 6351576580
    • IGNEK
    • Ahmedabad, Gujarat, India – 382470
  • SCHEDULE CALL

Various Approaches of API Integration In Spring Boot

  • Spring Boot
  • December 4, 2023

Share On :

Introduction

In Spring Boot, there are many ways to perform API integration. By API integration, we enable communication between applications and external services. API integration plays an important role in modern application and software development because it allows systems to interact with each other, exchange data, and expand functionality. In spring boot, we can do API integration in several ways.

1) Rest Template

  • Rest Template is mostly used to create applications that consume RESTful Web Services.
  • This is a synchronous client for making HTTP requests. 
  • It’s a direct way to interact with APIs and perform GET, POST, PUT, and DELETE.
  • By use of the exchange() method you can consume the web services for all HTTP methods.

Here is an example of creating API integration using the rest template

  • Autowired the Rest Template Object.
  • Use HttpHeaders to set the Request Headers.
  • Use HttpEntity to wrap the request object.
  • Provide the URL, HttpMethod, and Return type for the Exchange() method.
				
					//ConsumeWebService.java
package com.ignek.restTemplateDemo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
@RestController
public class ConsumeWebService {
    @Autowired
    RestTemplate restTemplate;
    @RequestMapping(value = "/ignek/products")
    public String getProductList() {
        HttpHeaders headers= new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        HttpEntity <String> entity = new HttpEntity<String>(headers);
        return restTemplate.exchange(" http://localhost:8080/products", HttpMethod.GET,entity,String.class).getBody();
    }
}
				
			

Consuming the GET API by using the RestTemplate – exchange() method

				
					[
    {
        "id": "1", 
        "name": "pen"
    },
    {
        "id": "2",
        "name": "pencil"
    }
]
				
			

Create Bean for Rest Template to auto-wire the Rest Template object.

				
					package com.ignek.restTemplateDemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class RestTemplateDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(RestTemplateDemoApplication.class, args);
    }

    @Bean
    public RestTemplate getRestTemplate(){return  new RestTemplate();}
}
				
			

2) WebClient:

  • Spring WebClient is a non-blocking, reactive client for handling HTTP requests.
  • Comparison with RestTemplate and the advantages of using WebClient, especially in reactive programming scenarios.
  • Code snippets to showcase WebClient usage for synchronous and asynchronous operations.
  • It is also the replacement for the classic Rest Template.

Here is an example of creating API integration using the web client

Add this dependency

				
					// Web Client dependency
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
				
			
WebClient Configuration:

Create a configuration class to set up WebClient with custom settings. 

This configuration allows you to define timeouts, connection limits, and other settings for WebClient usage.

				
					// WebClientConfig.java
package com.ignek.webClientDemo.config;

import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.handler.timeout.WriteTimeoutHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.web.reactive.function.client.ExchangeStrategies;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.netty.http.client.HttpClient;

@Configuration
public class WebClientConfig {

    @Bean
    public WebClient.Builder webClientBuilder() {

        HttpClient httpClient = HttpClient.create().tcpConfiguration(tcpClient ->
                tcpClient
                        .doOnConnected(conn -> conn
                                .addHandlerLast(new ReadTimeoutHandler(10))
                                .addHandlerLast(new WriteTimeoutHandler(10))
                        )
        );

        // Setup ExchangeStrategies to avoid buffer limit issues (if needed)
        ExchangeStrategies exchangeStrategies = ExchangeStrategies.builder()
                .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(16 * 1024 * 1024))
                .build();

        return WebClient.builder()
                .clientConnector(new ReactorClientHttpConnector(httpClient))
                .exchangeStrategies(exchangeStrategies);
    }
}
				
			

Using WebClient in a Service or Controller:

Now, you can inject the configured WebClient into your services or controllers and use it to make HTTP requests.

				
					@Service
public class ApiService {

    private final WebClient webClient;

    @Autowired
    public ApiService(WebClient.Builder webClientBuilder) {
        this.webClient = webClientBuilder.build();
    }

    public Mono<String> fetchDataFromExternalAPI() {
        return webClient.get()
                .uri("https://api.example.com/data")
                .retrieve()
                .bodyToMono(String.class);
    }
}

				
			

3) Third-Party Libraries

Some APIs come with their own Java SDKs or libraries. You can use these libraries directly within your Spring Boot application to integrate with the respective services.

Integrating a third-party API in a Spring Boot application involves making HTTP requests to external services, fetching data, and handling responses within your Spring Boot application. This can be done using various methods such as RESTful API calls, HTTP clients, and libraries like Retrofit, RestTemplate, Feign, etc.

Here’s an example of integrating a third-party API using Spring Boot, specifically by making a simple RESTful API call :

You want to integrate with a hypothetical weather API to get the current weather by city.

Create a model for the response :

Assume the API returns weather data in JSON format. You’d create a model class to represent this data:

				
					// Weather.java
package com.ignek.thirdPartyDemo.model;

public class Weather {
    private String city;
    private double temperature;

}

				
			

Create a Service to fetch data from the API : 

				
					// WeatherAPIService.java
package com.ignek.thirdPartyDemo.services;

import com.ignek.thirdPartyDemo.model.Weather;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.ResponseEntity;

@Service
public class WeatherAPIService {
    private final RestTemplate restTemplate;

    public WeatherAPIService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public Weather getWeatherByCity(String city) {
        String apiKey = "YOUR_API_KEY";
        String url = "https://weather-api.com/api/current?city=" + city + "&key=" + apiKey;

        ResponseEntity<Weather> response = restTemplate.getForEntity(url, Weather.class);

        if (response.getStatusCode() == HttpStatus.OK) {
            return response.getBody();
        } else {
            // Handle errors
            return null;
        }
    }
}
				
			

Create a Controller to handle incoming requests :

				
					// WeatherController.java
package com.ignek.thirdPartyDemo.controller;

import com.ignek.thirdPartyDemo.model.Weather;
import com.ignek.thirdPartyDemo.services.WeatherAPIService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/weather")
public class WeatherController {
    private final WeatherAPIService weatherAPIService;

    public WeatherController(WeatherAPIService weatherAPIService) {
        this.weatherAPIService = weatherAPIService;
    }

    @GetMapping("/{city}")
    public ResponseEntity<Weather> getWeather(@PathVariable String city) {
        Weather weather = weatherAPIService.getWeatherByCity(city);
        if (weather != null) {
            return new ResponseEntity<>(weather, HttpStatus.OK);
        } else {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
				
			

Configure RestTemplate :

In your Spring Boot application configuration, you’ll need to configure RestTemplate (or another HTTP client) and set up error handling, logging, etc.

				
					// AppConfig.java
package com.ignek.thirdPartyDemo.config;

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();
    }
}
				
			

4) WebSocket for Real-time Communication :

If you need real-time communication or bidirectional data exchange, you can use Spring’s WebSocket support to integrate with WebSocket-based APIs. The WebSocket protocol makes your application handle real-time messages. The WebSocket specification and their sub-protocols allow operation on a higher application level. STOMP is one of the supported Spring Framework for this. STOMP is a simple text-based messaging protocol initially created for scripting languages such as Ruby, Python, and Perl to connect to enterprise message brokers.

Here is an example of creating API integration using the web Socket

Add this dependency

				
					//web socket dependency

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
				
			

Configure spring to enable WebSocket and STOMP messaging.

				
					// WebSocketConfig.java
package com.ignek.webSocketDemo.config;

import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry
                                               registry) {
        registry.addEndpoint("/mywebsockets")
                .setAllowedOrigins("mydomain.com").withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config){
        config.enableSimpleBroker("/topic/", "/queue/");
        config.setApplicationDestinationPrefixes("/app");
    }
}
				
			

Implement a controller that will handle user requests. It will broadcast the received message to all users subscribed to a given topic.

				
					/ NewsControler.java
package com.ignek.webSocketDemo.controller;

import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.stereotype.Controller;

@Controller
public class NewsControler {

    private SimpMessagingTemplate simpMessagingTemplate;

    public void WebSocketController(SimpMessagingTemplate simpMessagingTemplate) {
        this.simpMessagingTemplate = simpMessagingTemplate;
    }

    public NewsControler(SimpMessagingTemplate simpMessagingTemplate) {
        this.simpMessagingTemplate = simpMessagingTemplate;
    }

    @MessageMapping("/news")
    public void broadcastNews(String message) {
        this.simpMessagingTemplate.convertAndSend("/topic/news", message);
    }

    @MessageMapping("/greetings")
    @SendToUser("/queue/greetings")
    public String reply(@Payload String message) {
        return "Hello " + message;
    }
}

				
			

you can use SimpMessagingTemplate which you can autowire inside your controller.

				
					@MessageMapping("/news")
    public void broadcastNews(String message) {
        this.simpMessagingTemplate.convertAndSend("/topic/news", message);
    }

				
			

Building the WebSocket Client : 

Autowire Spring STOMP client.

				
					@Autowired
    private WebSocketStompClient stompClient;
				
			

Open a connection.

				
					String loggerServerQueueUrl = "your_logger_server_url"; // Replace this with your logger server URL

        StompSessionHandler sessionHandler = new CustomStompSessionHandler();

        try {
            StompSession stompSession = stompClient.connect(loggerServerQueueUrl, sessionHandler).get();

            // Send a message to a destination (e.g., "topic/greetings")
            stompSession.send("topic/greetings", "Hello new user");
        } catch (Exception e) {
            // Handle exceptions or errors
            e.printStackTrace();
        }
    }
				
			

We need to annotate a controller’s method with @SendToUser.

				
					 @MessageMapping("/greetings")
    @SendToUser("/queue/greetings")
    public String reply(@Payload String message) {
        return "Hello " + message;
    }
				
			

5) Feign Client : 

Feign is a declarative web service client. It makes writing web service clients easier. Feign clients are interfaces that declare the HTTP API of a remote service. They abstract the complexity of HTTP requests and responses, providing a more straightforward way to communicate with RESTful services. Use Feign to create an interface and annotate it. Pluggable annotation support, such as Feign and JAX-RS annotations, is a core feature. Feign offers flexibility through its support for custom encoders and decoders. Spring Cloud enriches this by incorporating Spring MVC annotations and seamlessly utilizing the same HttpMessageConverters as Spring Web by default. By integrating Eureka, Spring Cloud facilitates a load-balanced HTTP client when leveraging Feign, offering enhanced scalability and reliability.

Here is an example of creating API integration using the feign client

Add this dependency

				
					// feign client dependency
    <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
            <version>1.4.7.RELEASE</version>
    </dependency>

				
			

In your Spring Boot main application class or a configuration class, you need to enable the Feign client using @EnableFeignClients annotation.

				
					// FeignClientApplication.java
package com.ignek.feignClient;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.feign.EnableFeignClients;

@SpringBootApplication
@EnableFeignClients
public class FeignClientApplication {

    public static void main(String[] args) {
        SpringApplication.run(FeignClientApplication.class, args);
    }

}
				
			

Here is a simple REST API that provides post information and you want to retrieve this data using the Feign client in a Spring Boot application.

				
					package com.ignek.feignClient;

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;

@FeignClient(name = "exampleClient", url = "https://jsonplaceholder.typicode.com")
public interface ExampleFeignClient {

    @GetMapping("/posts/{id}")
    String getPostById(Long id);
}

				
			

You can inject the Feign client interface into your service or controller and use it to make requests to the external API.

a controller is not specifically required when using a Feign client. Feign clients can be used within services or other components without the necessity of a controller.

				
					// MyService.java
package com.ignek.feignClient.services;

import com.ignek.feignClient.ExampleFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MyService {

    private final ExampleFeignClient exampleFeignClient;

    @Autowired
    public MyService(ExampleFeignClient exampleFeignClient) {
        this.exampleFeignClient = exampleFeignClient;
    }

    public String getPostById(Long id) {
        return exampleFeignClient.getPostById(id);
    }
}
				
			

7) Now, deploy the module.

Explore Our Services

Discover how we can help your business thrive, whether you’re running a small startup, an SME, or a large enterprise. We’re here to understand your unique needs and goals, offering the expertise and resources to support your journey to success.

Stay informed about our Spring Boot services and updates by subscribing to our newsletter—just fill in the details below to subscribe.

Loading
Loading...

Related Blogs

August 28, 2023
Best Approach to integrate Spring Boot with GraphQl
GraphQL with Spring Boot
October 17, 2023
Enhance program organization and structure through Spring Boot Custom Annotations.
Custom Annotations in Spring Boot
October 17, 2023
Apache Kafka integration: Pros and cons
Apache Kafka Case Studies: Pros and cons
Loading...

Featured Projects Portfolios

October 6, 2023
Incident Management Portal _ Simplifying Reporting, Tracking and Collaboration
Incident Management Portal : Simplifying Reporting, Tracking, and Collaboration
October 6, 2023
Collaborative Blogging Platform for Businesses, Authors, and Readers
Collaborative Blogging Platform for Businesses, Authors, and Readers
October 6, 2023
Dynamic E-commerce Platform_for Sales, Rentals and Inventory Management
Dynamic E-commerce Platform for sales, Rentals and Inventory Management

Digital Solutions for Your Business with IGNEK

4.9

5.0

5.0

5.0

LOGO

Making the world a better place through constructing elegant hierarchies

COMPANY

  • About
  • Career
  • Case Study
  • Blogs

SERVICES

  • Enterprise Portal Development
  • Dedicated Development Team
  • Back-end Development
  • Front-end Development
  • Digital Transformation
  • SaaS Development

HIRE US

  • Liferay
  • Spring Boot
  • ReactJS
  • Healthcare
  • MERN Stack
  • AEM

CONTACT

  • info@ignek.com
  • info@ignek.com
SALES
  • sales@ignek.com
  • (+91) 635 157 6580
CAREER
  • hr@ignek.com
  • (+91) 932 849 5160
  • E 910-912, Ganesh Glory 11, Jagatpur Road, SG Highway, Ahmedabad, Gujarat - 382470

© 2018-2025 IGNEK, Inc. All rights reserved

Linkedin Facebook X-twitter Instagram