RestTemplate
REST APIs are becoming more and more common because of their heavy traffic and fast service accessibility. REST is an architectural set of limitations rather than a protocol or standard. It is also known as a web API or RESTful API. A client request simply sends an HTTP representation of the resource’s current state to the requester or to the endpoint.
Implementation of RestTemplate
Step 1: In your pom.xml file, add the Spring-Web dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Step 2: To utilise and invoke the Spring RestTemplate in your project, create a bean
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.web.client.RestTemplate;
import java.time.Duration;
@Configuration
public class RestTemplateConfig {
// Configuring a RestTemplate bean with timeout settings
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder
.setConnectTimeout(Duration.ofMillis(3000)) // Set connection timeout to 3000 milliseconds
.setReadTimeout(Duration.ofMillis(3000)) // Set read timeout to 3000 milliseconds
.build();
}
}
Step 3: You may now make HTTP requests using the RestTemplate methods
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
@Component
public class ProductsRestClient {
@Autowired
private RestTemplate restTemplate;
private static final String productsUrl = "https://api.product.com/name/watch";
// Method to perform a GET request using getForEntity and retrieve the response body
public Products getForEntity() {
ResponseEntity<Products> response = restTemplate.getForEntity(productsUrl, Products.class);
return response.getBody();
}
// Method to perform a GET request using getForObject and retrieve the response body
public Products getForObject() {
return restTemplate.getForObject(productsUrl, Products.class);
}
// Method to retrieve headers using headForHeaders and format them into a map
public Map<String, String> getHeaders() {
HttpHeaders httpHeaders = restTemplate.headForHeaders(productsUrl);
Map<String, String> headerContent = new HashMap<>();
httpHeaders.forEach((key, value) -> {
headerContent.put(String.format("Header '%s'", key),
String.join("|", value)); // Join header values with "|" separator
});
return headerContent;
}
}
Call a Slow Service
Using Spring RestTemplate
@GetMapping("/tweets-blocking")
public List<Tweet> getTweetsBlocking() {
log.info("Starting BLOCKING Controller!");
final String uri = getSlowServiceUri();
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<List<Tweet>> response = restTemplate.exchange(
uri, HttpMethod.GET, null,
new ParameterizedTypeReference<List<Tweet>>(){});
List<Tweet> result = response.getBody();
result.forEach(tweet -> log.info(tweet.toString()));
log.info("Exiting BLOCKING Controller!");
return result;
}
Using Spring WebClient
@GetMapping(value = "/tweets-non-blocking",
produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<Tweet> getTweetsNonBlocking() {
log.info("Starting NON-BLOCKING Controller!");
Flux<Tweet> tweetFlux = WebClient.create()
.get()
.uri(getSlowServiceUri())
.retrieve()
.bodyToFlux(Tweet.class);
tweetFlux.subscribe(tweet -> log.info(tweet.toString()));
log.info("Exiting NON-BLOCKING Controller!");
return tweetFlux;
}
Spring – WebClient vs RestTemplate
Reactor is the foundation of WebClient’s functional and fluid API (see Reactive Libraries), allowing declarative building of asynchronous logic without requiring knowledge of threads or concurrency. REST is an architectural set of limitations rather than a protocol or standard. It is also known as a web API or RESTful API. A client request simply sends an HTTP representation of the resource’s current state to the requester or the endpoint.