Spring RestTemplate CRUD operations with JSON
Spring RESTFul Client – RestTemplate Example with CRUD operations using JSON
CRUD
stands for Create,Read,Update and Delete operation
These are the most common operations that we perform in any application.
Let’s do these operations using Spring Rest service with RestTemplate client.
Requirement :
Perform CRUD operations on USER object.
We have User Domain object, we can insert User data, read the inserted data,
Update some user information and finally delete the user data.
Create a new Maven Web project in eclipse (Refer Spring MVC Hello World project for the same)
Project structure
Please refer Spring Rest CRUD Json Project for the below files
1)pom.xml
2)web.xml
3)UserService.java
4)UserDAO.java
Step 1
Create a domain class which represents the data in JSON format
create User.java
- package com.kb.rest.model;
- public class User {
- private String name;
- private int age;
- private int id;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- }
package com.kb.rest.model; public class User { private String name; private int age; private int id; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
We have created a User class with id,name and age to represent the data
create UserDetailsResponse.java
- package com.kb.rest.model;
- import java.util.List;
- public class UserDetailsResponse {
- private List<User> users;
- public List<User> getUsers() {
- return users;
- }
- public void setUsers(List<User> users) {
- this.users = users;
- }
- }
package com.kb.rest.model; import java.util.List; public class UserDetailsResponse { private List<User> users; public List<User> getUsers() { return users; } public void setUsers(List<User> users) { this.users = users; } }
We have created a UserDetailsResponse class which contains the List of User.
We will perform CRUD operations on these objects.
Why do we need to create UserDetailsResponse class when we already have User class ?
Reason is very simple,When we use Rest Template as a client, internally it uses HttpMessageConverters to convert the request/response into appropriate object.
So when we get List of user as a response , we need some POJO class to map this response.(User class will be mapped only to single User)
Hence we need to write this POJO class.
Step 2
Create the resource mapping class which will have the URL mapping methods for all our CRUD operations
- package com.kb.rest.controllers;
- import java.util.List;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.PathVariable;
- import org.springframework.web.bind.annotation.RequestBody;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.bind.annotation.ResponseBody;
- import com.kb.rest.model.User;
- import com.kb.rest.model.UserDetailsResponse;
- import com.kb.rest.service.UserService;
- @Controller
- @RequestMapping("/user")
- public class RestController {
- @Autowired
- private UserService userService;
- // CRUD -- CREATE operation
- @RequestMapping(value = "/create", method = RequestMethod.POST)
- public @ResponseBody User createUser(@RequestBody User user) {
- User userResponse = userService.createUser(user);
- return userResponse;
- }
- // CRUD -- READ operation
- @RequestMapping(value = "/getAllUsers", method = RequestMethod.GET)
- public @ResponseBody UserDetailsResponse getAllUsers() {
- List<User> userList = userService.getAllUsers();
- UserDetailsResponse userDetailsResponse = new UserDetailsResponse();
- userDetailsResponse.setUsers(userList);
- return userDetailsResponse;
- }
- // CRUD -- READ operation
- @RequestMapping(value = "/getSpecificUser/{id}", method = RequestMethod.GET)
- public @ResponseBody User getUserForId(@PathVariable ("id") int id) {
- User user = userService.getUserForId(id);
- return user;
- }
- // CRUD -- UPDATE operation
- @RequestMapping(value = "/updateUser", method = RequestMethod.PUT)
- public @ResponseBody User updateUser(@RequestBody User user) {
- User userResponse = userService.updateUser(user);
- return userResponse;
- }
- // CRUD -- DELETE operation
- @RequestMapping(value = "/deleteUser/{id}", method = RequestMethod.DELETE)
- public @ResponseBody User deleteeUser(@PathVariable("id") int id) {
- User userResponse = userService.deleteUser(id);
- return userResponse;
- }
- }
package com.kb.rest.controllers; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.kb.rest.model.User; import com.kb.rest.model.UserDetailsResponse; import com.kb.rest.service.UserService; @Controller @RequestMapping("/user") public class RestController { @Autowired private UserService userService; // CRUD -- CREATE operation @RequestMapping(value = "/create", method = RequestMethod.POST) public @ResponseBody User createUser(@RequestBody User user) { User userResponse = userService.createUser(user); return userResponse; } // CRUD -- READ operation @RequestMapping(value = "/getAllUsers", method = RequestMethod.GET) public @ResponseBody UserDetailsResponse getAllUsers() { List<User> userList = userService.getAllUsers(); UserDetailsResponse userDetailsResponse = new UserDetailsResponse(); userDetailsResponse.setUsers(userList); return userDetailsResponse; } // CRUD -- READ operation @RequestMapping(value = "/getSpecificUser/{id}", method = RequestMethod.GET) public @ResponseBody User getUserForId(@PathVariable ("id") int id) { User user = userService.getUserForId(id); return user; } // CRUD -- UPDATE operation @RequestMapping(value = "/updateUser", method = RequestMethod.PUT) public @ResponseBody User updateUser(@RequestBody User user) { User userResponse = userService.updateUser(user); return userResponse; } // CRUD -- DELETE operation @RequestMapping(value = "/deleteUser/{id}", method = RequestMethod.DELETE) public @ResponseBody User deleteeUser(@PathVariable("id") int id) { User userResponse = userService.deleteUser(id); return userResponse; } }
We have created the Controller class above which will act as a Rest service in Spring.
We have @RequestBody along with method parameter in POST and PUT methods which indicates to Spring that ,the request for this method will be coming as a HTTP request body with specified MIME type and it is mapped with a parameter of a method.
We have @ResponseBody before the return type of a method in method signature which indicates to Spring that ,the returned value from this method will not be a view rather it has to be read from the response body.
@PathVariable :
It is used to get the parameter value passed along with the URL.
Its very similar to @PathParam in JAX-RS.
@PathVariable(“id”) int id
This will get the value passed in the URL and inject it to id variable of method argument.
Step 3
Create Rest Clients using RestTemplate as below
PostUserClient.java
- package com.kb.rest.client;
- import org.springframework.web.client.RestTemplate;
- import com.kb.rest.model.User;
- public class PostUserClient {
- public static void main(String[] args) {
- RestTemplate restTemplate = new RestTemplate();
- final String url = "http://localhost:8080/SpringRestCRUDJSON/user/create";
- User user = new User();
- user.setId(1);
- user.setAge(45);
- user.setName("John");
- User addedUser = restTemplate.postForObject(url, user, User.class);
- System.out.println("User Inserted is : " + addedUser.getName());
- }
- }
package com.kb.rest.client; import org.springframework.web.client.RestTemplate; import com.kb.rest.model.User; public class PostUserClient { public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); final String url = "http://localhost:8080/SpringRestCRUDJSON/user/create"; User user = new User(); user.setId(1); user.setAge(45); user.setName("John"); User addedUser = restTemplate.postForObject(url, user, User.class); System.out.println("User Inserted is : " + addedUser.getName()); } }
In this client , we are making a POST call with User details using postForObject() method of RestTemplate
It takes 3 parameters which are
url – the end point of the Rest service
user – object which has to be submitted to rest service
User.class – type of the object
After posting, we are getting the same object as a response and we are displaying its details.
GetUsersClient.java
- package com.kb.rest.client;
- import org.springframework.web.client.RestTemplate;
- import com.kb.rest.model.User;
- import com.kb.rest.model.UserDetailsResponse;
- public class GetUsersClient {
- public static void main(String[] args) {
- RestTemplate restTemplate = new RestTemplate();
- final String url = "http://localhost:8080/SpringRestCRUDJSON/user/getAllUsers";
- UserDetailsResponse userDetailsResponse = restTemplate.getForObject(url, UserDetailsResponse.class);
- System.out.println("User retrieved details : ");
- for (User user : userDetailsResponse.getUsers()) {
- System.out.println(user.getName() + " " + user.getAge() + " " + user.getId());
- }
- }
- }
package com.kb.rest.client; import org.springframework.web.client.RestTemplate; import com.kb.rest.model.User; import com.kb.rest.model.UserDetailsResponse; public class GetUsersClient { public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); final String url = "http://localhost:8080/SpringRestCRUDJSON/user/getAllUsers"; UserDetailsResponse userDetailsResponse = restTemplate.getForObject(url, UserDetailsResponse.class); System.out.println("User retrieved details : "); for (User user : userDetailsResponse.getUsers()) { System.out.println(user.getName() + " " + user.getAge() + " " + user.getId()); } } }
In this client , we are making a GET call to get All Users details using getForObject() method of RestTemplate
It takes 2 parameters which are
url – the end point of the Rest service
UserDetailsResponse.class – type of the response object
After Get call, we are getting userDetailsResponse object as a response which contains the List of Users and we are displaying each user details.
GetSpecificUserClient.java
- package com.kb.rest.client;
- import org.springframework.web.client.RestTemplate;
- import com.kb.rest.model.User;
- public class GetSpecificUserClient {
- public static void main(String[] args) {
- RestTemplate restTemplate = new RestTemplate();
- final String url = "http://localhost:8080/SpringRestCRUDJSON/user/getSpecificUser/1";
- User user = restTemplate.getForObject(url, User.class);
- System.out.println("User retrieved details : ");
- System.out.println(user.getName() + " " + user.getAge() + " " + user.getId());
- }
- }
package com.kb.rest.client; import org.springframework.web.client.RestTemplate; import com.kb.rest.model.User; public class GetSpecificUserClient { public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); final String url = "http://localhost:8080/SpringRestCRUDJSON/user/getSpecificUser/1"; User user = restTemplate.getForObject(url, User.class); System.out.println("User retrieved details : "); System.out.println(user.getName() + " " + user.getAge() + " " + user.getId()); } }
In this client , we are making a GET call to get only single User details using getForObject() method of RestTemplate
It takes 2 parameters which are
url – the end point of the Rest service
User.class – type of the response object
After Get call, we are getting User object as a response which contains the User details and we are displaying the same.
PutUserClient.java
- package com.kb.rest.client;
- import org.springframework.web.client.RestTemplate;
- import com.kb.rest.model.User;
- public class PutUserClient {
- public static void main(String[] args) {
- RestTemplate restTemplate = new RestTemplate();
- final String url = "http://localhost:8080/SpringRestCRUDJSON/user/updateUser";
- User user = new User();
- user.setId(1);
- user.setAge(20);
- user.setName("John1");
- restTemplate.put(url, user);
- // Verify updated user details
- final String getUrl = "http://localhost:8080/SpringRestCRUDJSON/user/getSpecificUser/1";
- User updatedUser = restTemplate.getForObject(getUrl, User.class);
- System.out.println("User updated details : ");
- System.out.println(updatedUser.getName() + " " + updatedUser.getAge() + " " + updatedUser.getId());
- }
- }
package com.kb.rest.client; import org.springframework.web.client.RestTemplate; import com.kb.rest.model.User; public class PutUserClient { public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); final String url = "http://localhost:8080/SpringRestCRUDJSON/user/updateUser"; User user = new User(); user.setId(1); user.setAge(20); user.setName("John1"); restTemplate.put(url, user); // Verify updated user details final String getUrl = "http://localhost:8080/SpringRestCRUDJSON/user/getSpecificUser/1"; User updatedUser = restTemplate.getForObject(getUrl, User.class); System.out.println("User updated details : "); System.out.println(updatedUser.getName() + " " + updatedUser.getAge() + " " + updatedUser.getId()); } }
In this client , we are making a PUT call with User details using put() method of RestTemplate
It takes 2 parameters which are
url – the end point of the Rest service
user – object which has to be updated by rest service
After posting, we are making a GET call with the same id and displaying the updated details.
DeleteUserClient.java
- package com.kb.rest.client;
- import org.springframework.web.client.RestTemplate;
- import com.kb.rest.model.User;
- public class DeleteUserClient {
- public static void main(String[] args) {
- RestTemplate restTemplate = new RestTemplate();
- final String url = "http://localhost:8080/SpringRestCRUDJSON/user/deleteUser/3";
- restTemplate.delete(url);
- // Verify updated user details
- final String getUrl = "http://localhost:8080/SpringRestCRUDJSON/user/getSpecificUser/3";
- User deletedUser = restTemplate.getForObject(getUrl, User.class);
- System.out.println("Deleted user details : " + deletedUser);
- }
- }
package com.kb.rest.client; import org.springframework.web.client.RestTemplate; import com.kb.rest.model.User; public class DeleteUserClient { public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); final String url = "http://localhost:8080/SpringRestCRUDJSON/user/deleteUser/3"; restTemplate.delete(url); // Verify updated user details final String getUrl = "http://localhost:8080/SpringRestCRUDJSON/user/getSpecificUser/3"; User deletedUser = restTemplate.getForObject(getUrl, User.class); System.out.println("Deleted user details : " + deletedUser); } }
In this client , we are making a DELETE call by passing User Id as part of URL using delete() method of RestTemplate
It takes 1 parameter which is
url – the end point of the Rest service
After the Delete call, we are making a GET call with the same id and displaying the updated details.
Step 4
Build and deploy the project
Step 5
Let’s see the output of all CRUD operations
POST
Run PostUserClient.java
output
we can see the user inserted details in the output
GET
Run GetUsersClient.java
output
we can see the List of Users available in the output
GET with specific user ID
Run GetSpecificUserClient.java
output
we can see the user details for a user with ID 1
PUT
Run PutUserClient.java
output
we can see that User name has been updated and we can see the same in the output as “John1”
DELETE
Run DeleteUserClient.java
output
we can see that User has been deleted and requesting to get the same user is giving as null in the output.
that could be nice if you could show a spring mvc apps who call spring rest service… both separate
Ya , will do it sometime, just a new project needs to be created to make a call,
Hi,
I am getting the following error. It looks like there is no data base connection. There is no properties for that in the example you provided
Exception in thread “main” org.springframework.web.client.ResourceAccessException: I/O error on GET request for “http://localhost:8080/SpringRestCRUDJSON/user/getAllUsers”:Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:602)
Please check below line mentioned before Step 1 in this artcile, where I have added values in DAO class.
Please refer Spring Rest CRUD Json Project for the below files
Your error looks like rest service is not deployed properly in server or firewall might be blocking it.
Please check it and let me know