About Me
Facebook
Facebook
Linked In
Linked In
Twitter
Twitter
YouTube
YouTube
Google +
Google +
Showing posts with label RESTful. Show all posts
Showing posts with label RESTful. Show all posts

September 23, 2015

Introduction to RESTful Web Services



Introduction
REST stands for Representational State Transfer. REST is web standards based architecture and uses HTTP Protocol for data communication. It revolves around resource 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 2000.
Representational State Transfer (REST) is a software architecture style that centers on the transmission of data over HTTP, using only the four basic HTTP verbs. It also eschews the use of any additional wrappers such as a SOAP envelope and the use of any state data.

Overview
Representational State Transfer (REST) is an architectural style first described in a doctoral dissertation by a researcher named Roy Fielding. In RESTful systems, servers expose resources using a URI, and clients access these resources using the four HTTP verbs. As clients receive representations of a resource they are placed in a state. When they access a new resource, typically by following a link, they change, or transition, their state. In order to work, REST assumes that resources are capable of being represented using a pervasive standard grammar.
The World Wide Web is the most ubiquitous example of a system designed on REST principles. Web browsers act as clients accessing resources hosted on Web servers. The resources are represented using HTML or XML grammars that all Web browsers can consume. The browsers can also easily follow the links to new resources.
The advantages of RESTful systems is that they are highly scalable and highly flexible. Because the resources are accessed and manipulated using the four HTTP verbs, the resources are exposed using a URIs, and the resources are represented using standard grammars, clients are not as affected by changes to the servers. Also, RESTful systems can take full advantage of the scalability features of HTTP such as caching and proxies.
HTTP Methods
Following well known HTTP methods are commonly used in 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.
Basic Rest Principles
v  RESTful architectures adhere to the following basic principles:
v  Application state and functionality are divided into resources.
v  Resources are addressable using standard URIs that can be used as hypermedia links.
v  All resources use only the four HTTP verbs.
ü  DELETE
ü  GET
ü  POST
ü  PUT
v  All resources provide information using the MIME types supported by HTTP.
v  The protocol is stateless.
v  Responses are cacheable.
v  The protocol is layered.
Resources
Resources are central to REST. A resource is a source of information that can be addressed using a URI. In the early days of the Web, resources were largely static documents. In the modern Web, a resource can be any source of information. For example a Web service can be a resource if it can be accessed using a URI.
RESTful endpoints exchange representations of the resources they address. A representation is a document containing the data provided by the resource. For example, the method of a Web service that provides access to a customer record would be a resource, the copy of the customer record exchanged between the service and the consumer is a representation of the resource.
Rest Best Practices
When designing RESTful Web services it is helpful to keep in mind the following:
ü  Provide a distinct URI for each resource you wish to expose.
For example, if you are building a system that deals with driving records, each record should have a unique URI. If the system also provides information on parking violations and speeding fines, each type of resource should also have a unique base. For example, speeding fines could be accessed through /speedingfines/driverID and parking violations could be accessed through /parkingfines/driverID.
ü  Use nouns in your URIs.
Using nouns highlights the fact that resources are things and not actions. URIs such as /ordering imply an action, whereas /orders implies a thing.
ü  Methods that map to GET should not change any data.
ü  Use links in your responses.
Putting links to other resources in your responses makes it easier for clients to follow a chain of data. For example, if your service returns a collection of resources, it would be easier for a client to access each of the individual resources using the provided links. If links are not included, a client needs to have additional logic to follow the chain to a specific node.
ü  Make your service stateless.
Requiring the client or the service to maintain state information forces a tight coupling between the two. Tight couplings make upgrading and migrating more difficult. Maintaining state can also make recovery from communication errors more difficult.
Designing a Restful Web Service
Regardless of the framework you use to implement a RESTful Web service, there are a number of steps that should be followed:
v  Define the resources the service will expose.
In general, a service will expose one or more resources that are organized as a tree. For example, a driving record service could be organized into three resources:
*      /License/driverID
*      /License/driverID/speedingfines
*      /License/driverID/parkingfines
v  Define what actions you want to be able to perform on each resource.
For example, you may want to be able to update a diver's address or remove a parking ticket from a driver's record.
v  Map the actions to the appropriate HTTP verbs.
Once you have defined the service, you can implement it using Apache CXF.
Sr. No.
HTTP Method
URI
Operation
Operation Type
1
GET
/License/driverID
Get list of License
Read Only
2
GET
/License/driverID/1
Get License with Id 1
Read Only
3
PUT
/License/driverID/2
Insert License with Id 2
Idempotent
4
POST
/License/driverID/2
Update License with Id 2
N/A
5
DELETE
/License/driverID/1
Delete License with Id 1
Idempotent
6
OPTIONS
/License/driverID
List the supported operations in web service
Read Only

Conclusion
In REST architecture, a REST Server simply provides access to resources and 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. Now a days JSON is the most popular format being used in web services. 

continue reading

July 22, 2015

Developing AngularJS web applications with RESTful CRUD



This blog will discuss about the details involved in developing AngularJS web applications with RESTful CRUD. To understand the details, it is required to have a basic knowledge of AngularJS and REST concepts.
The application involves writing the client side using AngularJS (a JavaScript framework) which will communicate with the REST module that implements a service to manage Employee Information. To make the illustration simple, the Employee Information data will be stored in memory. Java Collections Framework will be used to manage the data structure. The client side AngularJS will provide the user interface in the browser to view, add, update and delete employee information.
Required Software infrastructure
Following is the list of software that needs to be installed to implement the application and run it.
1.      Java Development Kit – The latest version of JDK available for download from Oracle should be downloaded and installed.
2.      Google Chrome – The latest version of Google Chrome should be installed.
3.      Eclipse IDE for Java EE Developers – The Luna edition of Eclipse IDE for Java EE Developers should be downloaded from Eclipse website and installed.
4.      Apache Tomcat 8 – The latest version of Apache Tomcat 8 should be downloaded from Apache website and installed.
5.      Git client – Git client software should be downloaded from Git website and installed.
6.      Jersey – Jersey provides the framework for RESTful Web Services which needs to be downloaded from Jersey website and installed.
7.      Node.js – The latest version of Node.js should be downloaded from Node.js website and installed. Note that, in the current illustration we will not be using Node.js server for the server side software but will be using Apache Tomcat 8 server. Node.js will be primarily used for the npm package manager to download certain modules required for the implementation of the AngularJS application.
8.      Angular Seed – The Angular Seed Master zip should be downloaded from Git and extracted. Alternately, the angular-seed repository can be cloned from git.
9.      Bootstrap – The Bootstrap framework from Twitter can be downloaded and extracted to provide a better user interface.
10.  jQuery – The Bootstrap framework depends on jQuery and hence if Bootstrap is used, jQuery should be downloaded and extracted.
11.  Jackson JARs – Jackson JARS for handling JSON data should be downloaded from Jackson website.
Additional Configuration
After installing the above mentioned software, additional configuration needs to be done to configure before we start the implementation.
1.            If behind proxy, the proxy configuration for npm needs to be set using “npm config set proxy”.
2.            “npm install” needs to be executed in the Angular Seed Master directory so that the necessary npm modules are automatically downloaded and setup.
3.            The basic components of AngularJS would have got installed by default. Apart from that, we need an additional module “angular-resource” which should be downloaded and put under “bower_components”.
Implementation of AngularJS client side component
The Angular Seed Master provides an application skeleton for a typical AngularJS web application. We will use it as the starting point to implement the client side component of the Employee Information application.
index.html
This is the starting point of the application and specifies the CSS files and the JavaScript files used and also the views that are to be displayed. In the section, where CSS files are mentioned, the bootstrap CSS need to be included if the user interface provided by BootStrap is used to provide a better user interface. In the section, where JavaScript files are mentioned, the BootStrap and jQuery JavaScript libraries need to be included. The angular-resource JavaScript file also needs to be mentioned in the JavaScript files section.
In the section, where the views are mentioned, the views specific to Employee Information need to be provided. We will modify it to mention 3 views, “Add Employee”, “Update Employee” and “View Employee List”.
The code snippet will look like
  <ul class="nav nav-pills">
    <li><a href="#/addEmployee">Add Employee</a></li>
    <li><a href="#/updateEmployee/1">Update Employee</a></li>
    <li><a href="#/viewEmployeeList">View Employee List</a></li>
  </ul>
 app.js
app.js mentions the route for each of the view. We need to provide the routes for “Add Employee”, “Update Employee” and “View Employee List” here.  The “templateUrl” need to be updated to specify the HTML files (addEmployee.html, updateEmployee.html and viewEmployeeList.html) and “controller” needs to be updated with the respective controllers. The actual HTML files will be present under the “partials” directory and the code for the controllers will be in “controllers.js”.
The code snippet will look like
$routeProvider.when('/addEmployee', {templateUrl: 'partials/addEmployee.html', controller: 'AddEmployeeCtrl'});
$routeProvider.when('/updateEmployee/:id', {templateUrl: 'partials/updateEmployee.html', controller:'UpdateEmployeeCtrl'});
$routeProvider.when('/viewEmployeeList', {templateUrl: 'partials/viewEmployeeList.html', controller:'ViewEmployeeListCtrl'});
  $routeProvider.otherwise({redirectTo: '/viewEmployeeList'});
 HTML files
The HTML files “addEmployee.html” and “updateEmployee.html” need to specify the form which will be displayed to get the employee information to be added to the Employee Information data maintained at the server. The HTML file “viewEmployeeList.html” should be updated with the HTML code needed for displaying the employee list in a HTML table. Against each employee data, there will be a Edit button and Delete button provided to allow for editing and deletion of employee records.
controllers.js
controllers.js contains the code for all the controllers. The code required to add employee, update employee and view employee list need to be written in the respective controllers, “AddEmployeeCtrl”, “UpdateEmployeeCtrl” and “ViewEmployeeListCtrl”. To perform the actual action on the REST server, these controllers will use the services implemented in “services.js”.
services.js
services.js contains the code for the service which connects to the REST server and performs the necessary operations. To implement the service, the ngResource AngularJS plugin is used. ngResource contains a service $resource, a factory which creates a resource object that allows to interact with RESTful server-side data sources. The Employee service will use the $resource service to issue REST requests for add, update, delete and view.
The code snippet will look like
var services = angular.module('myApp.services', ['ngResource']);
services.factory('EmployeesFactory', ['$resource', function($resource) {
return $resource('/demo.employee/rest/employees', {}, {
query: {method:'GET', isArray:true},
            create: {method: 'POST' }
      })
}]);

services.factory('EmployeeFactory', ['$resource', function($resource) {
return $resource('/demo.employee/rest/employees/:id', {}, {
            show: {method:'GET'},
            update: {method: 'PUT', params: {id: '@id'} },
            delete: {method: 'DELETE', params: {id: '@id'} }
      })
}]);
Implementation of RESTful server side component
The server side component implemented using REST will provide the services to manage the Employee Information data. To implement the REST services, an Eclipse project using “Dynamic Web Project” option can be created which sets up the necessary infrastructure required for development. To implement the full application in Eclipse and package it, we can copy the client side AngularJS component – the files we had updated/created in Angular Seed Master, to the folders under the Eclipse project. The complete set of files and folders present under the “app” directory in Angular Seed Master should be copied under “WebContent” folder in the Eclipse project. All the necessary JARs (mentioned in the Software infrastructure required section) should be copied under WEB-INF/lib folder in the Eclipse project – These JARs include all the JARs which are under the various folders of Jersey installation and the Jackson JARs.
Employee class
The Employee class needs to be defined with the necessary fields required to manage the Employee information – for example, firstName, lastName, emailId, location, mobileNumber. Above the Employee class, @XmlRootElement tag need to be specified which defines the JAXB binding.
The code snippet will look like
@XmlRootElement
public class Employee {
      ...
}
REST implementation class
The class, say EmployeeRestService, which implements REST, should be defined to handle the REST requests from the client side AngularJS. Above the EmployeeRestService class, @Path(“/employees”) should be specified which maps all the REST requests having the “/employees” URI path template.
The code snippet will look like
@Path("/employees")
public class EmployeeRestService {
...
}
To handle the specific requests of add, show, update, delete, view from the client side AngularJS, the REST methods with appropriate annotations (@POST, @GET, @PUT, @DELETE, @GET) should be implemented. The output generated by the REST methods will be JSON data and should be specified by the annotation @Produces(MediaType.APPLICATION_JSON). The data passed from the client side AngularJS will also be JSON data and should be specified by the annotation @Consumes(MediaType.APPLICATION_JSON). Note:show method is to retrieve single employee information for the update view in the client side AngularJS component to display.
The code snippets will look like
      @POST
      @Consumes(MediaType.APPLICATION_JSON)
      @Produces(MediaType.APPLICATION_JSON)
      // add – REST implementation
      public Employee add(Employee employee) {
            ...
      }

      @GET
      @Path("{id}")
      @Produces(MediaType.APPLICATION_JSON)
      // show – REST implementation
      public Employee getEmployeeById(@PathParam("id") int id) {
            ...
      }

      @PUT
      @Path("{id}")
      @Consumes(MediaType.APPLICATION_JSON)
      @Produces(MediaType.APPLICATION_JSON)
      // update – REST implementation
      public Employee update(Employee employee) {
            ...
      }

      @DELETE
      @Path("{id}")
      @Produces(MediaType.APPLICATION_JSON)
      // delete – REST implementation
      public void delete(@PathParam("id") int id) {
            ...
      }

      @GET
      @Produces(MediaType.APPLICATION_JSON)
      // view – REST implementation
      public List<Employee> getEmployees() {
            ...
      }
The above REST methods will implement the add, show, update, delete and view methods to update / retrieve the Employee Information data structure which will be maintained in a HashMap. The data which flows to and from server to client is JSON data. JAXB binding and Jackson libraries handle the data conversion from JSON to Java objects so that the REST implementation need not bother about handling JSON data in the code and deals with only Java objects.
web.xml
The web.xml file present in WEB-INF folder should be configured so that the REST requests can be handled by the class implementing the REST Service and to handle JSON data.
Summary
The blog had explained how simple it is to develop an AngularJS web application interacting with a RESTful service using the Angular Seed Master as the base. The RESTful service with CRUD operations can be easily implemented by using the framework provided by Jersey for RESTful Web Services and the JAXB and Jackson libraries to seamlessly handle JSON data. The illustration had used Java Collections Framework to manage the data of Employee Information but the same can be easily replaced to manage the data in a database.

continue reading

Designed By AMEER BASHA G