- RESTful - Discussion
- RESTful - Useful Resources
- RESTful - Quick Guide
- RESTful - Questions and Answers
- RESTful - Java (JAX-RS)
- RESTful - Security
- RESTful - Caching
- RESTful - Statelessness
- RESTful - Methods
- RESTful - Addressing
- RESTful - Messages
- RESTful - Resources
- RESTful - First Application
- RESTful - Environment Setup
- RESTful - Introduction
- RESTful - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
RESTful Web Services - Methods
As we have discussed so far that RESTful web service makes heavy uses of HTTP verbs to determine the operation to be carried out on the specified resource(s). Following table states the examples of common use of HTTP Verbs.
HTTP Method | GET |
---|---|
URI | http://localhost:8080/UserManagement/rest/UserService/users |
Operation | Get pst of users |
Operation Type | Read Only |
HTTP Method | GET |
---|---|
URI | http://localhost:8080/UserManagement/rest/UserService/users/1 |
Operation | Get user of Id 1 |
Operation Type | Read Only |
HTTP Method | POST |
---|---|
URI | http://localhost:8080/UserManagement/rest/UserService/users/2 |
Operation | Insert user with Id 2 |
Operation Type | Non-Idempotent |
HTTP Method | PUT |
---|---|
URI | http://localhost:8080/UserManagement/rest/UserService/users/2 |
Operation | Update User with Id 2 |
Operation Type | N/A |
HTTP Method | DELETE |
---|---|
URI | http://localhost:8080/UserManagement/rest/UserService/users/1 |
Operation | Delete User with Id 1 |
Operation Type | Idempotent |
HTTP Method | OPTIONS |
---|---|
URI | http://localhost:8080/UserManagement/rest/UserService/users |
Operation | List the supported operations in web service |
Operation Type | Read Only |
HTTP Method | HEAD |
---|---|
URI | http://localhost:8080/UserManagement/rest/UserService/users |
Operation | Returns only HTTP Header, no Body |
Operation Type | Read Only |
Here are important points to be considered:
GET operations are read only and are safe.
PUT and DELETE operations are idempotent means their result will always same no matter how many times these operations are invoked.
PUT and POST operation are nearly same with the difference lying only in the result where PUT operation is idempotent and POST operation can cause different result.
Example
Let s update Example created in
tutorial to create a Web service which can perform CRUD (Create, Read, Update, Delete) operations. For simppcity, we ve used a file I/O to replace Database operations.Update UserService.java, User.java,UserDao.java files under the com.tutorialspoint package.
User.java
package com.tutorialspoint; import java.io.Seriapzable; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "user") pubpc class User implements Seriapzable { private static final long serialVersionUID = 1L; private int id; private String name; private String profession; pubpc User(){} pubpc User(int id, String name, String profession){ this.id = id; this.name = name; this.profession = profession; } pubpc int getId() { return id; } @XmlElement pubpc void setId(int id) { this.id = id; } pubpc String getName() { return name; } @XmlElement pubpc void setName(String name) { this.name = name; } pubpc String getProfession() { return profession; } @XmlElement pubpc void setProfession(String profession) { this.profession = profession; } @Override pubpc boolean equals(Object object){ if(object == null){ return false; }else if(!(object instanceof User)){ return false; }else { User user = (User)object; if(id == user.getId() && name.equals(user.getName()) && profession.equals(user.getProfession()) ){ return true; } } return false; } }
UserDao.java
package com.tutorialspoint; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.List; pubpc class UserDao { pubpc List<User> getAllUsers(){ List<User> userList = null; try { File file = new File("Users.dat"); if (!file.exists()) { User user = new User(1, "Mahesh", "Teacher"); userList = new ArrayList<User>(); userList.add(user); saveUserList(userList); } else{ FileInputStream fis = new FileInputStream(file); ObjectInputStream ois = new ObjectInputStream(fis); userList = (List<User>) ois.readObject(); ois.close(); } } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return userList; } pubpc User getUser(int id){ List<User> users = getAllUsers(); for(User user: users){ if(user.getId() == id){ return user; } } return null; } pubpc int addUser(User pUser){ List<User> userList = getAllUsers(); boolean userExists = false; for(User user: userList){ if(user.getId() == pUser.getId()){ userExists = true; break; } } if(!userExists){ userList.add(pUser); saveUserList(userList); return 1; } return 0; } pubpc int updateUser(User pUser){ List<User> userList = getAllUsers(); for(User user: userList){ if(user.getId() == pUser.getId()){ int index = userList.indexOf(user); userList.set(index, pUser); saveUserList(userList); return 1; } } return 0; } pubpc int deleteUser(int id){ List<User> userList = getAllUsers(); for(User user: userList){ if(user.getId() == id){ int index = userList.indexOf(user); userList.remove(index); saveUserList(userList); return 1; } } return 0; } private void saveUserList(List<User> userList){ try { File file = new File("Users.dat"); FileOutputStream fos; fos = new FileOutputStream(file); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(userList); oos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
UserService.java
package com.tutorialspoint; import java.io.IOException; import java.util.List; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.OPTIONS; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; @Path("/UserService") pubpc class UserService { UserDao userDao = new UserDao(); private static final String SUCCESS_RESULT="<result>success</result>"; private static final String FAILURE_RESULT="<result>failure</result>"; @GET @Path("/users") @Produces(MediaType.APPLICATION_XML) pubpc List<User> getUsers(){ return userDao.getAllUsers(); } @GET @Path("/users/{userid}") @Produces(MediaType.APPLICATION_XML) pubpc User getUser(@PathParam("userid") int userid){ return userDao.getUser(userid); } @POST @Path("/users") @Produces(MediaType.APPLICATION_XML) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) pubpc String createUser(@FormParam("id") int id, @FormParam("name") String name, @FormParam("profession") String profession, @Context HttpServletResponse servletResponse) throws IOException{ User user = new User(id, name, profession); int result = userDao.addUser(user); if(result == 1){ return SUCCESS_RESULT; } return FAILURE_RESULT; } @PUT @Path("/users") @Produces(MediaType.APPLICATION_XML) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) pubpc String updateUser(@FormParam("id") int id, @FormParam("name") String name, @FormParam("profession") String profession, @Context HttpServletResponse servletResponse) throws IOException{ User user = new User(id, name, profession); int result = userDao.updateUser(user); if(result == 1){ return SUCCESS_RESULT; } return FAILURE_RESULT; } @DELETE @Path("/users/{userid}") @Produces(MediaType.APPLICATION_XML) pubpc String deleteUser(@PathParam("userid") int userid){ int result = userDao.deleteUser(userid); if(result == 1){ return SUCCESS_RESULT; } return FAILURE_RESULT; } @OPTIONS @Path("/users") @Produces(MediaType.APPLICATION_XML) pubpc String getSupportedOperations(){ return "<operations>GET, PUT, POST, DELETE</operations>"; } }
Now using Ecppse, export your apppcation as a war file and deploy the same in tomcat. To create WAR file using ecppse, follow the option File -> export -> Web > War File and finally select project UserManagement and destination folder. To deploy war file in Tomcat, place the UserManagement.war in Tomcat Installation Directory > webapps directory and start the Tomcat.
Testing the Web Service
Jersey provides APIs to create a Web Service Cpent to test web services. We ve created a sample test class WebServiceTester.java under the com.tutorialspoint package in the same project.
WebServiceTester.java
package com.tutorialspoint; import java.util.List; import javax.ws.rs.cpent.Cpent; import javax.ws.rs.cpent.CpentBuilder; import javax.ws.rs.cpent.Entity; import javax.ws.rs.core.Form; import javax.ws.rs.core.GenericType; import javax.ws.rs.core.MediaType; pubpc class WebServiceTester { private Cpent cpent; private String REST_SERVICE_URL = "http://localhost:8080/UserManagement/rest/UserService/users"; private static final String SUCCESS_RESULT="<result>success</result>"; private static final String PASS = "pass"; private static final String FAIL = "fail"; private void init(){ this.cpent = CpentBuilder.newCpent(); } pubpc static void main(String[] args){ WebServiceTester tester = new WebServiceTester(); //initiapze the tester tester.init(); //test get all users Web Service Method tester.testGetAllUsers(); //test get user Web Service Method tester.testGetUser(); //test update user Web Service Method tester.testUpdateUser(); //test add user Web Service Method tester.testAddUser(); //test delete user Web Service Method tester.testDeleteUser(); } //Test: Get pst of all users //Test: Check if pst is not empty private void testGetAllUsers(){ GenericType<List<User>> pst = new GenericType<List<User>>() {}; List<User> users = cpent .target(REST_SERVICE_URL) .request(MediaType.APPLICATION_XML) .get(pst); String result = PASS; if(users.isEmpty()){ result = FAIL; } System.out.println("Test case name: testGetAllUsers, Result: " + result ); } //Test: Get User of id 1 //Test: Check if user is same as sample user private void testGetUser(){ User sampleUser = new User(); sampleUser.setId(1); User user = cpent .target(REST_SERVICE_URL) .path("/{userid}") .resolveTemplate("userid", 1) .request(MediaType.APPLICATION_XML) .get(User.class); String result = FAIL; if(sampleUser != null && sampleUser.getId() == user.getId()){ result = PASS; } System.out.println("Test case name: testGetUser, Result: " + result ); } //Test: Update User of id 1 //Test: Check if result is success XML. private void testUpdateUser(){ Form form = new Form(); form.param("id", "1"); form.param("name", "suresh"); form.param("profession", "clerk"); String callResult = cpent .target(REST_SERVICE_URL) .request(MediaType.APPLICATION_XML) .put(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), String.class); String result = PASS; if(!SUCCESS_RESULT.equals(callResult)){ result = FAIL; } System.out.println("Test case name: testUpdateUser, Result: " + result ); } //Test: Add User of id 2 //Test: Check if result is success XML. private void testAddUser(){ Form form = new Form(); form.param("id", "2"); form.param("name", "naresh"); form.param("profession", "clerk"); String callResult = cpent .target(REST_SERVICE_URL) .request(MediaType.APPLICATION_XML) .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), String.class); String result = PASS; if(!SUCCESS_RESULT.equals(callResult)){ result = FAIL; } System.out.println("Test case name: testAddUser, Result: " + result ); } //Test: Delete User of id 2 //Test: Check if result is success XML. private void testDeleteUser(){ String callResult = cpent .target(REST_SERVICE_URL) .path("/{userid}") .resolveTemplate("userid", 2) .request(MediaType.APPLICATION_XML) .delete(String.class); String result = PASS; if(!SUCCESS_RESULT.equals(callResult)){ result = FAIL; } System.out.println("Test case name: testDeleteUser, Result: " + result ); } }
Now run the tester using Ecppse. Right cpck on the file, and follow the option Run as -> Java Apppcation. You ll see the following result in Ecppse console −
Test case name: testGetAllUsers, Result: pass Test case name: testGetUser, Result: pass Test case name: testUpdateUser, Result: pass Test case name: testAddUser, Result: pass Test case name: testDeleteUser, Result: passAdvertisements