Abhishek Malay Chatterjee

Subscribe to Abhishek Malay Chatterjee: eMailAlertsEmail Alerts
Get Abhishek Malay Chatterjee: homepageHomepage mobileMobile rssRSS facebookFacebook twitterTwitter linkedinLinkedIn


Related Topics: Java EE Journal, Apache Web Server Journal, XML Magazine, SOA & WOA Magazine, Open Web Magazine

J2EE Journal: Article

Web Services on Rails

A Web 2.0 perspective for SOA

The term Web Services refers to loosely coupled, executable application components linked dynamically over the network with open standards. Typically, they are software components that employ one or a combination of the following XML standards: SOAP, WSDL, and UDDI. Ruby on Rails is an open source Web application framework written in Ruby that closely follows the Model View Controller (MVC) architecture. It strives for simplicity, allowing real-world applications to be developed in less code than other frameworks and with a minimum of configuration. To define Rails - the Web Services or a Web Framework - we have to say that Rails is a full-stack, open source Web development framework that requires comparatively less time and effort to code XML interfaces than most other frameworks.

Implementation
Rails has a vast library of plug-ins, and similar plug-ins can also be developed easily. The Action Pack splits the response into a controller part (performing the logic) and view part (to render the template). Action Pack implements the CRUD (create, read, update, delete) actions as public methods on Action controllers that are responsible for handling all of the actions relating to a certain part of the application. Action views use templates that are written using embedded Ruby code in tags along with HTML similar to what ASP does.

BlogController < ActionController::Base
    def display
       @customer = find_customer
    end

    def update
       @customer = find_customer
       @customer.attributes = params[:customer]
       @customer.save ?
         redirect_to(:action => "display") :
         render(:action => "edit")
    end

    private
       def find_customer() Customer.find(params[:id]) end
    end

Actions grouped in controller as methods

<% for post in @posts %>
    Title: <%= post.title %>
<% end %>

Embedded Ruby for templates

Choosing a Web Server
WEBrick, the default server for Rails, is written entirely in Ruby. It supports the standards you'll need: HTTP for communications, HTML for Web pages, and RHTML for embedding Ruby code into Web pages for dynamic content. WEBrick has some important advantages:

  • It comes with Ruby, so it's free and always available for use or packaging of projects.
  • It's built into Rails, so we don't have to go through any special effort for integration.
  • It can make direct calls to a Rails application because they are both written in Ruby.
  • It's simple to use.
Apache
Although WEBrick is the most convenient choice, it's not the most scalable or flexible choice. The Apache Web server is the most widely deployed Web server in the world. You can choose from an incredible array of plug-ins to run dozens of programming languages or serve other kinds of dynamic content. Apache scales well, with outstanding caching plug-ins and good support for load balancers and sprayers (machines that efficiently spread requests across multiple Web servers). If you're looking for a safe solution, look no further than the Apache Web server.

Other options are lighttpd, Mongrel, and any Web server that supports CGI.

Action Web Service
Action Web Services have procedures for implementing SOAP and XML-RPC Web Services Protocols. Automatic generation of the WSDL (Web Service Definition Language) files or the contract for the Web Service is another feature of Action Web Service. To expose a method as an API, we have to use the ActionWebService::API::Base derivative. We can then specify the API definition class wherever we want to use the API. The implementation of the method is done separately to the API specification. Action Web Service camelcases the method names according to the Rails inflector rules for the API visible to the public. This means that the names in the WSDL file will be camelcased. For example, a name such as loan_amount gets converted to LoanAmount in the WSDL file. However, this can be disabled by using the inflect_names false command in the API definition. Input output parameters are stated as api_method :<method name>, :expects => [<data type>], :returns => [<data type>].

The Api can then be used in the controller class using the statement web_service_api <apiName>. The following are the advantages of using Action Web Services:

  • Drop-in support for accessing other Action Web Service APIs into our controller code.
  • Custom APIs generated using these Action Web Services and exposed as endpoints can be used by other platforms for their functionality.

    The following are the disadvantages:

  • Too much support for XML-RPC types of messages.
  • It does not implement all supported features of W3 specifications, only those required for interoperability with other platforms such as .NET.
Choosing the XML Message Format in Rails for Web Services
Although SOAP stands for Simple Object Access Protocol, creating messages that can comply with all the interoperability rules (Basic Profile Compliance) is difficult, and the messages generated are complex and huge. Thus, another standard called REST based Web Services are becoming mainstream with industry leaders like Yahoo and Amazon exposing their Web Services as REST Web Services.

The creation of REST Web Services is supported by Rails 1.1 and above; this makes the creation of Web Services in Rails a child's play. REST stands for Representational State Transfer; this basically means that each unique URL is a representation of some object. We can get the contents of that object using an HTTP GET; to delete it, we might use a POST, PUT, or DELETE to modify the object.

Some Advantages of REST over SOAP
A REST call is actually accessing a Remote Resource instead of a normal Remote Procedure Call. It employs the usage of existing standards such as HTTP, XML, or TCP/IP, rather than creating new standards as in the case of SOAP. REST covers the most common scenarios and problems rather than trying to address every possible scenario.

Creating a Simple Web Service
The first step is to create a new Rails application and then create the raw structural files within which we will code the service.

rails FirstWebService
ruby script/generate web_service HelloWorld hello

Now, browse to the API folder and edit the helloworld_api.rb to define the interface. This step is optional but it's recommended to implement.

class HelloWorldApi < ActionWebService::API::Base
    api_method :hello,
    :expects => [:string],
    :returns => [:string]
end

Next, write the controller. Edit the helloworld_controller.rb. Here, we want to write the actual Web service code and specify the name of the API for the Web Service.

class HelloWorldController < ApplicationController
    wsdl_service_name 'Hello'

    web_service_api HelloWorldApi

    def hello (str)
      return "Hello "+str+", Howz life??"
    end
end

Running the Web Service
When finished with the code, use the following command to start the WEBrick server. The default startup port is 3000.

ruby script/server -p <port>

The endpoint for the Web Service is given below:
http://<machine-name>:3000/HelloWorld/invoke

The following is the WSDL endpoint:
http://<machine-name>:3000/HelloWorld/hello.wsdl

Testing Web Services
A big advantage to using Rails for Web Services development is having access to its testing features:

  • Functional Testing: Test the APIs by creating a functional test for the controller dispatching the API. Then call the #invoke in the test case for performing the invocation.
  • Scaffolding: Adding the following directive to the controller class automatically generates an HTML interface to manually test the Web Services (this feature is similar to what IDEs like Visual Studio provide):
    web_service_scaffold :invoke
Conclusion
Dynamic typed languages like Ruby extensively use REST instead of SOAP-based Web Services. The core architecture has many similarities with the J2EE architecture. However, the approach to development of Web applications is different in the two frameworks. Rails prefers explicit code instead of configuration files, and the dynamic nature of the Ruby language generates much of the plumbing code at runtime. Finally, the MVC structure of development of Web applications is the biggest advantage in Rails.

References

  • http://manuals.rubyonrails.com/read/chapter/67
  • www.xml.com/pub/a/2006/04/19/rest-on-rails.html
  • www-128.ibm.com/developerworks/java/library/j-cb08016/
  • http://searchwebservices.techtarget.com/tip/1,289483,sid26_gci1180700,00.html
  • More Stories By Abhishek Malay Chatterjee

    Abhishek Malay Chatterjee is working as part of the Web Services COE (Center of Excellence) for Infosys Technologies Ltd., a global IT consulting firm, and has substantial experience in publishing papers, presenting papers at conferences, and defining standards for SOA and Web services.

    Comments (1) View Comments

    Share your thoughts on this story.

    Add your comment
    You must be signed in to add a comment. Sign-in | Register

    In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


    Most Recent Comments
    anm 03/25/07 10:29:16 AM EDT

    Hi,
    I am new to RoR. I executed the two statements as mentioned by you, but I did not see an API folder anywhere, nor the rb files you mentioned. Can you help me figure out what's wrong? In my C:\ruby\lib\ruby\gems\1.8\gems directory, I have actionwebservice-1.2.2 folder.
    Need your help!