Friday, November 7, 2008

Using REST for a Facebook Application

Image representing Facebook as depicted in Cru...Image via CrunchBaseIf you're into Ruby on Rails, you've probably heard a lot about REST. It supposedly simplifies your life, but in many situations, things actually get more complicated.

Building Facebook apps is one of these situations. I've been using the Facebooker Rails plugin that helps you interact with the Facebook API.

Facebooker gives all requests from Facebook an "fbml" format. You need to add this line to your config/initializers/mime_types.rb file:

Mime::Type.register 'text/html', :fbml

You need to handle this format when you call respond_to:

def index
@facts = @topic.facts

respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @facts }
format.fbml end

The meaning of RESTful requests depends on which method or HTTP verb is used.

When GET is used and the path is "/topics/4/facts", the request is routed to the controller's "index" action. In this example, all the facts for topic 4 will be returned. But if POST is used, the request is routed to the "create" action, which will ry to add a new fact to topic 4 (these are nested resources).

But all Facebook requests are made with GET, so your code or your plugin needs to look at a request parameter called fb_sig_request_method to see which method was used initially.

One problem I had was deleting something RESTfully from a Facebook canvas page.

Normally, clicking a RESTful delete link created by Rails causes Javascript to run that creates the confirmation popup and a form that passes the authenticity_token variable required for deleting something.

But Facebook doesn't allow you to execute javascript so you can't rely upon the javascript normally created by the link_to tag to create the form when the page is loaded.

You can't create the form in HTML and then use FBJS to submit it either; Facebook rewrites your forms, dropping the name attribute. So you can't call the form when you click a link.

In the end I had to settle for confirming the deletion on a page of its own. And a less than desirable button had to be used instead of a link because Facebook links can't submit a form. So I'm still not happy with the outcome.
Reblog this post [with Zemanta]

1 comment:

Al Brown said...

Seems like these issues are now fixed. Facebooker has advanced some since I last used it to do REST. I didn't even have to do anything to handle FBML mime type or figure out whether the request was POST or GET.

Even deleting a resource works seemlessly right thru a Facebook canvas page.