Monday, December 2, 2013

RESTful Web Services



REST stands for REpresentational State Transfer, was first introduced by Roy Fielding in his thesis"Architectural Styles and the Design of Network-based Software Architectures" in year 2000. 

REST is an architectural style. HTTP is a protocol which contains the set of REST architectural constraints.

REST fundamentals
  • Everything in REST is considered as a resource.
  • Every resource is identified by an URI.
  • Uses uniform interfaces. Resources are handled using POST, GET, PUT, DELETE operations which are similar to Create, Read, update and Delete(CRUD) operations.
  • Be stateless. Every request is an independent request. Each request from client to server must contain all the information necessary to understand the request.
  • Communications are done via representations. E.g. XML, JSON

RESTful Web Services

RESTful Web Services have embraced by large service providers across the web as an alternative to SOAP based Web Services due to its simplicity. This post will demonstrate how to create a RESTful Web Service and client using Jersey framework which extends JAX-RS API. Examples are done using Eclipse IDE and Java SE 6.

Creating RESTful Web Service
  • In Eclipse, create a new dynamic web project called "RESTfulWS"
  • Download Jersey zip bundle from here. Jersey version used in these examples is 1.17.1. Once you unzip it you'll have a directory called "jersey-archive-1.17.1". Inside it find the lib directory. Copy following jars from there and paste them inside WEB-INF -> lib folder in your project. Once you've done that, add those jars to your project build path as well.
    1. asm-3.1.jar
    2. jersey-client-1.17.1.jar
    3. jersey-core-1.17.1.jar
    4. jersey-server-1.17.1.jar
    5. jersey-servlet-1.17.1.jar
    6. jsr311-api-1.1.1.jar
  • In your project, inside Java Resources -> src create a new package called "com.eviac.blog.restws". Inside it create a new java class called "UserInfo". Also include the given web.xml file inside WEB-INF folder.
  • UserInfo.java
    1.    
    2. package com.eviac.blog.restws;  
    3.   
    4. import javax.ws.rs.GET;  
    5. import javax.ws.rs.Path;  
    6. import javax.ws.rs.PathParam;  
    7. import javax.ws.rs.Produces;  
    8. import javax.ws.rs.core.MediaType;  
    9.   
    10. /** 
    11.  *  
    12.  * @author pavithra 
    13.  *  
    14.  */  
    15.   
    16. // @Path here defines class level path. Identifies the URI path that   
    17. // a resource class will serve requests for.  
    18. @Path("UserInfoService")  
    19. public class UserInfo {  
    20.   
    21.  // @GET here defines, this method will method will process HTTP GET  
    22.  // requests.  
    23.  @GET  
    24.  // @Path here defines method level path. Identifies the URI path that a  
    25.  // resource class method will serve requests for.  
    26.  @Path("/name/{i}")  
    27.  // @Produces here defines the media type(s) that the methods  
    28.  // of a resource class can produce.  
    29.  @Produces(MediaType.TEXT_XML)  
    30.  // @PathParam injects the value of URI parameter that defined in @Path  
    31.  // expression, into the method.  
    32.  public String userName(@PathParam("i") String i) {  
    33.   
    34.   String name = i;  
    35.   return "" + "" + name + "
" + "";  
  •  }  
  •    
  •  @GET   
  •  @Path("/age/{j}")   
  •  @Produces(MediaType.TEXT_XML)  
  •  public String userAge(@PathParam("j"int j) {  
  •   
  •   int age = j;  
  •   return "" + "" + age + "
  • " + "";  
  •  }  
  • }  
  • web.xml
    1. "1.0" encoding="UTF-8"?>    
    2. "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">    
  •   RESTfulWS    
  •       
  •     Jersey REST Service    
  •     class>com.sun.jersey.spi.container.servlet.ServletContainer
  • class>    
  •         
  •       com.sun.jersey.config.property.packages    
  •       com.eviac.blog.restws    
  •     
  •     
  •     1    
  •   
  •     
  •       
  •     Jersey REST Service    
  •     /rest/*    
  •   
  •     
  •   
  • To run the project, right click on it and click on run as ->run on server.
  • Execute the following URL in your browser and you'll see the output.
    1. http://localhost:8080/RESTfulWS/rest/UserInfoService/name/Pavithra  
  • output
    Creating Client
    • Create a package called "com.eviac.blog.restclient". Inside it create a java class called "UserInfoClient".
    • UserInfoClient.java
      1. package com.eviac.blog.restclient;  
      2.   
      3. import javax.ws.rs.core.MediaType;  
      4.   
      5. import com.sun.jersey.api.client.Client;  
      6. import com.sun.jersey.api.client.ClientResponse;  
      7. import com.sun.jersey.api.client.WebResource;  
      8. import com.sun.jersey.api.client.config.ClientConfig;  
      9. import com.sun.jersey.api.client.config.DefaultClientConfig;  
      10.   
      11. /** 
      12.  *  
      13.  * @author pavithra 
      14.  *  
      15.  */  
      16. public class UserInfoClient {  
      17.   
      18.  public static final String BASE_URI = "http://localhost:8080/RESTfulWS";  
      19.  public static final String PATH_NAME = "/UserInfoService/name/";  
      20.  public static final String PATH_AGE = "/UserInfoService/age/";  
      21.   
      22.  public static void main(String[] args) {  
      23.   
      24.   String name = "Pavithra";  
      25.   int age = 25;  
      26.   
      27.   ClientConfig config = new DefaultClientConfig();  
      28.   Client client = Client.create(config);  
      29.   WebResource resource = client.resource(BASE_URI);  
      30.   
      31.   WebResource nameResource = resource.path("rest").path(PATH_NAME + name);  
      32.   System.out.println("Client Response \n"  
      33.     + getClientResponse(nameResource));  
      34.   System.out.println("Response \n" + getResponse(nameResource) + "\n\n");  
      35.   
      36.   WebResource ageResource = resource.path("rest").path(PATH_AGE + age);  
      37.   System.out.println("Client Response \n"  
      38.     + getClientResponse(ageResource));  
      39.   System.out.println("Response \n" + getResponse(ageResource));  
      40.  }  
      41.   
      42.  /** 
      43.   * Returns client response. 
      44.   * e.g :  
      45.   * GET http://localhost:8080/RESTfulWS/rest/UserInfoService/name/Pavithra  
      46.   * returned a response status of 200 OK 
      47.   * 
      48.   * @param service 
      49.   * @return 
      50.   */  
      51.  private static String getClientResponse(WebResource resource) {  
      52.   return resource.accept(MediaType.TEXT_XML).get(ClientResponse.class)  
      53.     .toString();  
      54.  }  
      55.   
      56.  /** 
      57.   * Returns the response as XML 
      58.   * e.g : Pavithra  
      59.   *  
      60.   * @param service 
      61.   * @return 
      62.   */  
      63.  private static String getResponse(WebResource resource) {  
      64.   return resource.accept(MediaType.TEXT_XML).get(String.class);  
      65.  }  
      66. }  
    • Once you run the client program, you'll get following output.
      1. Client Response   
      2. GET http://localhost:8080/RESTfulWS/rest/UserInfoService/name/Pavithra returned a response status of 200 OK  
      3. Response   
      4. Pavithra  
      5.   
      6.   
      7. Client Response   
      8. GET http://localhost:8080/RESTfulWS/rest/UserInfoService/age/25 returned a response status of 200 OK  
      9. Response   
      10. 25  




    No comments:

    Post a Comment