A collection of computer systems and programming tips that you may find useful.
 
Brought to you by Craic Computing LLC, a bioinformatics consulting company.

Wednesday, April 22, 2009

Getting started with Sinatra and RestClient

Sinatra is a Ruby framework for developing web applications with RESTful interfaces. It looks like a great way to build specific applications where a full blown Rails app would be overkill.

I'm interested in it as a way to provide very focused, lightweight web services to support larger Rails applications. One example is fetching DNA sequences from a remote database, hosted on AWS EC2. Here is the entire Sinatra app (which calls a separate data lookup class).

#!/usr/bin/env ruby
require 'rubygems'
require 'sinatra'
require 'lib/seqlookup.rb'
get '/:db/:id' do
content_type('text/plain')
SeqLookup.fetch(params[:db], params[:id])
end

I ran into one wrinkle testing this out on my Mac. Following the 'hello world' example on their site did not work for me - never a good sign. It wants to fire up the Thin web server, which I don't have. It ought to then move on to try Mongrel and Webrick, but in my case it found some components of Thin and then barfed when it failed to find the rest. Including this line after the 'require' statements got it going.
set :server, %w[mongrel webrick]

But the better fix is to install Thin.
# sudo gem install thin

So Sinatra is a great way to create lightweight web services, but how do you consume them? Well you can use the URLs directly in curl or wget, or you can use ActiveResource from within Rails. Or you can use Sinatra's friend RestClient

Install the gem and then you can call your new web service with a script like this:
#!/usr/bin/env ruby
require 'rubygems'
require 'rest_client'
data = RestClient.get 'http://localhost:4567/genbank/NM_007294'
puts data

So far I'm impressed with these tools. I can reduce the complexity of my Rails apps by splitting off common services to small Sinatra apps. Sure, I'm adding complexity by having multiple web apps running and I risk failure in a supporting app causing failure in the larger app. But using a reliable hosting service like EC2 this is a risk I'm willing to take.

No comments:

Archive of Tips