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 entity = new HttpEntity(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
org.springframework.boot
spring-boot-starter-webflux
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 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 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 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
org.springframework.boot
spring-boot-starter-websocket
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
org.springframework.cloud
spring-cloud-starter-feign
1.4.7.RELEASE
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.