devxlogo

RESTful Web Services: The Keep-It-Simple Style

RESTful Web Services: The Keep-It-Simple Style

first wrote an XML-over-HTTP web service almost a decade ago. At that time, it seemed a completely natural solution to a practical business problem: provisioning web-based, product-pricing quotes. As web services became a formal technology with numerous standards, I became somewhat weary of the true usefulness of the technology. It grew so complex and institutionalized that it carried a significant learning curve and required considerable investment in the infrastructure. I often wondered what happened to my primitive XML-over-HTTP/S services, and why they were not good solutions anymore. They worked perfectly well for my application?a major e-business site serving a great number of diverse businesses across the globe.

Then two years ago I had a revelation: my good, old style of web services design was back and it now had a formal name?REST (Representational State Transfer). It was documented in the doctoral work of Roy Fielding, primary architect of HTTP 1.1 and co-founder of the Apache HTTP server project. Since then, I have effectively adopted REST as my architectural style for web services, and I have successfully applied it on multiple occasions.

This article demonstrates the most essential features of RESTful web services through a sample shipment-tracking application implemented in Java. Hopefully, it will pique your interest in this very common-sense architectural style.

Key Properties of the REST Architectural Style
REST is not a standard like SOAP or a protocol like HTTP?for that matter, it is not necessarily a services-oriented protocol either. Rather, it is a set of extraordinarily simple recommendations on how to leverage Internet protocols, formats, and infrastructure to accomplish technically sound and well-defined interoperable architectures. Although REST (like SOAP) is often associated with XML, XML is not a premise of REST and following the REST style does not automatically mean using XML. REST is primarily an architectural style, and as such it is far more concerned with the proper and complete utilization of web infrastructure and protocols than with the specifics of the exact formatting for the resource state representation.

REST’s focus is really on web resources, related operations, and the transfers of their state representation to the clients. These web resources have representational states that are created, accessed, updated, and deleted via standard methods of the HTTP protocol: PUT to create, GET to read, POST to update, and DELETE to delete. (Think of RESTful services as CRUD (Create, Read, Update, Delete) operations upon web resources.)

In addition, probably the most attractive fact about the REST architectural style is that it fully leverages the most common and readily available parameters and methods of the HTTP protocol, such as HTTP methods, headers, representations, types, and caches. For that reason, REST architectural style has been recently included in the concept of WOA (web-oriented architecture), as it truly represents the architectural style of the mechanism that operates underneath the web as we know it.

REST in the Context?Global Tracking Application
More than anything else, the web has revolutionized how global logistics and supply chain networks operate. Almost all major international carriers such as UPS, FedEx, and DHL offer highly useful and accessible online shipment-tracking services. Updates to shipment status occur nearly in real time as shipments move from location to location. This article expands on these highly valuable, relatively simple features in a small example RESTful application that enables automated web-services-based access and management of information on global shipments. This application will show what you need to build a framework for a REST-compliant application and demonstrate how easy it is to build RESTful web services by using just a few, very rudimentary Java and Java EE APIs.

Note that this application was built following the so-called Hi-REST approach. Hi-REST and Low-REST are informal labels for two sub-styles of REST. Low-REST applications support only POST and GET methods, while Hi-REST applications support all the methods of the HTTP protocol and formally incorporate XML as a data format as well.

Use Cases for the Sample Global Tracking Application
The global tracking system will enable the following:

  • Creating the shipment information?Each shipment has a unique tracking number.
  • Updating the status of the shipment?Shipment is identified by the tracking number.
  • Querying the status of the shipment?Shipment is identified by the tracking number.
  • Deleting the shipment?Shipment is identified by the tracking number.

Named Resources
According to the principles of the REST style, each web-accessible domain object should be represented as a unique URI. In this case, each shipment will be a standalone URI formatted as follows:

http://localhost:8080/GlobalTracking/shipment/1229292919911

Through this URI, one will be able to create, update, query, and delete shipment states.

So, from an implementation perspective, you need to build a platform that can support these two key RESTful design items:

  1. Embedding of the domain object identifiers (in this case, tracking numbers) in the URI as resources
  2. Support for all four HTTP methods: PUT, GET, POST, DELETE

To complete the first requirement of dispatching web requests for URIs constructed in this fashion, the example utilizes the “wildcard” servlet mapping available as an option in the web.xml file:

      Shipment    /shipment/*  

You also will need to do some parsing in the mapped servlet itself to extract the last element from the passed URI:

  String URI = req.getPathInfo();		  String shipmentID = URI.substring( URI.lastIndexOf("/") + 1 );

You will use this tracking number to access the shipment and apply the method requested upon it.

Processing of the HTTP Methods
If you’re familiar with the Servlets API, you will recall that HttpServlet (the superclass of all servlets) provides a no-functionality implementation for all four methods required by REST (see Class HttpServlet documentation page).

In order to implement the handling logic for HTTP methods, you just need to override each one of these methods in the servlet mapped to handle shipment URIs.

There is, however, a common browser-side issue associated with the implementation of the HTTP methods and their support in form submissions. Most browsers support only POST and GET, and they convert all other methods to GET. To work around this issue, I needed to add a custom hidden form parameter to a test html page (workbench.html):

I then needed to insert under the HttpServlet an additional superclass that overrides the service method from HttpServlet to parse this parameter and, based on this value, I dispatched the processing to the appropriate do* method that matches HTTP method:

@Overrideprotected void service(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException { String httpMethod = request.getParameter("method"); if ( httpMethod != null && !"".equals(httpMethod.trim() )) { if (httpMethod.equalsIgnoreCase("delete")) { doDelete(request, response); return; } else if (httpMethod.equalsIgnoreCase("put")) { doPut(request, response); return; } } super.service(request, response); }

Inputs and Outputs for RESTful Services
REST accepts plain text-based, discrete HTTP query parameters as inputs for the state information into a resource. For example, if you want to update your shipment (tracking number 1234567890) with the date and the location of the delivery, you would POST the following query parameters to the 1234567890 URI:

http://localhost:8080/GlobalTracking/shipment/1234567890?location=CA&date=12122008&status=delivered

Unlike other web services standards, nothing in REST mandates using XML or any other input type. It is perfectly fine and appropriate to use an HTTP query string to query or update the state of the web-accessible resource. However, query strings should not be used to identify the resources themselves, only to query or update their states.

The only acceptable REST method for identifying and accessing resources is via URI:

http://localhost:8080/GlobalTracking/shipment/1229292919911

You should never identify resources via query parameters like this:

http://localhost:8080/GlobalTracking?shipment=1229292919911

For output, REST promotes using standard HTTP status codes. For example, when an update to a resource is issued via POST, the Shipment servlet will respond with either HTTP OK or HTTP ERROR code:

resp.setStatus( HttpServletResponse.SC_OK );

In the case of the GET method issued against the resource, the Shipment servlet will transfer the state to the client using the following XML:

	          100200345100 	   in transit	   LA	   12-12-2007      

With REST, all standard information formats such as (X)HTML, XML, JPEG, GIF, etc. are valid resource representations. In practice, it is common to use query parameters as the input for resource methods, and XML as the output from the methods that produce rich state representation (e.g., GET).

Web Services for Developers
REST architectural style deserves the attention of any developer or architect who is interested in solving common interoperability problems in the simplest and most pragmatic fashion. Specifically, it is hard to ignore REST’s very specific and very attractive propositions when it comes to establishing a web-based, interoperable infrastructure:

  • It promotes the reuse of well-established protocols, APIs, and infrastructure.
  • It promotes a pragmatic and simplistic approach to application design.

The architectural values and productivity that the REST style promotes have led many to call RESTful web services the web services for developers. This article was a brief and practical introduction to getting started with RESTful web services.

Numerous debates are taking place on the web about which is the better approach for web services, REST or SOAP. This article left those debates alone, but I strongly advise you to read the additional material on REST provided in the Related Resources section in the left column. These great readings cover not only REST but web architectures and pragmatic development as well.

devx-admin

Share the Post: