Spring Boot

Various Approaches of API Integration In Spring Boot

Mansi Isamaliya
Mansi IsamaliyaDec 4, 2023

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.
1//ConsumeWebService.java
2package com.ignek.restTemplateDemo.controller;
3
4import org.springframework.beans.factory.annotation.Autowired;
5import org.springframework.http.HttpHeaders;
6import org.springframework.http.MediaType;
7import org.springframework.http.HttpEntity;
8import org.springframework.http.HttpMethod;
9import org.springframework.web.bind.annotation.RequestMapping;
10import org.springframework.web.bind.annotation.RestController;
11import org.springframework.web.client.RestTemplate;
12
13import java.util.Arrays;
14@RestController
15public class ConsumeWebService {
16    @Autowired
17    RestTemplate restTemplate;
18    @RequestMapping(value = "/ignek/products")
19    public String getProductList() {
20        HttpHeaders headers= new HttpHeaders();
21        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
22        HttpEntity <String> entity = new HttpEntity<String>(headers);
23        return restTemplate.exchange(" http://localhost:8080/products", HttpMethod.GET,entity,String.class).getBody();
24    }
25}

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

1[
2    {
3        "id": "1",
4        "name": "pen"
5    },
6    {
7        "id": "2",
8        "name": "pencil"
9    }
10]

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

1package com.ignek.restTemplateDemo;
2
3import org.springframework.boot.SpringApplication;
4import org.springframework.boot.autoconfigure.SpringBootApplication;
5import org.springframework.context.annotation.Bean;
6import org.springframework.web.client.RestTemplate;
7
8@SpringBootApplication
9public class RestTemplateDemoApplication {
10
11    public static void main(String[] args) {
12        SpringApplication.run(RestTemplateDemoApplication.class, args);
13    }
14
15    @Bean
16    public RestTemplate getRestTemplate(){return  new RestTemplate();}
17}

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

1// Web Client dependency
2<dependency>
3            <groupId>org.springframework.boot</groupId>
4            <artifactId>spring-boot-starter-webflux</artifactId>
5</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.

1// WebClientConfig.java
2package com.ignek.webClientDemo.config;
3
4import io.netty.handler.timeout.ReadTimeoutHandler;
5import io.netty.handler.timeout.WriteTimeoutHandler;
6import org.springframework.context.annotation.Bean;
7import org.springframework.context.annotation.Configuration;
8import org.springframework.http.client.reactive.ReactorClientHttpConnector;
9import org.springframework.web.reactive.function.client.ExchangeStrategies;
10import org.springframework.web.reactive.function.client.WebClient;
11import reactor.netty.http.client.HttpClient;
12
13@Configuration
14public class WebClientConfig {
15
16    @Bean
17    public WebClient.Builder webClientBuilder() {
18
19        HttpClient httpClient = HttpClient.create().tcpConfiguration(tcpClient ->
20                tcpClient
21                        .doOnConnected(conn -> conn
22                                .addHandlerLast(new ReadTimeoutHandler(10))
23                                .addHandlerLast(new WriteTimeoutHandler(10))
24                        )
25        );
26
27        // Setup ExchangeStrategies to avoid buffer limit issues (if needed)
28        ExchangeStrategies exchangeStrategies = ExchangeStrategies.builder()
29                .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(16 * 1024 * 1024))
30                .build();
31
32        return WebClient.builder()
33                .clientConnector(new ReactorClientHttpConnector(httpClient))
34                .exchangeStrategies(exchangeStrategies);
35    }
36}

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.

1@Service
2public class ApiService {
3
4    private final WebClient webClient;
5
6    @Autowired
7    public ApiService(WebClient.Builder webClientBuilder) {
8        this.webClient = webClientBuilder.build();
9    }
10
11    public Mono<String> fetchDataFromExternalAPI() {
12        return webClient.get()
13                .uri("https://api.example.com/data")
14                .retrieve()
15                .bodyToMono(String.class);
16    }
17}

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:

1// Weather.java
2package com.ignek.thirdPartyDemo.model;
3
4public class Weather {
5    private String city;
6    private double temperature;
7
8}

Create a Service to fetch data from the API :

1// WeatherAPIService.java
2package com.ignek.thirdPartyDemo.services;
3
4import com.ignek.thirdPartyDemo.model.Weather;
5import org.springframework.http.HttpStatus;
6import org.springframework.stereotype.Service;
7import org.springframework.web.client.RestTemplate;
8import org.springframework.http.ResponseEntity;
9
10@Service
11public class WeatherAPIService {
12    private final RestTemplate restTemplate;
13
14    public WeatherAPIService(RestTemplate restTemplate) {
15        this.restTemplate = restTemplate;
16    }
17
18    public Weather getWeatherByCity(String city) {
19        String apiKey = "YOUR_API_KEY";
20        String url = "https://weather-api.com/api/current?city=" + city + "&key=" + apiKey;
21
22        ResponseEntity<Weather> response = restTemplate.getForEntity(url, Weather.class);
23
24        if (response.getStatusCode() == HttpStatus.OK) {
25            return response.getBody();
26        } else {
27            // Handle errors
28            return null;
29        }
30    }
31}

Create a Controller to handle incoming requests :

1// WeatherController.java
2package com.ignek.thirdPartyDemo.controller;
3
4import com.ignek.thirdPartyDemo.model.Weather;
5import com.ignek.thirdPartyDemo.services.WeatherAPIService;
6import org.springframework.http.HttpStatus;
7import org.springframework.http.ResponseEntity;
8import org.springframework.web.bind.annotation.GetMapping;
9import org.springframework.web.bind.annotation.PathVariable;
10import org.springframework.web.bind.annotation.RequestMapping;
11import org.springframework.web.bind.annotation.RestController;
12
13@RestController
14@RequestMapping("/weather")
15public class WeatherController {
16    private final WeatherAPIService weatherAPIService;
17
18    public WeatherController(WeatherAPIService weatherAPIService) {
19        this.weatherAPIService = weatherAPIService;
20    }
21
22    @GetMapping("/{city}")
23    public ResponseEntity<Weather> getWeather(@PathVariable String city) {
24        Weather weather = weatherAPIService.getWeatherByCity(city);
25        if (weather != null) {
26            return new ResponseEntity<>(weather, HttpStatus.OK);
27        } else {
28            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
29        }
30    }
31}

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.

1// AppConfig.java
2package com.ignek.thirdPartyDemo.config;
3
4import org.springframework.context.annotation.Bean;
5import org.springframework.context.annotation.Configuration;
6import org.springframework.web.client.RestTemplate;
7
8@Configuration
9public class AppConfig {
10
11    @Bean
12    public RestTemplate restTemplate() {
13        return new RestTemplate();
14    }
15}

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

1//web socket dependency
2
3<dependency>
4            <groupId>org.springframework.boot</groupId>
5            <artifactId>spring-boot-starter-websocket</artifactId>
6</dependency>

Configure spring to enable WebSocket and STOMP messaging.

1// WebSocketConfig.java
2package com.ignek.webSocketDemo.config;
3
4import org.springframework.messaging.simp.config.MessageBrokerRegistry;
5import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
6import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
7import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
8
9@EnableWebSocketMessageBroker
10public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
11
12    @Override
13    public void registerStompEndpoints(StompEndpointRegistry
14                                               registry) {
15        registry.addEndpoint("/mywebsockets")
16                .setAllowedOrigins("mydomain.com").withSockJS();
17    }
18
19    @Override
20    public void configureMessageBroker(MessageBrokerRegistry config){
21        config.enableSimpleBroker("/topic/", "/queue/");
22        config.setApplicationDestinationPrefixes("/app");
23    }
24}

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

1/ NewsControler.java
2package com.ignek.webSocketDemo.controller;
3
4import org.springframework.messaging.handler.annotation.MessageMapping;
5import org.springframework.messaging.handler.annotation.Payload;
6import org.springframework.messaging.simp.SimpMessagingTemplate;
7import org.springframework.messaging.simp.annotation.SendToUser;
8import org.springframework.stereotype.Controller;
9
10@Controller
11public class NewsControler {
12
13    private SimpMessagingTemplate simpMessagingTemplate;
14
15    public void WebSocketController(SimpMessagingTemplate simpMessagingTemplate) {
16        this.simpMessagingTemplate = simpMessagingTemplate;
17    }
18
19    public NewsControler(SimpMessagingTemplate simpMessagingTemplate) {
20        this.simpMessagingTemplate = simpMessagingTemplate;
21    }
22
23    @MessageMapping("/news")
24    public void broadcastNews(String message) {
25        this.simpMessagingTemplate.convertAndSend("/topic/news", message);
26    }
27
28    @MessageMapping("/greetings")
29    @SendToUser("/queue/greetings")
30    public String reply(@Payload String message) {
31        return "Hello " + message;
32    }
33}

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

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

Building the WebSocket Client :

Autowire Spring STOMP client.

1@Autowired
2    private WebSocketStompClient stompClient;

Open a connection.

1String loggerServerQueueUrl = "your_logger_server_url"; // Replace this with your logger server URL
2
3        StompSessionHandler sessionHandler = new CustomStompSessionHandler();
4
5        try {
6            StompSession stompSession = stompClient.connect(loggerServerQueueUrl, sessionHandler).get();
7
8            // Send a message to a destination (e.g., "topic/greetings")
9            stompSession.send("topic/greetings", "Hello new user");
10        } catch (Exception e) {
11            // Handle exceptions or errors
12            e.printStackTrace();
13        }
14    }

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

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

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

1// feign client dependency
2    <dependency>
3            <groupId>org.springframework.cloud</groupId>
4            <artifactId>spring-cloud-starter-feign</artifactId>
5            <version>1.4.7.RELEASE</version>
6    </dependency>

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

1// FeignClientApplication.java
2package com.ignek.feignClient;
3
4import org.springframework.boot.SpringApplication;
5import org.springframework.boot.autoconfigure.SpringBootApplication;
6import org.springframework.cloud.netflix.feign.EnableFeignClients;
7
8@SpringBootApplication
9@EnableFeignClients
10public class FeignClientApplication {
11
12    public static void main(String[] args) {
13        SpringApplication.run(FeignClientApplication.class, args);
14    }
15
16}

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.

1package com.ignek.feignClient;
2
3import org.springframework.cloud.netflix.feign.FeignClient;
4import org.springframework.web.bind.annotation.GetMapping;
5
6@FeignClient(name = "exampleClient", url = "https://jsonplaceholder.typicode.com")
7public interface ExampleFeignClient {
8
9    @GetMapping("/posts/{id}")
10    String getPostById(Long id);
11}

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.

1// MyService.java
2package com.ignek.feignClient.services;
3
4import com.ignek.feignClient.ExampleFeignClient;
5import org.springframework.beans.factory.annotation.Autowired;
6import org.springframework.stereotype.Service;
7
8@Service
9public class MyService {
10
11    private final ExampleFeignClient exampleFeignClient;
12
13    @Autowired
14    public MyService(ExampleFeignClient exampleFeignClient) {
15        this.exampleFeignClient = exampleFeignClient;
16    }
17
18    public String getPostById(Long id) {
19        return exampleFeignClient.getPostById(id);
20    }
21}

6) Now, deploy the module.

© 2026 IGNEK. All rights reserved.

Ignek on LinkedInIgnek on InstagramIgnek on FacebookIgnek on YouTubeIgnek on X