RESTful routes for Sinatra applications

What is it?

Actually it’s a set of templates to introduce RESTful routes into Sinatra. The only thing for you to do is to provide the views. Automatically works nicely for models based on ActiveRecord, DataMapper, or Stone.

Of course you need to require the gem in your sinatra application:

require 'sinatra'
require 'sinatra/rest'

I’m sure you know how to defining routes in Sinatra (get, post, …). But this time you let the model’s name define the routes by convention.

For example, if your model’s class is called Person you only need to add this line:

rest Person

Which will add the following RESTful routes to your application. (Note the pluralization of Person to the /people/* routes.)

Verb Route Controller View
GET /people index /people/index.haml
GET /people/new new /people/new.haml
POST /people create → redirect to show
GET /people/1 show /people/show.haml
GET /people/1/edit edit /people/edit.haml
PUT /people/1 update → redirect to show
DELETE /people/1 destroy → redirect to index

As you can see, each route is also associated with a named code block in the controller. The controller does the minimum to make the routes work. Based on the route it treates the model and redirects or renders the expected view.

So imagine the following steps to show a single person:

  1. request from the client’s browser
    GET http://localhost:4567/people/99
  2. Find and set @person in the controller
    @person = Person.find_by_id(99)
  3. render the view to show @person
    render VIEW_DIR/people/show.haml

It’s up to you to provide the views, because this goes beyond the restful routing. The variable @person is correctly named and injected into the view. So maybe you’d like to do something like this:

  <div>ID: <%= %></div>
  <div>Name: <%= %></div>

That’s it!


Guess what!

$ sudo gem source --add
$ sudo gem install blindgaenger-sinatra-rest

Or clone of course:

$ git clone git://


Questions, suggestions or need some help?

Send me an Email or have a look at my Homepage on how to get in touch with me.

Fork me on GitHub