Easily integrating your Mojolicious app with Facebook.

2011-01-08 − 🏷 facebook 🏷 mojolicious 🏷 oauth 🏷 oauth2 🏷 perl

Facebook has recently released a new Graph API. It's a simple RESTish API, and uses the newly released OAuth2 spec for authorization. This makes it a great match for Mojolicious, and using my new OAuth2 plugin (Also coming to a CPAN mirror near you), it's absolutely trivial.

Here is a simple Lite example. Just register an app with facebook to get the key and secret.

   use Mojolicious::Lite;
   # configure the plugin
   plugin 'oauth2', facebook => {
       key => 'my-key',
       secret => 'my-secret' };

   get 'hello' => sub { 
      My $self=shift;
      #redirects the gets the token asynchronous   
   $self->get_token('facebook', callback => sub {
      my $token=shift;
      my $me=$self->client->get(
          $self->render( text =>
            "Hello ".$me->{name} );

As you can see, the plugin handles the request flow automatically. We then use the built in JSON parsing in the Mojolicious Client to turn the API data into structures we can work with in our application.

Updating facebook data is just as trivial, you just use post requests with the data you need to update. See http://graph.facebook.com/ for more info on that.

If you plan to run your app through a standalone daemon such as Hypnotoad (I really think you should :) It could be worth it to rewrite the last section of your app to take advantage of async operations like this:

  $self->client->async->get(        'https://graph.facebook.com/me?access_token='.$token, sub {
  my $me=shift->res->json;
  $self->render( text=>"Hello ".$me->{name} );

The async plugin itself also supports an optional async=>1 setting to enable async fetching of the token.