Steve Klabnik changelog.com/posts

grape: a Ruby DSL for making APIs

If you’re writing a web service and you’d like to expose an API to the world, few things are simpler than running a Sinatra application to provide one. Grape, by Michael Bleigh, is one of those things. Grape builds on top of rack, but gives you versioning, automatically providing responses in multiple formats, and other cool stuff.

Here’s a tiny example for FooCorp, who wants to expose their paradigm-shifting, revolutionary Widget models to the world:

class Foo::API < Grape::API
  version '2'

  resource :widgets do

    get :best do
      Widget.best_list
    end

    get '/show/:id' do
      Widget.find params[:id]
    end

  end
end

Since this is just another Rack application, you’d put this into your config.ru:

run Foo::API

This gives you these two calls:

  • /2/widgets/best(.json)
  • /2/widgets/show/:id(.json)

I originally thought that Rails 3 did just about as much as they possibly could to eliminate extra noise with the new respond_with syntax, but it’s still more than Grape. Here’s what a similar Rails 3 controller would look like:

class WidgetController < ApplicationController
  respond_to :html, :json

  def show
    respond_with(Widget.find(params[:id]))
  end

  def best
    respond_with(Widget.best_list)
  end
end

This also doesn’t take into account the versioning aspect, either. Now, Rails obviously can do a bit more than Grape can, but APIs are a great reason to use a microframework: You want the web server to be doing as little work as possible with an API. Serving up some JSON is a much more lightweight activity than the big, JavaScript-heavy pages that we expect from the Web today.

Grape’s roadmap shows some cool stuff is still in store. Rate Limiting is an important feature for any API, and filter support and OAuth are nice to have.

[Source on GitHub] [RDoc] [Presentation from RubyConf 2010]


Discussion

Sign in or Join to comment or subscribe

Player art
  0:00 / 0:00