Showing posts with label Restful web services. Show all posts
Showing posts with label Restful web services. Show all posts

Thursday, April 4, 2013

RESTful web service tutorial

In this post,we will see RESTful web service introduction.

Part-1:Introduction to web services
Part-2:SOAP web service introduction 
Part-3:RESTful web service introduction
Part-4:SOAP web service example in java using eclipse
Part-5:JAX-WS web service eclipse tutorial
Part-6:JAX-WS web service deployment on tomcat 
Part-7:Create RESTful web service in java(JAX-RS) using jersey

REST is an architectural style which was brought in by Roy Fielding in 2000 in his doctoral thesis.

In the web services terms, REpresentational State Transfer (REST) is  a stateless client-server architecture in which the web services are viewed as resources and can be identified by their URIs. Web service clients that want to use these resources access via globally defined set of remote methods that describe the action to be performed on the resource.

It consists of two components REST server which provides access to the resources and a REST client which accesses and modify the REST resources.

In the REST architecture style, clients and servers exchange representations of resources by using a standardized interface and protocol.REST isn't protocol specific, but when people talk about REST they usually mean REST over HTTP.

The response from server is considered as the representation of the resources. This representation can be generated from one resource or more number of resources.


REST allows that resources have different representations, e.g.xml, json etc. The rest client can ask for specific representation via the HTTP protocol.

HTTP methods : 

RESTful web services use HTTP protocol methods for the operations they perform.Methods are:
  • GET:It defines a reading access of the resource without side-effects.This operation is idempotent i.e.they can be applied multiple times without changing the result
  • PUT :  It creates a new resource.It must also be idempotent.
  • DELETE : It removes the resources. The operations are idempotent i.e. they can get repeated without leading to different results.
  • POST :It updates an existing resource or creates a new resource.

Features of RESTful web services:

Resource identification through URI:Resources are identified by their URIs (typically links on internet). So, a client can directly access a RESTful Web Services using the URIs of the resources (same as you put a website address in the browser’s address bar and get some representation as response).

Uniform interface: Resources are manipulated using a fixed set of four create, read, update, delete operations: PUT, GET, POST, and DELETE.

Client-Server: A clear separation concerns is the reason behind this constraint. Separating concerns between the Client and Server helps improve portability in the Client and Scalability of the server components.

Stateless: each request from client to server must contain all the information necessary to understand the request, and cannot take advantage of any stored context on the server.

Cache: to improve network efficiency responses must be capable of being labeled as cacheable or non-cacheable.

Named resources - the system is comprised of resources which are named using a URL.

Interconnected resource representations - the representations of the resources are interconnected using URLs, thereby enabling a client to progress from one state to another.

Layered components - intermediaries, such as proxy servers, cache servers, gateways, etc, can be inserted between clients and resources to support performance, security, etc.

Self-descriptive messages: Resources are decoupled from their representation so that their content can be accessed in a variety of formats, such as HTML, XML, plain text, PDF, JPEG, JSON, and others. 

Create RESTful web services in java(JAX-RS) using jersey

In this post,we will develop RESTful web service using jersey in eclipse

Web service Tutorial Content:

Part-1:Introduction to web services
Part-2:SOAP web service introduction 
Part-3:RESTful web service introduction
Part-4:SOAP web service example in java using eclipse
Part-5:JAX-WS web service eclipse tutorial
Part-6:JAX-WS web service deployment on tomcat 
Part-7:Create RESTful web service in java(JAX-RS) using jersey

Java API for RESTful Web Services (JAX-RS), is a set if APIs to developer REST service. JAX-RS is part of the Java EE6, and make developers to develop REST web application easily.

Jersey is the reference implementation for this specification. Jersey contains basically a REST server and a REST client. The core client can communicate with the server using jersey lib.

On the server side Jersey uses a servlet which scans predefined classes to identify RESTful resources. Via the web.xml configuration file for your web application.

The base URL of this servlet is:
http://your_domain:port/display-name/url-pattern/path_from_rest_class 
This servlet analyzes the incoming HTTP request and selects the correct class and method depending on  request. This selection is based on annotations provided in the class and methods. 

Prerequisites:


1) Open eclipse.
2) Create new dynamic web project named "RESTfulWebserviceExample"

3) Now go to location where you have download jersey and go to jersey-archive-1.17->lib
folder.you can have all jars but for now you can copy following jars
  • asm-3.1
  • jersey-client-1.17
  • jersey-core-1.17
  • jersey-server-1.17
  • jersey-servlet-1.17
  • jsr311-api-1.1.1
Paste all above copied jars to WebContent->WEB-INF->lib

Add all these jars to eclipse build path.
Right click on project(RESTfulWebserviceExample)->properties


Click on Java Build Path and then Add jars as shown in above diagram.

go to project->WebContent->WEB-INF->lib and select all jars then click on ok.

Click ok.Jersey jars added to class path.
4) Create new package named "org.arpit.javapostsforlearning.webservice"

5)Create  FeetToInchAndInchToFeetConversionService.java

package org.arpit.javapostsforlearning.webservice;
/**
* @author Arpit Mandliya
*/

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("ConversionService")
public class FeetToInchAndInchToFeetConversionService {
@GET
@Path("/InchToFeet/{i}")
@Produces(MediaType.TEXT_XML)
public String convertInchToFeet(@PathParam("i") int i) {

int inch=i;
double feet = 0;
feet =(double) inch/12;

return "<InchToFeetService>"
+ "<Inch>" + inch + "</Inch>"
+ "<Feet>" + feet + "</Feet>"
+ "</InchToFeetService>";
}

@Path("/FeetToInch/{f}")
@GET
@Produces(MediaType.TEXT_XML)
public String convertFeetToInch(@PathParam("f") int f) {
int inch=0;
int feet = f;
inch = 12*feet;

return "<FeetToInchService>"
+ "<Feet>" + feet + "</Feet>"
+ "<Inch>" + inch + "</Inch>"
+ "</FeetToInchService>";
}
}

@Path(/your_path_at_class_level) : Sets the path to base URL + /your_path_at_class_level. The base URL is based on your application name, the servlet and the URL pattern from the web.xml" configuration file.

@Path(/your_path_at_method_level): Sets path to base URL + /your_path_at_class_level+ /your_path_at_method_level

@Produces(MediaType.TEXT_XML [, more-types ]): @Produces defines which MIME type is delivered by a method annotated with @GET. In the example text ("text/XML") is produced.

@PathParam: Used to inject values from the URL into a method parameter.This way you inject inch in convertFeetToInch method and convert that to feet.
6)Now you need to create web.xml and put it under /RESTfulWebserviceExample/WebContent/WEB-INF/
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>RESTfulWebServiceExample</display-name>
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>org.arpit.javapostsforlearning.webservices</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
In above <param-value>,put your web service package.
8) Run project:right click on project->run as ->run on server
9) Test your REST service under: "http://localhost:8080/RESTfulWebServiceExample/rest/ConversionService/FeetToInch/2". 

You will get output as :

If You see web service information page then you are done.

Creating a Restful Web Service Client:

Create ConversionServiceClient.java under org.arpit.javapostsforlearning.websevices.client

package org.arpit.javapostsforlearning.webservices.client;

import javax.ws.rs.core.MediaType;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;

public class ConversionServiceClient {
    static final String REST_URI = "http://localhost:8080/RESTfulWebServiceExample";
    static final String INCH_TO_FEET = "/ConversionService/InchToFeet/";
    static final String FEET_TO_INCH = "/ConversionService/FeetToInch/";

    public static void main(String[] args) {

        int inch=12;
        int feet=2;

        ClientConfig config = new DefaultClientConfig();
        Client client = Client.create(config);
        WebResource service = client.resource(REST_URI);

        WebResource addService = service.path("rest").path(INCH_TO_FEET+inch);
        System.out.println("INCH_TO_FEET Response: " + getResponse(addService));
        System.out.println("INCH_TO_FEET Output as XML: " + getOutputAsXML(addService));
        System.out.println("---------------------------------------------------");

        WebResource subService = service.path("rest").path(FEET_TO_INCH+feet);
        System.out.println("FEET_TO_INCH Response: " + getResponse(subService));
        System.out.println("FEET_TO_INCH Output as XML: " + getOutputAsXML(subService));
        System.out.println("---------------------------------------------------");

    }

    private static String getResponse(WebResource service) {
        return service.accept(MediaType.TEXT_XML).get(ClientResponse.class).toString();
    }

    private static String getOutputAsXML(WebResource service) {
        return service.accept(MediaType.TEXT_XML).get(String.class);
    }
}

Run above program
Output:
INCH_TO_FEET Response: GET http://localhost:8080/RESTfulWebServiceExample/rest/ConversionService/InchToFeet/12 returned a response status of 200 OK
INCH_TO_FEET Output as XML: <InchToFeetService><Inch>12</Inch><Feet>1.0</Feet></InchToFeetService>
---------------------------------------------------
FEET_TO_INCH Response: GET http://localhost:8080/RESTfulWebServiceExample/rest/ConversionService/FeetToInch/2 returned a response status of 200 OK
FEET_TO_INCH Output as XML: <FeetToInchService><Feet>2</Feet><Inch>24</Inch></FeetToInchService>
---------------------------------------------------
Source:Download