Friday, October 21, 2011

REST introduction by building a simple web application

Introduction:

REST (Representational state transferhas become very popular and in fact it was always there but we just didn't see it until Roy Fielding presented his doctoral dissertation. It gives us the power of distributed computing without the hassle of redefining the protocol to access those distributed objects. The current peers of REST can be EJB or so called Service oriented architectures which again requires their own custom protocols such as RMI or SOAP. Unlike REST works with HTTP protocol and hence leverage whats already there. We can define distributed objects using REST and access those object using simple HTTP protocols such as GET, PUT, DELETE etc. Furthermore, the REST based server side object can be deployed in a simple web container which makes it easy enough to use with Spring and a no EJB approach.

Another important fact to note is the popularity of JQuery for ajax programming and usage of JSON (Javasript Object Notion), which made REST almost a defacto/slamdunk choice in Java server side programming.

With the advent of smart phones and mobile devices (iPhone/iPad etc) we need a consistent way of accessing information from server side without bothering on the protocol to use. REST gives us exactly that because the protocol is HTTP which is widely supported and can be accessed on any platform with a support for browser.


Many companies are already taking advantage of this and making their products available through RESTful API's so that the mobile App developers can leverage those APIs in their apps seamlessly. e.g. BestBuy has a developer section that you can access https://bbyopen.com/developer it gives a list of all the APIs that are available. You have to register for an api key and then can access all the info. I registered for it and got the key as {m3rwueytrfbaxsbertw7qzvm}

Following URL will give you access to products in BestBuy which you can access in a normal web browser with xml plugin or in REST client as defined below.
http://api.remix.bestbuy.com/v1/products?apiKey=m3rwueytrfbaxsbertw7qzvm


The beauty is that by default it gives you an XML formatted result which you can convert to Java objects easily and is a no-brainier but the real flexibility comes from the fact that while making a GET request you can specify the content type as application/json and it would return you results in JSON which can be consumed directly in your javascript.


Installing a simple REST client:

To play around with REST as a developer I would recommend to install a REST client tool available in Chrome called "Simple REST Client".
 
    1. Goto Web store https://chrome.google.com/webstore?hl=en-US

    2. Search for "Simple REST Client" and install it.

You can change the header information here to play around by passing objects or receiving a different content type etc.

Note: You can use third party providers and write the client in Java or any other language as well.

Lets build a sample Zip Locator REST App:

The first idea came to my mind was a zip locator app as it can be very useful for address validation. To build a REST app we need a provider that can run the distributed object in the Servlet container. For that we are using Apache CXF. Note: A complete source code is available at the end of this post.


Lets build a basic one for this tutorial without any database. The key components are described below. First is the ZipcodeDetails which is a data object to hold zipcode information.

@XmlRootElement
public class ZipcodeDetails implements Serializable
{
  private String zipcodeId;
  private String cityName;
  private String state;
}
The service name will be named FindZipcodeService. Please note that we are defining that the results can be consumed as XML or JSON using @Produces annotation. We can define more Media types if needed.
Also the @Path annotation is what leads us to these methods. Again if you are familiar with Spring MVC then it should be straight forward.
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public class FindZipcodeService 
{
 @GET
 @Path("findbyzipcode/{zipcode}")
 public ZipcodeDetails findzipcodeDetails( @PathParam("zipcode") String zipcode)
 {}
 
 @GET
 @Path("findbycity/{city}")
 public List findByCity(@PathParam("city") String city)
 {}
 
 @GET
 @Path("findbystate/{state}")
 public List findByState(@PathParam("state") String state)
 {}
This is how we can define the REST service using Apache CXF.

    
    
        
            
        
        
            
            
        
    
The main dependencies are Apache CXF and JaxRS

  org.apache.cxf
  cxf-rt-transports-http
  ${cxf.version}
 
 
  org.apache.cxf
  cxf-rt-frontend-jaxrs
  ${cxf.version}
  
 
      javax.ws.rs
      jsr311-api
      1.1
 

Your Web XML needs to define the Dispatcher servlet to handle REST related request as shown.

        contextConfigLocationclasspath*:com/spinachsoftware/restful/config/applicationContext.xml
    
        
            org.springframework.web.context.ContextLoaderListener
        
    
    
        CXFServlet
        org.apache.cxf.transport.servlet.CXFServlet
        1
    
    
        CXFServlet
        /rest/*
    

When you deploy this on Jetty or Tomcat or any Server give the context path to "/". This way the URL will be formed as http://localhost:8080/rest/findbyzipcode/55401


  1. A complete source code can be downloaded as a zip ZipRESTWebApp.zip
  2. Another step you can do is to deploy on Cloud foundry see the instructions here.
  3. I have already deployed a full blown ziplocator service to cloud foundry with all US based zip codes. http://ziplocator.cloudfoundry.com/ e.g. http://ziplocator.cloudfoundry.com/rest/findbyzipcode/55426
In my next post we can see how to connect to database using cloud foundry and also touch base on basic authentication/security for REST.

No comments:

Post a Comment