Simplify interoperability between web applications using Rails Active Resource

Take the RESTful way

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.

Share:

Saideep Annadatha (saideep.a@in.ibm.com), Software Engineer, IBM

Saideep Annadatha photoSaideep 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.



03 August 2010

Also available in Chinese Japanese

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.

The Rails framework is a combination of several packages:

  • Active Record: An object-relational mapping layer for database-related access and functions
  • Action Pack: A manager of controller and view functions
  • Action Mailer: A handler of email
  • Active Support
  • Active Resource: Provides web services (was Action Web services)

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.

RESTSOAP
Is not a protocolIs a protocol
Is the trendy way to create a web serviceIs 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
class IndianHistory < ActiveResource::Base
self.site = “http://indian-history.com”
end

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:

>> books = IndianHistory.find(:all, :params => { :title => “Akbar”}}

Unlike the regular :conditions clause in the Active Record find method, the example instead uses :params, and the URL is GET http://indian-history.com/indian_histories.xml?title=Akbar.

Active Resource is not limited to retrieving data. You can use all the CRUD operations. In the script/console you can use:

>> IndianHistory.create (:title => “Jhansi Stories”, :amount => 233.00, :available => 0)

The line above would create an HTTP POST with the supplied data to the controller where the code in Listing 2 exists in the create action.

Listing 2. Create
class IndianHistoryController < ActiveResource::Base
def create
@book = IndianHistory.new (params [:indian_history])
respond_to do |format|
if @book.save
flash[:notice] = “New title added successfully” 
format.html { redirect_to(@book) }
format.xml { render :xml => @book, :status => :created}
else
format.html { render :action => “new” }
format.xml { render :xml => @book.errors, :status => :unprocessable_entity}
end
end
end

end

If the book record is saved successfully, the newly created record is returned with an HTTP 201 status code, and the view is redirected with the newly created record.

Similarly, you can update and delete the records, provided you have permission or access to perform administration.

For the Update operation, in the script/console use:

Listing 3. Update
>> book= IndianHistory.find (2)
>> book.available = 1
>> book.save 
>> book = IndianHistory.find (2)
>> book.available # => 1

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.


Summary

In this article you learned about web services, REST, SOAP, and Rails Active Resource. A simple example of Active Resource walked you through the CRUD operations.

The Ruby on Rails Active Resource package provides easy communication between multiple web applications in a RESTful manner. In addition to the CRUD operations, it lets you create customized actions.

Resources

Learn

Get products and technologies

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


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.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into Web development on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Web development
ArticleID=504363
ArticleTitle=Simplify interoperability between web applications using Rails Active Resource
publish-date=08032010