Learn a fast and
easy way to implement and consume web services with Ruby on Rails' Active
Resource. In a RESTful way, Rails helps you simplify the interoperability
between your web applications. Examples walk you through the basic operations
of Active Resource. You'll also explore the differences between REST and
SOAP.

Saideep Annadatha is currently working as part of the TXSeries (Transaction processing middleware on distributed platforms) quality assurance team at IBM India Software labs and is responsible for the Inter System Communication (ISC) area. He has worked on several Rails-based projects previously. Apart from Ruby on Rails, his interests include working with Python and C.

Introduction

Today's applications need to interoperate not
only with browser-based clients but also with other applications. To
achieve interoperability, web applications commonly offer a web service
API. A web service API offers remote access to an application over a
network (such as the Internet). Until recently, web service APIs were
integrated using heavy and complex SOAP-based web services which, besides
having few advantages, were taking a long time to implement.
The Rails framework with Representational State Transfer (REST)-based web services has an easier and
faster way to implement and consume web services with Active Resource.

With the RESTful way Rails is implemented, it's now easy to offer different content types, or
representations of a particular resource, through only one Rails action.
Advantages include:

Various representational states of a resource

Additional support for non-browser-based HTML clients is
simplified in the Controller view.

Interoperability between applications and with new clients

In this article, learn about REST, SOAP, Rails Active Resource, and how to
improve the interoperability between multiple applications.

Ruby on Rails

Ruby on Rails (also called Rails, or RoR) is an open source web
application framework written in the Ruby language. Ruby on Rails is
designed to help you
develop and deploy web applications faster and easier by making several
assumptions when compared to other languages and frameworks. It is
intended to be used with an Agile development methodology for rapid development.

Web services

Web services are application components that communicate using open
protocols. They can be used by other applications. Web services are simple APIs
that are accessed with HTML and executed on remote systems hosting
requested services. Web services are the key point of
integration for various applications on different platforms,
in different languages, and on different systems.

REST is not a protocol; it is an
architectural style of large-scale networked software that takes advantage
of the technologies and protocols of the World Wide Web. REST describes
how distributed data objects, or resources, can be defined and addressed,
stressing the easy exchange of information and scalability. REST
architecture describes six constraints applied to the architecture.

SOAP, on the other hand, is a protocol specification for exchanging
structured information in the implementation of web services in computer
networks. It relies on XML as its message format and usually relies on
other application layer protocols (RPC and HTTP) for message negotiation
and transmission. SOAP can form the foundation layer of a web services
protocol stack, providing a basic messaging framework upon which web
services can be built.

REST versus SOAP

The chart below shows some comparisons between REST and SOAP.

REST

SOAP

Is not a
protocol

Is a protocol

Is the trendy way to
create a web service

Is older; major applications have built their communication and interoperability
with other applications using SOAP.

Architecture: Key resources are identified;
they can be
entities, collections, or anything that seems worthy of having its own
URI. The standard methods (the HTTP verbs) are mapped to
resource-specific semantics. All resources implement the same uniform
interface. The dimension of content-types allows for different
representations of resources (for example, in XML, HTML, and plain text)
and the ability to link to resources in resource
representations.

Architecture: Several layers of specifications for
message format, message exchange patterns (MEP), underlying transport
protocol bindings, message processing models, and protocol extensibility.
Mainly used for enterprise applications to integrate various types
of applications. Another trend is to integrate with legacy
systems.

Key to methodology is to write web services using a
widely known and used interface: the URI.
Any client or server
application with HTTP support could easily call the service with an HTTP
GET command.

Depending on how the script is written, the
resulting HTTP response might be as simple as standard headers and a
text string containing the current price for the given ticker symbol. Or,
it might be an XML document. This interface method has significant
benefits over SOAP-based services.

Provides relatively stronger typing since it has a fixed set of
supported data types. SOAP guarantees that a return value will be
available directly in the corresponding native type in a particular
platform.

With HTTP-based APIs, the return value needs to be
deserialized from XML and then type-casted.

Requests and responses can
be short.

Requires an XML wrapper around every request and response.
Once namespaces and typing are declared, a four or five-digit stock quote
in a SOAP response could require more than ten times as many bytes as
the same response in REST.

HTTP-based RESTful APIs can be consumed using simple GET requests. Intermediate
proxy servers and reverse-proxies can cache their responses easily.

By
sticking to simple semantics scales, REST can take advantage
of all levels of caching between clients and the server.

Requests use POST and require a complex
XML request to be created, which makes response-caching difficult.

REST relies on a single application protocol (HTTP), URIs, and standardized
data formats through XML. It employs
established HTTP methods, such as GET and POST, to direct applications. Instead of creating a standard, machine-readable way for applications to
discover and use application components on remote systems (the way SOAP
is being used for web services), REST developers use URIs to create a
common ground so applications can use HTTP and XML to share data. REST
developers use XML documents rather than application-method calls to tell
distributed programs how to use each other's data.

REST proponents say that using the SOAP protocol to access the functions of
remote programs directly is doomed to suffer from the same type of
interoperability problems that hobbled previous distributed computing
architectures such as DCOM and Common Object Request Broker Architecture.

Active Resource

Prior to the RESTful approach for web applications communicating between
server and client applications, SOAP and other XML-RPC forms were
used to communicate via an API. Active Resource, introduced with
Rails 2, replaced Action Web Service. Active Resource has complete
understanding of the RESTful routing and the XML representation. This is a
class that maps RESTful resources as models in a Rails application.
Active Resource provides the tools to quickly and easily consume
REST-based web services conforming to the Rails RESTful URI structure and
protocol conventions. Active Resource automatically maps the response from
any conforming service to rich Ruby objects. Active Resource also provides
all the lifecycle methods needed to easily perform the basic CRUD
functions.

The CRUD operations correspond to the HTTP
methods POST, GET, PUT, and DELETE, respectively. Active Resource has a
method for each of these HTTP methods, too. They take the same arguments as
CRUD but return a hash of the XML received. An Active Resource object is
essentially a front end to the REST web server. It obtains and modifies
its data by making HTTP calls back to the server and parsing the XML
results back into a Ruby object.

A minimal Active Resource example is shown in Listing 1. Assume there's a
library application that has each category as a different client and
Indian History is one of the categories.

Listing 1. Active Resource example

ActiveResource has the same methods as Active
Record. In the code sample above, the class IndianHistory is being inherited from ActiveResource Base. On the second line,
self.site holds the site value that holds the URI of
the IndianHistory books. In this case , the URI is http://indian-history.com (assuming that the URI is
yet another Rails application with required models and
controller actions).

Now that the class is mapped to the RESTful resources located with the site
value, you're ready to manipulate the resources of the IndianHistory
class. To get a list of all books under
Indian History, you would call its find method, which is similar to the
Active Record find method.

>> books = IndianHistory.find (:all)

This Active Resource module is similar to the Active Record
module; they have the same look and feel.

Assume you're looking for books with the title "Akbar." You would use the
following code:

Listing 3. Update

You updated the availability of the book and saved the record.
There is a slight difference between ActiveResource and ActiveRecord: The
methods (save) and (update) are not present in the ActiveResource.

Finally, the statement below removes the record from the database.

>> IndianHistory.delete(2)

In addition to the basic operations described here, Active Resource
lets you support HTTP basic authentication by setting an HTTP
header. The security aspect of client server connections is accomplished
by Active Resource authenticating on each connection, provided the username
and password are set and errors are thrown on failure of authentication.
Basic authentication can also be easily implemented.

The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.