RESTful Web Service

What is RESTful Web Service?

Table of Contents

RESTful web service is a very lightweight, maintainable, and scalable web service that exposes API from your application in a secure, uniform, and stateless manner to the calling client. The calling client can then perform predefined operations using Restful service. The full form of REST is Representational State Transfer, and the protocol used is HTTP.

Key Elements of RESTful:

  • Resources: It is the first key element of RESTful. Suppose a web application on the server contains records of several employees. To access the record of a particular employee using REST, you need to issue some command say https://www.abc.com/employee-1, which will tell the server to fetch details of the employee whose employee number is 1.
  • Request Verbs: It describes what to do with the resource. There are many verbs available like POST, PUT, GET, and DELETE. In https://www.abc.com/employee-1, the web browser is issuing a GET verb because it wants to fetch the employee record details.
  • Request Headers: The additional information sent with the request (maybe the type of response required or authorization details).
  • Request Body: Here, data is sent with the request. Data is usually sent in the request when a POST request is made. 
  • Response Body: The main body of the response is Response Body. In https://www.abc.com/employee-1, the webserver may return an XML document containing all the details of the employee.
  • Response Status Codes: The general codes, which are returned with the response are Response Status Codes. For example, code 200 is normally returned when there is no error in returning the response.

Methods in RESTful:

The below diagram shows all the methods used in REST:

  • POST: It is used to create a resource on the server.
  • GET: It is used to retrieve a resource from the server.
  • PUT: It is used to change the state of the resource or to update it.
  • DELETE: It is used to delete a resource from the server.

Advantages of RESTful:

  • Heterogeneous languages and environments: Web applications in REST can be developed in various programming languages. Also, they can reside in different environments (maybe Windows or Linux). The result should be that they should be able to talk to each other.
  • The event of devices: Nowadays, everything should work on mobile devices. RESTful Web Service API’s makes it simpler as you don’t need to know what is the underlying layer for the device.
  • The event of the cloud: Nowadays, all the applications are moving to the cloud. All the cloud-based architectures work on the REST principle.

Principles of RESTful:

The REST architecture depends on the following principles:

  1. RESTful Client-Server: It is the most fundamental principle of REST. If the client sends a request to the server, the server can either reject the request or provide an appropriate response as per the request.
  2. Stateless: This concept is required so that the server can process the response adequately. It is a simple independent question-answer sequence. The client asks the question; the server gives the answer. The client again asks the question, but the server responds to the new question independently.
  3. Cache: This concept helps in the problem of stateless. If the client asks a question many times, and the server responds to each request independently, it will increase the traffic across the network. Thus, the concept of the cache will store the client’s requests. If the client gives the same request, then instead of going to the server, it will just go to the cache and fetch the required information. This saves the amount of traffic.
  4. Layered System: In this principle, any middle layer can be inserted between the client and the server.
  5. Interface/Uniform Contract: These include the techniques on which the RESTful works such as POST, GET, PUT, and DELETE.

How to create the first RESTful Web Service?

Before writing RESTful Web Services, you need Jersey framework. Step 1: Open Eclipse IDE. Go to File > New > Project. Select Dynamic Web Project. Name your project.

https://4.bp.blogspot.com/-AAzM2Wo2EBw/UV0zq-hdD5I/AAAAAAAAA8M/GEBLNsPKMy8/s1600/NewProjectRESTWSExample.gif

Step 2: Add Jersey Framework and its dependencies (libraries). Copy all the jar files available from the downloaded Jersey folder in WEB-INF/lib directory of your project.

\jaxrs-ri-2.17\jaxrs-ri\api
\jaxrs-ri-2.17\jaxrs-ri\ext
\jaxrs-ri-2.17\jaxrs-ri\lib

Right-click on your project name and then go to the context menu > Build Path > Configure Build Path.

Use the Add JARs button present under Libraries to add the JAR files.

Step 3: Create the source files.

User.java

import java.io.Serializable;  
import javax.xml.bind.annotation.XmlElement; 
import javax.xml.bind.annotation.XmlRootElement; 
@XmlRootElement(name = "user") 
public class User implements Serializable {  
   private static final long serialVersionUID = 1L; 
   private int emp_id; 
   private String name; 
   private String profession;  
   public User(){}     
   public User(int emp_id, String name, String profession){  
      this.emp_id = emp_id; 
      this.name = name; 
      this.profession = profession; 
   }  
   public int getId() { 
      return emp_id; 
   }  
   @XmlElement 
   public void setId(int emp_id) { 
      this.emp_id = emp_id; 
   } 
   public String getName() { 
      return name; 
   } 
   @XmlElement
   public void setName(String name) { 
      this.name = name; 
   } 
   public String getProfession() { 
      return profession; 
   } 
   @XmlElement 
   public void setProfession(String profession) { 
      this.profession = profession; 
   }   
}

UserDao.java

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;  
public class UserDao { 
   public 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; 
   } 
   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

import java.util.List; 
import javax.ws.rs.GET; 
import javax.ws.rs.Path; 
import javax.ws.rs.Produces; 
import javax.ws.rs.core.MediaType;  
@Path("/UserService") 
public class UserService {  
   UserDao userDao = new UserDao();  
   @GET 
   @Path("/users") 
   @Produces(MediaType.APPLICATION_XML) 
   public List<User> getUsers(){ 
      return userDao.getAllUsers(); 
   }  
}

Step 4: Create the web.xml configuration file.

<?xml version = "1.0" encoding = "UTF-8"?> 
<web-app xmlns:xsi = "https://www.w3.org/2001/XMLSchema-instance"  
   xmlns = "https://java.sun.com/xml/ns/javaee"  
   xsi:schemaLocation="https://java.sun.com/xml/ns/javaee  
   https://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"  
   id = "WebApp_ID" version = "3.0"> 
   <display-name>User Management</display-name> 
   <servlet> 
      <servlet-name>Jersey RESTful Application</servlet-name> 
      <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> 
      <init-param> 
         <param-name>jersey.config.server.provider.packages</param-name> 
         <param-value>com.newproject</param-value> 
      </init-param> 
   </servlet> 
   <servlet-mapping> 
      <servlet-name>Jersey RESTful Application</servlet-name> 
      <url-pattern>/rest/*</url-pattern> 
   </servlet-mapping>   
</web-app>

How to Deploy the Project?

Export your above created project as a war file and deploy it in Tomcat. For creating a WAR file, go to File > Export > Web > War File. Select your project name and location of the project. To deploy this project in Tomcat, place your WAR file in Tomcat Installation Directory > webapps directory. Start the Tomcat.

How to run the Project?

We are using Postman here to run the program. Put URL http://localhost:8080/UserManagement/rest/UserService/users in Postman, and you will get the following output:

RESTful API, All users

3 Responses

  1. Hi,thank you for the guide to learn Rest API.
    But I have a little problem here:
    After launch tomcat and run the webservice, the browser show me
    “java.lang.ClassCastException: org.glassfish.jersey.servlet.ServletContainer cannot be cast to javax.servlet.Servlet”.
    I have had google how to solve ,but failed.
    Tomcat 9.0/ java 1.8.0.251
    Could you please some advice for this ?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share this article
Subscribe
By pressing the Subscribe button, you confirm that you have read our Privacy Policy.
Need a Free Demo Class?
Join H2K Infosys IT Online Training
Enroll Free demo class