LaunchSchool - An Online School for Developers /

Blog

Integrate Facebook Graph APIs in Rails Applications

In this article we will understand how to go about using facebooks graph API in a Ruby on Rails web application. We will be using two gems to get the work done, omniauth-facebook and koala.

Omniauth-Facebook and Koala

Omniauth-facebook is facebook OAuth2 strategy for OmniAuth and as every OmniAuth strategy it is a Rack Middleware. Koala is a facebook library for ruby which supports facebook graph API. In our application we are using omniauth-facebook for authentication(Getting permission from user to get data from their facebook profile) and koala for fetching the data. With koala you can do range of things, koala also provides unit tests for all of its methods.

We will now see how to use these gems in ruby on rails application. Before we start let me specify my development environment, I am using ruby 2.0.0, rails 4.1.1, ubuntu OS. Some things like gem version in application might change depending upon your development environment. We will go through two steps explained below to complete the application.

  1. Registering your application on https://developers.facebook.com/ so you can make API calls from your application.
  2. Add and Configure omniauth-facebook and koala correctly in your application.

Step 1. Register your application with Facebook

Following are the necessary steps for successful registration of your application.

  1. Log in to your facebook account, go to https://developers.facebook.com/
  2. Click on Apps, Add a new app. There will be a pop up, select website as a platform.
  3. Name your application, create new Facebook app ID. Select category(keep everything else as it is) and create App ID.
  4. Scroll down and Enter site URL as http://localhost:3000/ which is your default local rails server. Scroll down and click on Skip to Developer Dashboard in Next steps section.
  5. Go to Settings and enter your email address in Contact Email. Save changes.
  6. Go to status and Review, toggle “Do you want to make this app and all its live features available to the general public?” to yes.

The whole purpose of step 1 was to get App ID & App secret and to activate the application(step 6) so we can make calls from our web application.

Step 2. Add and Configure omniauth-facebook and koala

Create a new rails application rails new sample_app. Enter into directory of your new application. Now we have to setup and configure both omniauth-facebook and koala.

First lets add both of the gems to the Gemfile.

1
2
gem 'omniauth-facebook' # Facebook authentication
gem "koala", "~> 1.10.0rc" # Facebook API

As apps created after f8 2014 cannot use the v1.0 API, we specify version for global use in /config/application.rb. After adding Koala.config.api_version = 'v2.0' your /config/application.rb will look something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
require File.expand_path('../boot', __FILE__)

require 'rails/all'

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module SampleApp
  class Application < Rails::Application
    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.

    # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
    # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
    # config.time_zone = 'Central Time (US & Canada)'

    # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
    # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
    # config.i18n.default_locale = :de
    Koala.config.api_version = 'v2.0'
  end
end

Now we use App ID and App Secret we got from previous section. Lets create file facebook.yml to store id and secret so we can use it in our application. In case you are using git(if not you should be), its a good idea to put /config/facebook.yml in .gitignore.

1
2
3
development:
  app_id: Enter App ID here
  secret: Enter App Secret here

We need to load /config/facebook.yml when application starts, we can do it by creating a new file facebook.rb and adding code below in facebook.rb. This file will be placed in initializers folder.

/config/initializers/facebook.rb

1
FACEBOOK_CONFIG = YAML.load_file("#{::Rails.root}/config/facebook.yml")[::Rails.env]

We will now create one more initializer file where we configure omniauth-facebook. Here lets create omniauth.rb.

/config/initializers/omniauth.rb

1
2
3
Rails.application.config.middleware.use OmniAuth::Builder do
  provider :facebook, FACEBOOK_CONFIG['app_id'], FACEBOOK_CONFIG['secret'], {:scope => 'user_about_me'}
end

Here we have added OmniAuth to the Rack middleware and configured facebook as provider. We are passing App Id and App Secret through environment variables and added required scope. Now we should be able to carry the authentication smoothly.

Now we need model, view, controller for our application. Let create model first, here we have user.rb as our model. If you wish you can use scaffold command but that will just create lot of files which we do not need right now. Also as of now we are not storing any data but if you are building something on top of this application you may need to store some basic information so I am using model.

/app/models/user.rb

1
2
3
4
5
6
7
8
9
class User < ActiveRecord::Base

  def self.koala(auth)
    access_token = auth['token']
    facebook = Koala::Facebook::API.new(access_token)
    facebook.get_object("me?fields=name,picture")
  end

end

Here we have defined method koala which we will call from our controller. User.koala takes authentication credentials obtained using omniauth-facebook and then we use koala methods for fetching data from facebooks graph API. facebook.get_object("me?fields=name,picture") will get name and profile picture of user who is currently logged into facebook.

/app/controllers/users_controller.rb

1
2
3
4
5
6
7
8
9
10
11
class UsersController < ApplicationController

  def index

  end

  def login
    @user = User.koala(request.env['omniauth.auth']['credentials'])
  end

end

login is method/action we have defined to call koala method we just defined and display result in login.html.erb.

/app/views/users/index.html.erb

1
<%= link_to "Facebook Login", '/auth/facebook' %>

This is a root page with link pointing to /auth/facebook which will do the authentication part for us.

/app/views/users/login.html.erb

1
2
<%= image_tag @user['picture']['data']['url'].to_s %>
<%= @user['name'] %>

This page displays result of our application.

/config/routes.rb

1
2
3
4
5
Rails.application.routes.draw do
  root to: 'users#index', via: :get
  get 'auth/facebook', as: "auth_provider"
  get 'auth/facebook/callback', to: 'users#login'
end

Configured all the necessary routes.

Now just to finish and test the application.

  1. Run bundle, rake db:create and then start the server rails s. That’s it now your application is ready to use.
  2. Go to http://localhost:3000/ and click on Facebook Login.

Errors

  • If you are using facebooks graph API for the first time you might run into various errors, facebook has very nice documentation on handling these errors.
  • If you are deploying your application to production you have to make changes in application settings on facebook(callback_url and more) and setup app id & secret into production environment.

Conclusion

Social plugins(especially facebook logins!) are widely used web applications. We covered basic of how you can integrate facebook into your application. Please refer to koala and facebook documentation for better understanding and deeper integration.

References/Resources