----

RESTFul Services

What Are RESTful Web Services?

RESTful web services are loosely coupled, lightweight web services that are particularly well suited for creating APIs for clients spread out across the internet. REST: Representational State Transfer is an architectural style of client-server application centered around the transfer of representations of resources through requests and responses. In the REST architectural style, data and functionality are considered resources and are accessed using Uniform Resource Identifiers (URIs), typically links on the Web. The resources are represented by documents, and are acted upon by using a set of simple, well-defined operations.

For example, a REST resource might be the current weather conditions for a city. The representation of that resource might be an XML document, or an image file, or an HTML page. A client might retrieve a particular representation, modify the resource by updating its data, or delete the resource entirely.

The REST architectural style is designed to use a stateless communication protocol, typically HTTP. In the REST architecture style, clients and servers exchange representations of resources by using a standardized interface and protocol.   RESTful applications are simple, lightweight, and fast.

Step by step guide for creating RESTful web service using spring 3 mvc

In this step by step guide, let us take an example of flight reservation system where the front end UI client allows customers to book a reservation, update a reservation, delete a reservation and view the reservation using restful web service APIs. Here flight reservation details is considered as a resource represented using JSON which is created, updated or deleted using rest APIs by the front end UI client.

1.       Initial Setup:
     ·  Install JDK (the version that I have used here is 1.6.0_45).
       ·  Download and extract the following into C drive (or any other location which you feel is more appropriate.)
                                     Apache Maven (version used for the purpose of this guide is 3.1.1)
                                   Apache tomcat (version used for the purpose of this guide is 7.0.42)  
              · Eclipse IDE (or any other IDE which you are comfortable with)

2.       Create a project structure using the following maven command (if you are running the maven command for the first time then it will take a while to create the project structure because all the required dependencies has to be downloaded first)

mvn archetype:generate -DarchetypeGroupId=org.springframework.ws -DarchetypeArtifactId=spring-ws-archetype -DarchetypeVersion=2.1.2.RELEASE -DartifactId=flight-rest-ws -DgroupId=com.flight -DinteractiveMode=false


Same directory structure will be created as shown here. Also web.xml and spring-ws-servlet.xml are created by default in WEB-INF directory.  
        3.   Create a new directory by name java under flight-rest-ws/src/main directory.

           4.    Create eclipse project files by running the following maven command. This command has to be executed from inside flight-rest-ws directory where pom.xml is located. This command is useful if you want to use eclipse IDE for your development.

mvn eclipse:eclipse

This command will create .settings folder, target folder, .classpath file and .project file

               5.       Create a Spring MVC controller to handle rest web service requests for creating reservation, getting reservation, updating reservation and deleting reservation. These different rest requests are mapped to Http POST, GET, PUT and DELETE requests. POST is used to create a new reservation, GET is used to retrieve an existing reservation, PUT is used to update a reservation and DELETE is used to delete to cancel a reservation.

package com.flight;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/reservation")
public class FlightController {

       @RequestMapping(value = "/{userId}/create", method = RequestMethod.POST)
       public ResponseEntity<FlightReservationResponse> create(
                     @PathVariable("userId") String userId,
                     @RequestBody FlightReservationDetails reservation) {

     // For the given userId, create a flight reservation using the details
     // from FlightReservationRequest object.
     // You can use a database to store reservation details and to generate
     // unique reservation number.

     // Create FlightReservationResponse object with a unique reservation number.
              FlightReservationResponse response = new FlightReservationResponse(
                           "RID123456", "Create Successful");

     // The FlightReservationResponse object is converted into JSON and then
     // sent to the client.
              return new ResponseEntity<FlightReservationResponse>(response,
                           HttpStatus.OK);
       }

       @RequestMapping(value = "/{userId}/get/{reservationNumber}", method = RequestMethod.GET)
       public ResponseEntity<FlightReservationDetails> get(
                     @PathVariable("userId") String userId,
                     @PathVariable("reservationNumber") String reservationNumber) {

       // Get the flight reservation details for the given user id and
       // reservation number.
       // You can use a database to retrieve the details using the given
       // reservation number and user id.
              FlightReservationDetails details = new FlightReservationDetails();
              details.setFlightNumber("FLIGHT 123");
              details.setSource("CITY A");
              details.setDestination("CITY B");
              details.setDate("MON JAN 1 2014");
              details.setTime("09:00 AM");

       // The FlightReservationDetails object is converted into JSON and then
       // sent to the client.
              return new ResponseEntity<FlightReservationDetails>(details,
                           HttpStatus.OK);
       }

       @RequestMapping(value = "/{userId}/update/{reservationNumber}", method = RequestMethod.PUT)
       public ResponseEntity<FlightReservationResponse> update(
                     @PathVariable("userId") String userId,
                     @PathVariable("reservationNumber") String reservationNumber,
                     @RequestBody FlightReservationDetails details) {

        // Retrieve the existing reservation details using the given user id and
        // reservation number and update it with the input reservation details.
        // If you are using a data base then update the database entry.

        // Create FlightReservationResponse object with the input reservation
        // number
              FlightReservationResponse response = new FlightReservationResponse(
                           "RID123456", "Update Successful");

        // The FlightReservationResponse object is converted into JSON and then
        // sent to the client.
              return new ResponseEntity<FlightReservationResponse>(response,
                           HttpStatus.OK);
       }

       @RequestMapping(value = "/{userId}/delete/{reservationNumber}", method = RequestMethod.DELETE)
       public ResponseEntity<FlightReservationResponse> delete(
                     @PathVariable("userId") String userId,
                     @PathVariable("reservationNumber") String reservationNumber) {
        // Delete the reservation details for the given user id and reservation
        // number.
        // If you are using a database then remove the reservation entry from
        // the database

        // Create FlightReservationResponse object with the input reservation
        // number
              FlightReservationResponse response = new FlightReservationResponse(
                           "RID123456", "Delete Successful");

        // The FlightReservationResponse object is converted into JSON and then
        // sent to the client.
              return new ResponseEntity<FlightReservationResponse>(response,
                           HttpStatus.OK);
       }
}



No comments :

Post a Comment