Contributor: Tasnim Mehzabin, Nascenia
Facebook Graph API is a low-level HTTP-based API. It can be used to query data, post new stories, manage ads, upload photos and many other tasks. In this article, we will learn how to use Facebook Graph API in a Ruby on Rails application. The current version of the Graph API is v2.8.
For this purpose, we have used two gems.
- Omniauth-facebook
- Koala
Omniauth-facebook and Koala
Omniauth-facebook is simply a Rack middleware. Here we have used it for authentication. In this phase, the users provide the permission to fetch the data from their Facebook profiles.
Koala is a light, flexible library of facebook for ruby applications. It provides support for OAuth authentication, the Graph and REST APIs. Here Koala has been used to fetch the data.
We can use Facebook Graph API through the following two steps.
- Register your application on facebook for developers site so that API calls can be made using the application.
- Add and Configure omniauth-facebook and koala in the application.
Register the application with Facebook
The steps to register the application with Facebook are given below:
- Log in to your Facebook account.
- Go to the following link facebook for developers site.
- Click on the Add a New App on the top of the page and a pop-up page will appear.
- Give a Display Name, Contact Email. Here Display Name is the name for your application that will be shown to the users. Select the category and create App ID.
- You will be taken to the Product Setup page. Here you can add various products.
- Go to the Settings page.
- Scroll down. Click on Add Platform. Select Website as the platform. As Site URL, enter http://localhost:3000/. Save the changes.
- Go to App Review, toggle “Make App public?” to Yes.
This process will give the App ID and App Secret. These are required to connect the application to facebook.
Add and Configure omniauth-facebook and koala
Firstly create a new rails app and navigate to the directory of your new application. Add the gems omniauth-facebook and koala to the Gemfile.
rails new sample_app cd sample_app # Add the gems to Gemfile gem 'omniauth-facebook' gem "koala", "~> 1.10.0rc"
And then run
bundle install
Then we have to specify the version of koala for global use.
Add the following line in /config/application.rb:
Koala.config.api_version = 'v2.0'
Then the /config/application.rb file will look as follows:
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 have to use the app ID and app secret that we obtained before. We will create the file /config/facebook.yml and store them there.
development: app_id: Enter App ID here secret: Enter App Secret here
In order to load the /config/facebook/yml file when the application starts, we need to create another file /config/initializers/facebook.rb and add the following code:
FACEBOOK_CONFIG = YAML.load_file("#{::Rails.root}/config/facebook.yml")[::Rails.env]
Now to configure omniauth-facebook we have to create another initializer file /config/initializers/omniauth.rb .
Rails.application.config.middleware.use OmniAuth::Builder do provider :facebook, FACEBOOK_CONFIG['app_id'], FACEBOOK_CONFIG['secret'], {:scope => 'user_about_me'} end
Thus Omniauth has been added to the Rack middleware and Facebook has been configured as the provider.
Now we need model, view, and controller for our application. We will start by creating a model, /app/models/user.rb.
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 a method name koala. It will fetch data from facebook graph API. Now we will fetch only username and profile picture of the currently logged in user.
Lets create a controller /app/controllers/users_controller.rb and add the following code:
class UsersController < ApplicationController def index end def login @user = User.koala(request.env['omniauth.auth']['credentials']) end end
Now we will display the result in /app/views/users/index.html.erb
This is the root page with the link to /auth/facebook. It will do the authentication of users.
We will create another page to display the result /app/views/users/login.html.erb
For configuring the necessary routes, we add in /config/routes.rb:
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
Now we can run our application. Run rake db: create and start the server.
Go to http://localhost:3000/ and click on the link Facebook Login. It will then authenticate and show the username and profile picture.
In case of any difficulty, you can always check the API documentation here.
More to Explore
The Quest for Knowledge Continues. Fuel Your Curiosity.

