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.

CRUD_operation_JAXB_Table

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


rest_spring_crud_json_proj_rest_template_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

  1. package com.kb.rest.model;
  2.  
  3. public class User {
  4.     private String name;
  5.     private int age;
  6.     private int id;
  7.     public String getName() {
  8.         return name;
  9.     }
  10.     public void setName(String name) {
  11.         this.name = name;
  12.     }
  13.     public int getAge() {
  14.         return age;
  15.     }
  16.     public void setAge(int age) {
  17.         this.age = age;
  18.     }
  19.     public int getId() {
  20.         return id;
  21.     }
  22.     public void setId(int id) {
  23.         this.id = id;
  24.     }
  25.  
  26. }
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

  1. package com.kb.rest.model;
  2.  
  3. import java.util.List;
  4.  
  5. public class UserDetailsResponse {
  6.     private List<User> users;
  7.  
  8.     public List<User> getUsers() {
  9.         return users;
  10.     }
  11.  
  12.     public void setUsers(List<User> users) {
  13.         this.users = users;
  14.     }
  15.  
  16. }
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

  1. package com.kb.rest.controllers;
  2.  
  3. import java.util.List;
  4.  
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Controller;
  7. import org.springframework.web.bind.annotation.PathVariable;
  8. import org.springframework.web.bind.annotation.RequestBody;
  9. import org.springframework.web.bind.annotation.RequestMapping;
  10. import org.springframework.web.bind.annotation.RequestMethod;
  11. import org.springframework.web.bind.annotation.ResponseBody;
  12.  
  13. import com.kb.rest.model.User;
  14. import com.kb.rest.model.UserDetailsResponse;
  15. import com.kb.rest.service.UserService;
  16.  
  17. @Controller
  18. @RequestMapping("/user")
  19. public class RestController {
  20.  
  21.     @Autowired
  22.     private UserService userService;
  23.    
  24.     // CRUD -- CREATE operation
  25.     @RequestMapping(value = "/create", method = RequestMethod.POST)
  26.     public @ResponseBody User createUser(@RequestBody User user) {
  27.         User userResponse = userService.createUser(user);
  28.         return userResponse;
  29.     }
  30.  
  31.     // CRUD -- READ operation
  32.     @RequestMapping(value = "/getAllUsers", method = RequestMethod.GET)
  33.     public @ResponseBody UserDetailsResponse getAllUsers() {
  34.         List<User> userList = userService.getAllUsers();
  35.         UserDetailsResponse userDetailsResponse = new UserDetailsResponse();
  36.         userDetailsResponse.setUsers(userList);
  37.         return userDetailsResponse;
  38.     }
  39.  
  40.     // CRUD -- READ operation
  41.     @RequestMapping(value = "/getSpecificUser/{id}", method = RequestMethod.GET)
  42.     public @ResponseBody User getUserForId(@PathVariable ("id") int id) {
  43.         User user = userService.getUserForId(id);
  44.         return user;
  45.     }
  46.  
  47.     // CRUD -- UPDATE operation
  48.     @RequestMapping(value = "/updateUser", method = RequestMethod.PUT)
  49.     public @ResponseBody User updateUser(@RequestBody User user) {
  50.         User userResponse = userService.updateUser(user);
  51.         return userResponse;
  52.     }
  53.  
  54.     // CRUD -- DELETE operation
  55.     @RequestMapping(value = "/deleteUser/{id}", method = RequestMethod.DELETE)
  56.     public @ResponseBody User deleteeUser(@PathVariable("id") int id) {
  57.         User userResponse = userService.deleteUser(id);
  58.         return userResponse;
  59.     }
  60. }
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

  1. package com.kb.rest.client;
  2.  
  3. import org.springframework.web.client.RestTemplate;
  4.  
  5. import com.kb.rest.model.User;
  6.  
  7. public class PostUserClient {
  8.     public static void main(String[] args) {
  9.         RestTemplate restTemplate = new RestTemplate();
  10.         final String url = "http://localhost:8080/SpringRestCRUDJSON/user/create";
  11.         User user = new User();
  12.         user.setId(1);
  13.         user.setAge(45);
  14.         user.setName("John");
  15.         User addedUser = restTemplate.postForObject(url, user, User.class);
  16.         System.out.println("User Inserted is : " + addedUser.getName());
  17.     }
  18. }
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

  1. package com.kb.rest.client;
  2.  
  3. import org.springframework.web.client.RestTemplate;
  4.  
  5. import com.kb.rest.model.User;
  6. import com.kb.rest.model.UserDetailsResponse;
  7.  
  8. public class GetUsersClient {
  9.     public static void main(String[] args) {
  10.         RestTemplate restTemplate = new RestTemplate();
  11.         final String url = "http://localhost:8080/SpringRestCRUDJSON/user/getAllUsers";
  12.         UserDetailsResponse userDetailsResponse = restTemplate.getForObject(url, UserDetailsResponse.class);
  13.         System.out.println("User retrieved details : ");
  14.         for (User user : userDetailsResponse.getUsers()) {
  15.             System.out.println(user.getName() + " " + user.getAge() + " " + user.getId());
  16.         }
  17.  
  18.     }
  19.  
  20. }
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

  1. package com.kb.rest.client;
  2.  
  3. import org.springframework.web.client.RestTemplate;
  4.  
  5. import com.kb.rest.model.User;
  6.  
  7. public class GetSpecificUserClient {
  8.     public static void main(String[] args) {
  9.         RestTemplate restTemplate = new RestTemplate();
  10.         final String url = "http://localhost:8080/SpringRestCRUDJSON/user/getSpecificUser/1";
  11.         User user = restTemplate.getForObject(url, User.class);
  12.         System.out.println("User retrieved details : ");
  13.         System.out.println(user.getName() + " " + user.getAge() + " " + user.getId());
  14.  
  15.     }
  16. }
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

  1. package com.kb.rest.client;
  2.  
  3. import org.springframework.web.client.RestTemplate;
  4.  
  5. import com.kb.rest.model.User;
  6.  
  7. public class PutUserClient {
  8.     public static void main(String[] args) {
  9.         RestTemplate restTemplate = new RestTemplate();
  10.         final String url = "http://localhost:8080/SpringRestCRUDJSON/user/updateUser";
  11.         User user = new User();
  12.         user.setId(1);
  13.         user.setAge(20);
  14.         user.setName("John1");
  15.         restTemplate.put(url, user);
  16.  
  17.         // Verify updated user details
  18.         final String getUrl = "http://localhost:8080/SpringRestCRUDJSON/user/getSpecificUser/1";
  19.         User updatedUser = restTemplate.getForObject(getUrl, User.class);
  20.         System.out.println("User updated details : ");
  21.         System.out.println(updatedUser.getName() + " " + updatedUser.getAge() + " " + updatedUser.getId());
  22.  
  23.     }
  24. }
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

  1. package com.kb.rest.client;
  2.  
  3. import org.springframework.web.client.RestTemplate;
  4.  
  5. import com.kb.rest.model.User;
  6.  
  7. public class DeleteUserClient {
  8.     public static void main(String[] args) {
  9.         RestTemplate restTemplate = new RestTemplate();
  10.         final String url = "http://localhost:8080/SpringRestCRUDJSON/user/deleteUser/3";
  11.         restTemplate.delete(url);
  12.  
  13.         // Verify updated user details
  14.         final String getUrl = "http://localhost:8080/SpringRestCRUDJSON/user/getSpecificUser/3";
  15.         User deletedUser = restTemplate.getForObject(getUrl, User.class);
  16.         System.out.println("Deleted user details : " + deletedUser);
  17.  
  18.     }
  19. }
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.

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on