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:
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:
{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.
Hello Sir
Can you please explain how we can handle the spring file upload Restful service in java application
without using the RestTemplate object
Did not work:
COMPILATION ERROR :
————————————————————-
com/doj/restapi/web/RestApplicationInitializer.java:[15,8] cannot access javax.servlet.ServletException
class file for javax.servlet.ServletException not found
1 error
————————————————————-
————————————————————————
BUILD FAILURE
————————————————————————
Total time: 1.345s
Finished at: Sun May 19 12:55:42 CEST 2019
Final Memory: 17M/309M
————————————————————————
Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.5.1:compile (default-compile) on project SpringREST-Example: Compilation failure
com/doj/restapi/web/RestApplicationInitializer.java:[15,8] cannot access javax.servlet.ServletException
class file for javax.servlet.ServletException not found
-> [Help 1]
To see the full stack trace of the errors, re-run Maven with the -e switch.
Re-run Maven using the -X switch to enable full debug logging.
For more information about the errors and possible solutions, please read the following articles:
[Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException