Integrating AJAX Clients and RESTful Web Services

t is no coincidence that AJAX and RESTful web services gained the attention of developers in their respective stages of infancy. Both technologies emerged during times that were dominated by cumbersome enterprise technologies. They gained popularity because of the freshness, innovation, and simplicity that they brought into the lives of hands-on technologists. AJAX brought the immediate gratification associated with a dynamic web experience, while RESTful web services brought the simplicity and pragmatism that developers expected from the web services concept but faced complex web services specifications.

Many also recognized that these two technologies offered the opportunity to create new models for service-oriented web applications. Being very compatible, AJAX and RESTful web services could be integrated and composed in new ways. These two technologies fit together particularly well for a number of reasons:

  1. Both AJAX and RESTful web services leverage widely available web technologies and standards such as HTML, JavaScript, browser objects, and HTTP. There is absolutely no need to buy, install, or configure any other major component to enable effective interaction between AJAX front ends and RESTful web services.
  2. Integration between these two technologies is simple. An AJAX front end implements a RESTful web service simply by invoking the RESTful URL with an HTTP method. If you need to pass any messages as parameters to the RESTful web service, you just issue them into the service as standard parameters of the HTTP query string like this:
    function getLastShipmentLocation( String shipmentID ){  var URLString = "https://localhost:8080/GlobalTracking/shipments/" + shipmentID;  //Issue AJAX request to Shipment RESTful service with last location as parameter   new Ajax.Request(URLString, {                   method: 'get',      parameters: {location: 'last', limit: 12}  });}
  3. AJAX naturally supports an essential feature of RESTful web services: resources as URLs. With RESTful web services each entity or resource is presented as an individual URL. For example, in an online shipment-tracking service (see article for reference) a shipment that you are interested in tracking would be presented as follows:
    https://localhost:8080/GlobalTracking/shipments/101

    AJAX-enabled applications naturally construct URLs on the fly based on user input. So the method to invoke a RESTful URL to get the status on a shipment with the tracking ID 101 would look like this:

    function getShipmentLocation( String shipmentID ){  //append shipment ID to get the status on the shipment from the service   var URLString = "https://localhost:8080/GlobalTracking/shipments/" + shipmentID;  //Issue AJAX request to Shipment RESTful service to get shipment status   new Ajax.Request(URLString, {                   method: 'get'}  });} 

    This example uses the Prototype framework to invoke URLs asynchronously because Prototype encapsulates and therefore simplifies logic that deals with cross-browser compatibility, asynchronous invocations of XMLHttpRequest, response codes checking, and HTTP method dispatching. However, you can opt to use XMLHttpRequest directly to issue RESTful web service calls.

  4. RESTful web services offer flexibility and freedom in your selection of message formats. Unlike SOAP web services they are not XML-only. In fact, the REST specification does not mandate using XML for RESTful web services.

My two previous articles about REST and enterprise service bus (ESB) integration reviewed the basics of RESTful web services and explored the solutions available for connecting RESTful web services to an ESB. This article discusses the third major area of interest for contemporary software developers: integrating AJAX-enabled application web front ends with backend services as RESTful web services.

AJAX and RESTful Integration Data Formats: Text, XML, or JSON
The simplest and most common format for data exchange probably still is plain, delimited text. JavaScript, just like Java or C#, has strong support for text parsing. So when results from RESTful web services are served as delimited text, you can easily parse, interpret, and dynamically inject them into online content through JavaScript. The XMLHttpRequest object supports text as a results output from a call to a URL, so you can extract plain text results without any special manipulation:

// parse the server response held in responseText // and split the comma separated values into array valuesvar values = httpRequester.responseText.split(",");                                                                      //pick third value and insert into (X)HTML element messageBody using DOM document.getElementById('messageBody').value = values[3];

For those uncomfortable with using plain text as a data interchange format, note that most of the well-known web service APIs such as Google’s as well as AJAX frameworks readily consume or produce service invocation results as plain text. So although plain text may not be your first choice, it offers the benefit of AJAX natively consuming web services that produce plain text results.

XML
XML, often called the lingua franca of information exchange, is an unwritten standard for a majority of information-integration services. RESTful web services, especially the Hi-REST version (see my first article on RESTful web services for an explanation of Hi-REST), use XML as the standard format for service input and output.

In order to simplify matters, RESTful web services (unlike SOAP web services) do not mandate XML results or inputs to be enveloped with special protocol-specific headers and message wrappers. This feature drastically simplifies the operations on the client by removing the need to preprocess the message headers and exposing the context of the message directly to the client’s parser.

In addition, an AJAX application running on a browser platform that supports DOM (Document Object Model) for JavaScript can natively and easily consume XML-formatted messages and navigate through the content.

In the example below, an XML message with shipping information:

               100200345100 	   in transit	   LA	   12-12-2007       

is parsed by JavaScript and navigated utilizing DOM objects:

var xmlInfo = httpRequester.responseXML;//get tracking_no using DOM. It is a single element, so go for text value of the first node var trackingNo = xmlInfo.getElementByTagName("tracking_no")[0].firstChild.nodeValue; 

The two concerns related to using XML for data exchange between AJAX front ends and RESTful web services are:

  1. Overhead associated with XML’s tagged markup nature
  2. Computational cost associated with parsing and tree navigation

To mitigate these concerns, keep your XML lean (if you can control it). Verbose or unnecessarily wrapped XML messages almost certainly will degrade the performance of an AJAX application on the browser.

JSON
JSON (JavaScript Object Notation) is a text-based representation for JavaScript data objects. It is a lightweight alternative to XML and has become the format many JavaScript developers favor.

This is how the shipment information in the XML message from the previous section would look if represented by JSON:

{"shipment":{     "tracking_no":"100200345100",     "status":"transit",     "location":"LA",     "date":"12-12-2007"  }} 

Curly braces delineate the structure of the objects, and key value pairs represent the object properties along with their states/values.

From a RESTful web services perspective, JSON simply is another text format with its own delineation rules. It requires no additional effort to produce service results in a JSON-compliant way. Furthermore, most versions of popular server-side languages such as Java and Ruby have native or third-party libraries readily available to facilitate conversion between JSON and language-specific data constructs.

On the front end of the AJAX application, JSON service responses can be easily parsed, evaluated, and assigned to textual variables using JavaScript’s eval() function:

var shipmentData = eval('('+httpRequester.responseText+')');//access tracking number by dereferencing the value using the 'dot' notationvar tracking_no = shipmentData.shipment.tracking_no; 

If you’re interested in learning more about integrating an AJAX front end with JSON-based services, read the DevX article “Speed Up Your AJAX-based Apps with JSON” by Alessandro Lacava.

Integration Challenges
Few technologies fit as well together and simultaneously provide developers with such richness of choices as RESTful web services and AJAX. However, even two services working in such harmony present a few challenges that you need to understand.

Weak Typing
As already mentioned, RESTful web services are flexible in the formats they use for the resource representation. You have complete freedom to present service results any way you choose, but that freedom requires significant diligence and attention to how you specify and change interfaces (e.g., a rigorous change-control process). Make sure each RESTful service is amenable to well-defined schema (regardless of the format) and for the sake of quality assurance carefully monitor the use of schemas for the services.

Service Contracts
The core ideas of RESTful web services are that resources are represented as URLs and consumers of those services can manipulate the services through HTTP methods. With lo-REST (GET and POST only) there is not much need for concern. Service clients can read the state of the resource only via GET and make updates to it only via POST.

With hi-REST services however, clients can create new resources using PUT method and delete them as well. For example, in the previously cited online shipment-tracking service (see article for reference) AJAX clients can create new shipments and assign unique shipment IDs to them, as well as delete them. In a massively distributed web environment, assigning that level of control to an AJAX client can be quite a challenge.

So can you trust web clients to perform operations as critical as resource creations on the fly? My experience suggests you can, but you must have a strong understanding of the environment in which the application is running, the business and technical contracts between the clients and the services, and the business rules related to governing the contracts. While banks won’t allow customers to assign account numbers to their newly created accounts, an internal application for shipment tracking that is well integrated with internal supply channels and all the rules governing the shipment-creation process could create new shipments. It could put (with PUT) the shipment info to the RESTful service that holds the new shipment’s ID, which the AJAX application would dynamically assign.

A Synergy Between Power and Simplicity
As cliché as it may sound, “match made in heaven” naturally comes to mind when speaking of RESTful web services and AJAX. Immediately upon seeing these two technologies, I was attracted by their potential synergy. Looking at the numerous examples provided by web innovation powerhouses such as Google or Amazon, as well as by doing my own work, I realized that these two technologies are some of the most powerful and at the same time simplest ways to build lean, flexible, and service-oriented web applications.

This article reviewed the essential aspects of integrating these two technologies to share not only the techniques and technology choices involved in the integration process but also the benefits of this simple, straightforward approach.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS