Go REST with Rails

Web 2.0 Expo Conference

This one I found very interesting. It was presented by David Heinemeier Hansson from 37signals

I wasn’t familiar with the REST concept prior to the presentation so here’s a wikipedia article on REST for some background.

In a nutshell David was working on creating an API to 37signals Basecamp product and detected a very strong smell while going through that exercise. When faced with a similar situation for their new product (Highrise) he knew that they needed to take a different approach. If I understand what they did correctly it boils down to this:

Your typical application performs Create, Read, Update and Delete operations on the data that it works with. This is obvious at the database level. What REST does – or at least how 37signals used the concept in building their Highrise API – is it extends this standard set of operations all the way up to the web layer and uses the very low level HTTP actions to implement them.

The key thing is to design your application and the URLs not as actions but to treat everything as a resource and apply 4 verbs to each resource.

Data Layer Web Layer
Create POST
Read GET
Update PUT
Delete DELETE

The actual implementation is done via an input field within an HTML form.

<form action="resource being modified" method="POST">
    <input name="action" value="PUT"/>
...
</form>

The other thing that was really interesting was that this paradigm lends itself to getting your output in different formats very easily. Since you define your URLs to refer to resources and not actions getting your responses back in different formats is simple.

For example say you are working with a list of users.
Your URL might look like this:

http://foo.bar/users

This by default would return you the list of users in some HTML page.

To get this list as XML you would only need to change the URL to:

http://foo.bar/users.xml

To get this list as an RSS feed you would only need to change the URL to:

http://foo.bar/users.rss

Likewise for any other format. There are a number of built-in formatters but to create a new one was very simple.
It’s like getting a different View of the same Model in MVC.

To GET a single user the URL might look like:

http://foo.bar/users/1

where “1” is the id of the user.

I mentioned earlier that the mechanism is very low level. They use the HTTP response codes to describe the result of the operation (verb) that was requested.

More details on this can be found at http://mr.hamptoncatlin.com

It's only fair to share...
Share on FacebookGoogle+Tweet about this on TwitterShare on LinkedIn

Leave a Reply