Spring RestTemplate - With Examples
Spring RestTemplate - With Examples
https://howtodoinjava.com/spring-boot2/resttemplate/spring-restful-client-resttemplate-example/
Spring RestTemplate is a synchronous REST client performing HTTP requests using a simple
template-style API. It uses an underlying HTTP client library, such as
JDK HttpURLConnection, Apache HttpComponents etc. The RestTemplate class is designed
on the same principles as the many other Spring *Template classes (e.g., JdbcTemplate,
JmsTemplate ), providing a simplified approach with default behaviors for performing
complex tasks.
Given that the RestTemplate class is a synchronous client and is designed to call REST
services. It should come as no surprise that its primary methods are closely tied to REST’s
underpinnings, which are the HTTP protocol’s methods HEAD, GET, POST, PUT,
DELETE, and OPTIONS.
1. Maven
Include the latest version of spring-web dependency to use RestTemplate in the application.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>6.0.2</version>
</dependency>
If you are using Spring boot then we can import all necessary dependencies by including the
spring-boot-starter-web dependency.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>3.0.0</version>
</dependency>
Current Time 0:00
Duration 1:45
The given below are a few ways to create RestTemplate bean in the application.
2.1. Using Constructor
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder
.setConnectTimeout(Duration.ofMillis(3000))
.setReadTimeout(Duration.ofMillis(3000))
.build();
}
2.3. Using SimpleClientHttpRequestFactory
@Bean
public RestTemplate restTemplate() {
Apache HTTP client library provides a very granular level of control for whole request and
response processing. We can use its CloseableHttpClient as the implementation
of HttpClient that also implements Closeable.
@Autowired
CloseableHttpClient httpClient;
@Value("${api.host.baseurl}")
private String apiHost;
@Bean
public RestTemplate restTemplate() {
@Bean
@ConditionalOnMissingBean
public HttpComponentsClientHttpRequestFactory clientHttpRequestFactory() {
HttpComponentsClientHttpRequestFactory clientHttpRequestFactory
= new HttpComponentsClientHttpRequestFactory();
clientHttpRequestFactory.setHttpClient(httpClient);
return clientHttpRequestFactory;
}
3. HTTP GET
We have the following two GET APIs that we will learn to consume using the RestTemplate.
@GetMapping("users")
public ResponseEntity<List<User>> getAll() { ... }
@GetMapping("users/{id}")
public ResponseEntity<User> getById(@PathVariable long id) { ... }
3.1. API Response as JSON String
The getForObject() is pretty useful when we are getting an unparsable response from
the server, and we have no control over getting it fixed on the server side. Here, we can get
the response as String, and use a custom parser or use a string replacement function to fix
the response before handing it over to the parser.
We can use the getForEntity() API which returns the ResponseEntity instance. To extract the
response body, use its responseEntity.getBody() method.
ResponseEntity<String> responseEntity =
restTemplate.getForEntity("/users/{id}", String.class, Map.of("id", "1"));
We can fetch the API response directly into the domain object using the getForObject() API.
User[] usersArray = restTemplate.getForObject("/users", User[].class);
ResponseEntity<User> responseEntityUser =
restTemplate.getForEntity("/users/{id}", User.class, Map.of("id", "1"));
3.3. Request Headers
If we want to send the request headers then we need to use the generic exchange() API.
postForObject(url, request, classType) – POSTs the given object to the URL and
returns the representation found in the response as given class type.
postForEntity(url, request, responseType) – POSTs the given object to the URL
and returns the response as ResponseEntity.
postForLocation(url, request, responseType) – POSTs the given object to the
URL and returns the value of the Location header.
exchange(url, requestEntity, responseType)
execute(url, httpMethod, requestCallback, responseExtractor)
@PostMapping("users")
public ResponseEntity<User> create(@RequestBody User newUser) { ... }
4.1. Using postForObject()
The postForObject() API accepts a POJO instance directly submitted to the remote API and
can return the response body having the created resource.
The postForLocation() API is very similar to postForObject(), except it returns only the
Location of the created resource.
@PutMapping("users/{id}")
public ResponseEntity<User> update(@RequestBody User updatedUser) { ... }
@DeleteMapping("users/{id}")
public HttpStatus delete(@PathVariable long id) { ... }
Feel free to copy and modify the above Spring RestTemplate examples for building the
Spring REST API Consumer in your Spring WebMVC application.
7. RestTemplate Examples
Happy Learning !!
Sourcecode on Github