Integrating AJAX Clients and RESTful Web Services

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.

devx-admin

devx-admin

Share the Post:
Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019

Cybersecurity Banking Revolution

Digital Banking Needs Cybersecurity

The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to

FinTech Leadership

Terry Clune’s Fintech Empire

Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used

Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019 tech firms, as per data

Huawei Electric Dazzle

Huawei Dazzles with Electric Vehicles and Wireless Earbuds

During a prominent unveiling event, Huawei, the Chinese telecommunications powerhouse, kept quiet about its enigmatic new 5G phone and alleged cutting-edge chip development. Instead, Huawei astounded the audience by presenting

Cybersecurity Banking Revolution

Digital Banking Needs Cybersecurity

The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to customers around the world. Rising

FinTech Leadership

Terry Clune’s Fintech Empire

Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created eight fintech firms, attracting renowned

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used in design, coding, content writing

Generative AI Revolution

Is Generative AI the Next Internet?

The increasing demand for Generative AI models has led to a surge in its adoption across diverse sectors, with healthcare, automotive, and financial services being among the top beneficiaries. These

Microsoft Laptop

The New Surface Laptop Studio 2 Is Nuts

The Surface Laptop Studio 2 is a dynamic and robust all-in-one laptop designed for creators and professionals alike. It features a 14.4″ touchscreen and a cutting-edge design that is over

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted

Battery Investments

Battery Startups Attract Billion-Dollar Investments

In recent times, battery startups have experienced a significant boost in investments, with three businesses obtaining over $1 billion in funding within the last month. French company Verkor amassed $2.1

Copilot Revolution

Microsoft Copilot: A Suit of AI Features

Microsoft’s latest offering, Microsoft Copilot, aims to revolutionize the way we interact with technology. By integrating various AI capabilities, this all-in-one tool provides users with an improved experience that not

AI Girlfriend Craze

AI Girlfriend Craze Threatens Relationships

The surge in virtual AI girlfriends’ popularity is playing a role in the escalating issue of loneliness among young males, and this could have serious repercussions for America’s future. A

AIOps Innovations

Senser is Changing AIOps

Senser, an AIOps platform based in Tel Aviv, has introduced its groundbreaking AI-powered observability solution to support developers and operations teams in promptly pinpointing the root causes of service disruptions

Bebop Charging Stations

Check Out The New Bebob Battery Charging Stations

Bebob has introduced new 4- and 8-channel battery charging stations primarily aimed at rental companies, providing a convenient solution for clients with a large quantity of batteries. These wall-mountable and

Malyasian Networks

Malaysia’s Dual 5G Network Growth

On Wednesday, Malaysia’s Prime Minister Anwar Ibrahim announced the country’s plan to implement a dual 5G network strategy. This move is designed to achieve a more equitable incorporation of both

Advanced Drones Race

Pentagon’s Bold Race for Advanced Drones

The Pentagon has recently unveiled its ambitious strategy to acquire thousands of sophisticated drones within the next two years. This decision comes in response to Russia’s rapid utilization of airborne

Important Updates

You Need to See the New Microsoft Updates

Microsoft has recently announced a series of new features and updates across their applications, including Outlook, Microsoft Teams, and SharePoint. These new developments are centered around improving user experience, streamlining