You are on page 1of 6

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.

Depreciation Warning: Spring docs recommend to use the non-blocking, reactive


WebClient API which offers efficient support for both sync, async and streaming scenarios.
RestTemplate will be deprecated in the future versions.

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

2. Creating Spring RestTemplate Instance

The given below are a few ways to create RestTemplate bean in the application.
2.1. Using Constructor

The simplest way to create a RestTemplate instance is by using its constructor:

RestTemplate restTemplate = new RestTemplate();


2.2. Using RestTemplateBuilder

The builder offers to customize the advanced configurations such as timeouts.

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {

return builder
.setConnectTimeout(Duration.ofMillis(3000))
.setReadTimeout(Duration.ofMillis(3000))
.build();
}
2.3. Using SimpleClientHttpRequestFactory

It uses standard JDK facilities to create a factory for new ClientHttpRequest objects.

@Bean
public RestTemplate restTemplate() {

var factory = new SimpleClientHttpRequestFactory();


factory.setConnectTimeout(3000);
factory.setReadTimeout(3000);
return new RestTemplate(factory);
}
2.4. Using Apache HTTPClient (Recommended)

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() {

RestTemplate restTemplate = new


RestTemplate(clientHttpRequestFactory());
restTemplate.setUriTemplateHandler(new
DefaultUriBuilderFactory(apiHost));
return restTemplate;
}

@Bean
@ConditionalOnMissingBean
public HttpComponentsClientHttpRequestFactory clientHttpRequestFactory() {

HttpComponentsClientHttpRequestFactory clientHttpRequestFactory
= new HttpComponentsClientHttpRequestFactory();
clientHttpRequestFactory.setHttpClient(httpClient);
return clientHttpRequestFactory;
}

See Also: RestTemplate Configuration with HttpClient

3. HTTP GET

Available methods for executing GET APIs are:

 getForObject(url, classType) – retrieve a representation by doing a GET on the


URL. The response (if any) is unmarshalled to the given class type and returned.
 getForEntity(url, responseType) – retrieve a representation as ResponseEntity by
doing a GET on the URL.
 exchange(url, httpMethod, requestEntity, responseType) – execute the
specified RequestEntity and return the response as ResponseEntity.
 execute(url, httpMethod, requestCallback, responseExtractor) – execute
the httpMethod to the given URI template, prepare the request with the RequestCallback,
and read the response with a ResponseExtractor.

We have the following two GET APIs that we will learn to consume using the RestTemplate.

 /users: returns a list of users.


 /users/{id}: returns a user by id.

@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.

String userJson = restTemplate.getForObject("/users/{id}", String.class,


Map.of("id", "1"));

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"));

ObjectMapper mapper = new ObjectMapper();


JsonNode root = mapper.readTree(responseEntity.getBody());
3.2. API Response as POJO

We can fetch the API response directly into the domain object using the getForObject() API.
User[] usersArray = restTemplate.getForObject("/users", User[].class);

User user = restTemplate.getForObject("/users/{id}", User.class,


Map.of("id", "1"));

Similarly, getForEntity() API can be used to fetch the ResponseEntity object.

ResponseEntity<User[]> responseEntity = restTemplate.getForEntity("/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.

HttpHeaders headers = new HttpHeaders();


headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.set("X-COM-PERSIST", "NO");
headers.set("X-COM-LOCATION", "USA");

HttpEntity<String> entity = new HttpEntity<String>(headers);

ResponseEntity<User[]> responseEntity = restTemplate.exchange("/users",


HttpMethod.GET, entity, User[].class);
4. HTTP POST

The available methods for consuming POST APIs are:

 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)

We will consume the following POST API using the RestTemplate:

@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.

User newUser = new User(1, "Alex", "Golan", "alex@mail.com"); //POJO

User createdUser = restTemplate.postForObject("/users", newUser,


User.class);
4.2. Using postForLocation()

The postForLocation() API is very similar to postForObject(), except it returns only the
Location of the created resource.

User newUser = new User(1, "Alex", "Golan", "alex@mail.com");

URI location = restTemplate.postForLocation("/users", newUser, User.class);


5. HTTP PUT

The available method to invoke an HTTP PUT API is:

 put(url, request) – PUTs the given request object to the URL.

We are consuming the following PUT API.

@PutMapping("users/{id}")
public ResponseEntity<User> update(@RequestBody User updatedUser) { ... }

Use the put() API as follows:

User user = new User(1, "Alex", "Golan", "a@mail.com"); //POJO

User updatedUser = restTemplate.put("/users/{id}", user, User.class,


Map.of("id", "1"));
6. HTTP DELETE

The available methods for invoking an HTTP DELETE API are:

 delete(url) – deletes the resource at the specified URL.

We are consuming the following DELETE API.

@DeleteMapping("users/{id}")
public HttpStatus delete(@PathVariable long id) { ... }

Use the delete() API as follows:

restTemplate.delete ("/users/{id}", Map.of("id", "1"));

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

 Spring RestTemplate basic authentication example


 Spring RestTemplate timeout configuration example
 Spring RestTemplateBuilder Example
 Spring RestTemplate – HttpClient configuration example
 Spring Boot RestTemplate GET Example
 Spring Boot RestTemplate POST Example
 Spring boot JUnit example with RestTemplate
 Spring boot TestRestTemplate POST with headers example
 Spring ClientHttpRequestInterceptor with RestTemplate

Happy Learning !!

Sourcecode on Github

You might also like