REST

Spring REST client – RestTemplate Consume RESTful Web Service Example JSON

In Spring REST client, The RestTemplate is the core class for client-side access to Spring RESTful web services. It communicates HTTP server using RESTful constraints. It is very similar to other template classes in the Spring like JdbcTemplate and HibernateTemplate etc. In Spring, RestTemplate provides higher level implementation of corresponding HTTP methods such as GET, POST, PUT, DELETE, HEAD etc. It provides the methods to communicate by using these HTTP methods with URI template, URI param, request object and response type as arguments.

In this example, we will see how to consume JSON response. In my previous article we have seen Spring RESTful web services crud example. Earlier we have used postman REST UI based client to demonstrate all HTTP methods such as get, post, delete and put. But here we are going to consume Restful web services via RestTemplate of Spring REST client.

RestTemplate Methods
RestTemplate provides higher level methods that correspond to each of the six main HTTP methods that make invoking many RESTful services. In the following list has methods provided by Spring RestTemplate for each http methods.

 
Method
 
Spring RestTemplate’s method
 
Get
 
 getForObject, getForEntity
 
Post
 

postForObject(String url, Object request, Class responseType, String…? uriVariables)

postForLocation(String url, Object request, String…? urlVariables),

 
Put
 
put(String url, Object request, String…?urlVariables)
 
Delete
 
delete()
 
Head
 
headForHeaders(String url, String…? urlVariables)
 
Options
 
optionsForAllow(String url, String…? urlVariables)

As per as name of these methods of RestTemplate class indicate which HTTP method they implement internally and second part of the method name indicates what is return by these methods. For example, getForObject() will perform a HTTP GET action on the server, and convert the HTTP response into an object of given type and return it to the client. And other method postForLocation() will do a HTTP POST action on the server, converting the given object into a HTTP request, and returns the response HTTP Location header where the newly created object can be found.

Let’s see these RestTemplate’s methods with examples.
Here I am using Spring Restful web services CRUD JSON Example of my previous post.

In this example, we are using @GetMapping, @PostMapping, @PutMapping and @DeleteMapping annotations, these annotations are introduced as of Spring 4.3 version in parallel of @RequestMapping annotation with Http Methods as below.

@GetMapping = @RequestMapping + Http GET method
@PostMapping = @RequestMapping + Http POST method
@PutMapping = @RequestMapping + Http PUT method
@DeleteMapping = @RequestMapping + Http DELETE method

HTTP GET Method Example
For API GET method call we can use either getForObject() or getForEntity() method of RestTemplate.

Spring REST API GET CODE:

@GetMapping("/account/{accountId}")
public Account get (@PathVariable Long accountId){
  return accountService.get(accountId);
}

We could define same above API call as below:

@RequestMapping(method=RequestMethod.GET, value = "/account/{accountId}", produces = MediaType.APPLICATION_JSON_VALUE)
public Account get (@PathVariable Long accountId){
  return accountService.get(accountId);
}

This call binds to convert on JSON media type only with the @RequestMapping annotation. If you want flexible return media type either JSON or XML based on the message converter available on the classpath of the application then it’s recommend do not define produces property request mapping annotation.

Spring RestTemplate get Method :

/**
 * 
 */
package com.doj.restclient.account;

import org.springframework.web.client.RestTemplate;

/**
 * @author Dinesh.Rajput
 *
 */
public class SpringRestClient {
 
 private static RestTemplate restTemplate = new RestTemplate();
 private static final String baseURL = "http://localhost:8080/restapi/";

 /**
  * @param args
  */
 public static void main(String[] args) {
  //Read Account details for a given accountId = 1 using GET method of RestTemplate
  Account accountDetail = restTemplate.getForObject(baseURL+"account/1", Account.class);
  System.out.println("Account Detail for given AccountId : " +accountDetail); 
  
 }

}

Output on console:
After running above code, you will get below output:

Account Detail for given AccountId : Account [accountId=1, name=Dinesh Rajput, city=Noida, balance=212.33]

HTTP POST Method Example

For Http POST method calling we can use either postForObject() or postForLocation() method of RestTemplate.

Spring Rest API Code post method:

@PostMapping("/account")
public Account create (@RequestBody Account account){
   return accountService.create(account);
}

Spring RestTemplate post Method call:

/**
 * 
 */
package com.doj.restclient.account;

import org.springframework.web.client.RestTemplate;

/**
 * @author Dinesh.Rajput
 *
 */
public class SpringRestClient {
 
 private static RestTemplate restTemplate = new RestTemplate();
 private static final String baseURL = "http://localhost:8080/restapi/";

 /**
  * @param args
  */
 public static void main(String[] args) {
  //Create Account using POST method of RestTemplate
  Account account = new Account("Arnav Rajput", "Noida", 312.33);
  account = restTemplate.postForObject(baseURL+"account", account, Account.class);
  System.out.println("Added account: " +account);
  
 }

}

Output on console:
After running above code, you will get below output:

Added account: Account [accountId=3, name=Arnav Rajput, city=Noida, balance=312.33]

HTTP PUT Method Example

For Http PUT method calling we can use put() method of RestTemplate.

Spring Rest API Code put method:

@PutMapping("/account")
public Account update (@RequestBody Account account){
  return accountService.update(account);
}

Spring RestTemplate put Method call:

/**
 * 
 */
package com.doj.restclient.account;

import org.springframework.web.client.RestTemplate;

/**
 * @author Dinesh.Rajput
 *
 */
public class SpringRestClient {
 
 private static RestTemplate restTemplate = new RestTemplate();
 private static final String baseURL = "http://localhost:8080/restapi/";

 /**
  * @param args
  */
 public static void main(String[] args) {
  //Create Account using POST method of RestTemplate
  Account account = new Account("Arnav Rajput", "Noida", 312.33);
  account = restTemplate.postForObject(baseURL+"account", account, Account.class);
  System.out.println("Added account: " +account);
  
  //Update Account detail for given accountId = 1 using PUT method of RestTemplate
  Account updateAccount = new Account("Anamika Rajput", "Noida", 123.33);
  updateAccount.setAccountId(1l);
  restTemplate.put(baseURL+"account", updateAccount);
  Account updatedAccount = restTemplate.getForObject(baseURL+"account/1", Account.class);
  System.out.println("Updated Account: " +updatedAccount);
  
 }

}

Output on console:
After running above code, you will get below output:

Added account: Account [accountId=1, name=Arnav Rajput, city=Noida, balance=312.33]
Updated Account: Account [accountId=1, name=Anamika Rajput, city=Noida, balance=123.33]

HTTP DELETE Method Example

For Http DELETE method calling we can use delete() method of RestTemplate.

Spring Rest API Code delete method:

@DeleteMapping("/account/{accountId}")
public void delete (@PathVariable Long accountId){
  accountService.delete(accountId);
}

Spring RestTemplate delete Method call:

/**
 * 
 */
package com.doj.restclient.account;

import java.util.List;

import org.springframework.web.client.RestTemplate;

/**
 * @author Dinesh.Rajput
 *
 */
public class SpringRestClient {
 
 private static RestTemplate restTemplate = new RestTemplate();
 private static final String baseURL = "http://localhost:8080/restapi/";

 /**
  * @param args
  */
 public static void main(String[] args) {
  List<Account> accounts = restTemplate.getForObject(baseURL+"accounts", List.class);
  System.out.println("Total Accounts before DELETE call: ");
  for(Object acct : accounts){
   System.out.println(acct);
  }
  
  //Delete Account for given accountId = 2 using Delete method of RestTemplate
  restTemplate.delete(baseURL+"account/2");
  accounts = restTemplate.getForObject(baseURL+"accounts", List.class);
  System.out.println("Total Accounts after DELETE call: ");
  for(Object acct : accounts){
   System.out.println(acct);
  }
 }

}

Output on console:
After running above code, you will get below output:

Total Accounts before DELETE call:
{accountId=1, name=Anamika Rajput, city=Noida, balance=123.33}
{accountId=2, name=Anamika Rajput, city=Noida, balance=222.33}
{accountId=3, name=Arnav Rajput, city=Noida, balance=522.33}
Total Accounts after DELETE call:
{accountId=1, name=Anamika Rajput, city=Noida, balance=123.33}
{accountId=3, name=Arnav Rajput, city=Noida, balance=522.33}

Download Source Code from GitHub.

  1. Spring RESTful web service CRUD Example
  2. Spring REST Client using RestTemplate Example
Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

3 years ago