পৃষ্ঠাসমূহ

.

Search Your Article

Total Pageviews

Saturday, March 11, 2017

RESTful Web Services - Quick Guide

RESTful Web Services - Introduction

What is REST?

REST stands for REpresentational State Transfer. REST is a web standards based architecture and uses HTTP Protocol for data communication. It revolves around resources where every component is a resource and a resource is accessed by a common interface using HTTP standard methods. REST was first introduced by Roy Fielding in year 2000.

In REST architecture, a REST Server simply provides access to resources and the REST client accesses and presents the resources. Here each resource is identified by URIs/ Global IDs. REST uses various representations to represent a resource like Text, JSON and XML. JSON is now the most popular format being used in Web Services.

HTTP Methods

The following HTTP methods are most commonly used in a REST based architecture.
  • GET − Provides a read only access to a resource.
  • PUT − Used to create a new resource.
  • DELETE − Used to remove a resource.
  • POST − Used to update an existing resource or create a new resource.
  • OPTIONS − Used to get the supported operations on a resource.

RESTFul Web Services

A web service is a collection of open protocols and standards used for exchanging data between applications or systems. Software applications written in various programming languages and running on various platforms can use web services to exchange data over computer networks like the Internet in a manner similar to inter-process communication on a single computer. This interoperability (e.g., between Java and Python, or Windows and Linux applications) is due to the use of open standards.
Web services based on REST Architecture are known as RESTful Web Services. These web services use HTTP methods to implement the concept of REST architecture. A RESTful web service usually defines a URI (Uniform Resource Identifier), which is a service that provides resource representation such as JSON and a set of HTTP Methods.

Creating RESTFul Web Service

In this tutorial, we will create a web service called User Management with the following functionalities −
Sr.No. HTTP Method URI Operation Operation Type
1 GET /UserService/users Get list of users Read Only
2 GET /UserService/users/1 Get User with Id 1 Read Only
3 PUT /UserService/users/2 Insert User with Id 2 Idempotent
4 POST /UserService/users/2 Update User with Id 2 N/A
5 DELETE /UserService/users/1 Delete User with Id 1 Idempotent
6 OPTIONS /UserService/users List the supported operations in web service Read Only

RESTful Web Services - Environment Setup

This tutorial will guide you on how to prepare a development environment to start your work with Jersey Framework to create RESTful Web Services. Jersey framework implements JAX-RS 2.0 API, which is a standard specification to create RESTful Web Services. This tutorial will also teach you how to setup JDK, Tomcat and Eclipse on your machine before you the Jersey Framework is setup.

Setup Java Development Kit (JDK)

You can download the latest version of SDK from Oracle's Java site − Java SE Downloads. You will find the instructions for installing JDK in the downloaded files. Follow the given instructions to install and configure the setup. Finally set the PATH and JAVA_HOME environment variables to refer to the directory that contains Java and Javac, typically java_install_dir/bin and java_install_dir respectively.
If you are running Windows and installed the JDK in C:\jdk1.7.0_75, you would have to put the following line in your C:\autoexec.bat file.
set PATH = C:\jdk1.7.0_75\bin;%PATH% 
set JAVA_HOME = C:\jdk1.7.0_75
Alternatively, on Windows NT/2000/XP, you could also right-click on My Computer → select Properties → then Advanced → then Environment Variables. Then, you would update the PATH value and press the OK button.
On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.7.0_75 and you use the C Shell, you would put the following into your .cshrc file.
setenv PATH /usr/local/jdk1.7.0_75/bin:$PATH 
setenv JAVA_HOME /usr/local/jdk1.7.0_75
Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to confirm that the IDE knows where you installed Java, otherwise do proper setup as given document of the IDE.

Setup Eclipse IDE

All the examples in this tutorial have been written using the Eclipse IDE. So, I would suggest you should have the latest version of Eclipse installed on your machine.
To install Eclipse IDE, download the latest Eclipse binaries from https://www.eclipse.org/downloads/. Once you downloaded the installation, unpack the binary distribution to a convenient location. For example, in C:\eclipse on windows, or /usr/local/eclipse on Linux/Unix and finally set the PATH variable appropriately.
Eclipse can be started by executing the following commands on a windows machine, or you can simply double click on eclipse.exe.
%C:\eclipse\eclipse.exe
Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine −
$/usr/local/eclipse/eclipse 
After a successful startup, if everything is fine, then your screen should display the following result −
Eclipse Home Page

Setup Jersey Framework Libraries

Now, if everything is fine, then you can proceed to setup the Jersey framework. Following are a few simple steps to download and install the framework on your machine.
  • Make a choice whether you want to install Jersey on Windows, or Unix and then proceed to the next step to download the .zip file for windows and then the .tz file for Unix.
  • Download the latest version of Jersey framework binaries from the following link – https://jersey.java.net/download.html.
  • At the time of writing this tutorial, I downloaded jaxrs-ri-2.17.zip on my Windows machine and when you unzip the downloaded file it will give you the directory structure inside E:\jaxrs-ri-2.17\jaxrs-ri as shown in the following screenshot.
Jaxrs Directory You will find all the Jersey libraries in the directories C:\jaxrs-ri-2.17\jaxrs-ri\lib and dependencies in C:\jaxrs-ri-2.17\jaxrs-ri\ext. Make sure you set your CLASSPATH variable on this directory properly otherwise you will face problem while running your application. If you are using Eclipse, then it is not required to set the CLASSPATH because all the settings will be done through Eclipse.

Setup Apache Tomcat

You can download the latest version of Tomcat from https://tomcat.apache.org/. Once you downloaded the installation, unpack the binary distribution into a convenient location. For example in C:\apache-tomcat-7.0.59 on windows, or /usr/local/apache-tomcat-7.0.59 on Linux/Unix and set CATALINA_HOME environment variable pointing to the installation locations.
Tomcat can be started by executing the following commands on a windows machine, or you can simply double click on startup.bat.
%CATALINA_HOME%\bin\startup.bat
or
C:\apache-tomcat-7.0.59\bin\startup.bat 
Tomcat can be started by executing the following commands on a Unix (Solaris, Linux, etc.) machine −
$CATALINA_HOME/bin/startup.sh
or
/usr/local/apache-tomcat-7.0.59/bin/startup.sh
After a successful startup, the default web applications included with Tomcat will be available by visiting http://localhost:8080/. If everything is fine then it should display the following result −
Tomcat Further information about configuring and running Tomcat can be found in the documentation included on this page. This information can also be found on the Tomcat website − https://tomcat.apache.org.
Tomcat can be stopped by executing the following commands on a windows machine −
%CATALINA_HOME%\bin\shutdown 
or
C:\apache-tomcat-7.0.59\bin\shutdown 
Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.) machine −
$CATALINA_HOME/bin/shutdown.sh 
or
/usr/local/apache-tomcat-7.0.59/bin/shutdown.sh
Once you are done with this last step, you are ready to proceed for your first Jersey example which you will see in the next chapter.

RESTful Web Services - First Application

Let us start writing the actual RESTful web services with Jersey Framework. Before you start writing your first example using the Jersey Framework, you have to make sure that you have setup your Jersey environment properly as explained in the RESTful Web Services - Environment Setup chapter. Here, I am also assuming that you have a little working knowledge of Eclipse IDE.
So, let us proceed to write a simple Jersey Application which will expose a web service method to display the list of users.

Creating a Java Project

The first step is to create a Dynamic Web Project using Eclipse IDE. Follow the option File → New → Project and finally select the Dynamic Web Project wizard from the wizard list. Now name your project as UserManagement using the wizard window as shown in the following screenshot −
Dynamic Web Project Wizard Once your project is created successfully, you will have the following content in your Project Explorer
Usermanagement Directories

Adding the Required Libraries

As a second step let us add Jersey Framework and its dependencies (libraries) in our project. Copy all jars from following directories of download jersey zip folder in WEB-INF/lib directory of the project.
  • \jaxrs-ri-2.17\jaxrs-ri\api
  • \jaxrs-ri-2.17\jaxrs-ri\ext
  • \jaxrs-ri-2.17\jaxrs-ri\lib
Now, right click on your project name UserManagement and then follow the option available in context menu − Build Path → Configure Build Path to display the Java Build Path window.
Now use Add JARs button available under Libraries tab to add the JARs present in WEBINF/lib directory.

Creating the Source Files

Now let us create the actual source files under the UserManagement project. First we need to create a package called com.tutorialspoint. To do this, right click on src in package explorer section and follow the option − New → Package.
Next we will create UserService.java, User.java,UserDao.java files under the com.tutorialspoint package.
User.java
package com.tutorialspoint;  

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 id; 
   private String name; 
   private String profession;  
   public User(){} 
    
   public User(int id, String name, String profession){  
      this.id = id; 
      this.name = name; 
      this.profession = profession; 
   }  
   public int getId() { 
      return id; 
   }  
   @XmlElement 
   public void setId(int id) { 
      this.id = 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
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;  

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
package com.tutorialspoint;  

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(); 
   }  
}
There are two important points to be noted about the main program,

UserService.java

  • The first step is to specify a path for the web service using @Path annotation to the UserService.
  • The second step is to specify a path for the particular web service method using @Path annotation to method of UserService.

Creating the Web.xml configuration File

You need to create a Web xml Configuration file which is an XML file and is used to specify Jersey framework servlet for our application.
web.xml
<?xml version = "1.0" encoding = "UTF-8"?> 
<web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"  
   xmlns = "http://java.sun.com/xml/ns/javaee"  
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  
   http://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</servletclass> 
      <init-param> 
         <param-name>jersey.config.server.provider.packages</param-name> 
         <param-value>com.tutorialspoint</param-value> 
      </init-param> 
   </servlet> 
   <servlet-mapping> 
      <servlet-name>Jersey RESTful Application</servlet-name> 
      <url-pattern>/rest/*</url-pattern> 
   </servlet-mapping>   
</web-app>

Deploying the Program

Once you are done with creating source and web configuration files, you are ready for this step which is compiling and running your program. To do this, using Eclipse, export your application as a war file and deploy the same in tomcat.
To create a WAR file using eclipse, follow the option File → export → Web → War File and finally select project UserManagement and destination folder. To deploy a war file in Tomcat, place the UserManagement.war in the Tomcat Installation Directory → webapps directory and start the Tomcat.

Running the Program

We are using Postman, a Chrome extension, to test our webservices.
Make a request to UserManagement to get list of all the users. Put http://localhost:8080/UserManagement/rest/UserService/users in POSTMAN with GET request and see the following result.
RESTful API, All users Congratulations, you have created your first RESTful Application successfully.

No comments:

Post a Comment