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:
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:
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:
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:
Download Source Code from GitHub.
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…