Wednesday, September 19, 2012

REST Web Service


What is Web Service?

The W3C defines a "Web service" as "a software system designed to support interoperable machine-to-machine interaction over a network" [W3C Web Service]

But Simply we can say that Web service is a software component that provides a business function as service over the web that can be accessed through a URL.


There are two most widely used approach for developing web services, one SOAP and another is REST. We will be discussing the REST Web service in this post.

REST (Representational State Transfer) is neither a technology nor a standard; it's an architectural style—a set of guidelines for exposing resources over the Web. The REST architecture style is related to a resource, which is a representation identified by a Uniform Resource Indicator (URI).

We will be using Apache CXF API to develop REST web service in this post. Apache CXF is open source web service framework that provides easy to use standard based programming model for developing web services. CXF supports variety web service standards like SOAP, WSDL, REST(JAX-RS) and so on. CXF provides integration with Spring framework which simplifies configuration and deployment of RESTful application


To develop the RESTful service, we typically perform the following steps:
-- Create Java data object for Request and Response
-- Provide binding for Request and Response objects
-- Create interface and annotate the interface with JAX-RS annotations to create RESTful implementation.
-- Provide implementation for your interface
-- Write configuration for deployment (If required)
-- Create client to invoke various methods of RESTful services
-- Deploy the web service in a container

We are going to create a simple Hello World RESTful web service in this post. So we do not need Java Data Object here. We will start writing interface and implementation class for RESTful service.
  


HelloWorldRestService.java
package com.sarf.service;

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("/hello-service/")
@Produces(MediaType.TEXT_PLAIN)
public interface HelloWorldRestService{
 
     @GET
     @Path("/hello")
     @Produces(MediaType.TEXT_PLAIN)
     public String sayHello();
     
     @GET
     @Path("/greet/{name}")
     @Produces(MediaType.TEXT_PLAIN)
     public String greetUser(@PathParam("name") String strName);
  

 } 

@Path annotation defines the URI path that a resource class or method will serve a request for. For example, HelloWorldRestService has path "hello-service" ,which mean URI request such as http://IP:8080/MyRESTExample/hello-service/ will be served by HelloWorldRestService class.

@Produce annotation defines the content type that the method or resource class can produce and send back to client.

The @PathParam annotation is used to map a given URI Path template variable to the method parameter

Each method in HelloWorldRestService  is mapped to the HTTP methods that they  support. In JAX-RS terminology, the HTTP methods annotations, that is, @GET and  @POST are called Request Method Designators.



HelloWorldRestServiceImpl.java
package com.sarf.service;

import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;


public class HelloWorldRestServiceImpl implements HelloWorldRestService{

   public HelloWorldRestServiceImpl() {}

    @Override
    public String sayHello() {
        return "Hello World";
    }
    
    @Override
    public String greetUser(String strName) {
        return "Hello "+strName;
    }
}




Since CXF provides integration with the Spring framework, we can leverage the dependency injection capability of Spring in our applications. So we will be creating two xml files. One for Spring CXF integration and another web.xml.



appContext.xml

These <import> statements, cxf.xml,cxf-extension-jaxrs-binding, and cxf-servlet.xml are filesare Spring-based configuration files that define core components of CXF. These files are used to kick start CXF runtime and load the necessary CXF infrastructure objects such as WSDL manager, conduit manager, destination factory manager and so on.

The <jaxrs:server> element in the appContext.xml file specifies the  helloRestServiceImpl as a RESTful resource. This <jaxrs:server> element publishes the HelloWorldRestServiceImpl bean as a RESTful resource over address. A developer need not have to write any Java class to publish the RESTful service. 

Next we need to wire the CXF Controller Servlet (CXFServlet) in web.xml which directs the request to one of the matching RESTful resources defined in the <jaxrs:server> element.

web.xml
web.xml, as we know, is the web application configuration file that defines a servlet and its properties. The file defines CXFServlet, which acts as a front runner component that initiates the CXF environment.

web.xml also defines the listener class ContextLoaderListener, which is responsible for loading the server-side configuration file appContext.xml. So on web server startup, the HelloWorldRestServiceImpl RESTful service will be registered and available over the address.



Client

We will write client to use the web service. We will be creating a simple jsp file which will access the web service.

index.jsp


We will now use pom.xml to build our application and package it as war file. Here is the link for pom.xml. Click here to download

After successful deployment, you can access the application using following url :
http://localhost:8080/MyRESTExample/index.jsp

After building and packaging , the war file structure will look like the image given below