Spring RestTemplate (with Examples)

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.


If you are using Spring boot then we can import all necessary dependencies by including the spring-boot-starter-web dependency.


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.

public RestTemplate restTemplate(RestTemplateBuilder builder) {
	return builder

2.3. Using SimpleClientHttpRequestFactory

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

public RestTemplate restTemplate() {
	var factory = new SimpleClientHttpRequestFactory();
	return new RestTemplate(factory);

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.

CloseableHttpClient httpClient;
private String apiHost;
public RestTemplate restTemplate() {

	RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory());
	restTemplate.setUriTemplateHandler(new DefaultUriBuilderFactory(apiHost));
	return restTemplate;
public HttpComponentsClientHttpRequestFactory clientHttpRequestFactory() {

	HttpComponentsClientHttpRequestFactory clientHttpRequestFactory
			= new HttpComponentsClientHttpRequestFactory();
	return clientHttpRequestFactory;

See Also: RestTemplate Configuration with HttpClient


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.
public ResponseEntity<List<User>> getAll() { ... }

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


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:

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


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.

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


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.

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

Happy Learning !!

Sourcecode on Github

Leave a Reply

Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial