+1

Google api with Rails

Google API is a comprehensive API of Google, which allows applications to access, manipulate with most Google services like Calender, Drive, Gmail, Google+, YouTube ... This article will guide you to build one application by Ruby on Rails web application that allows users to log in via their Google account and retrieve their data from two popular Google services are Googel + and Gmail through Google APIs.

Create app on the Google Developers Console

  • You access to the Google Developers Console and log in with your Google account.
  • Chose Create Project.
  • Fill the frame PROJECT NAME project name, then click Create .
  • After Google created project will redirect you to the project's Project Dashboard, you choose the Enable an API .
  • Because in this article will limit use Google+ and Gmail API API API should you find 2 on the list and press the OFF to activate them.
  • Next you select Credentials above APIs & auth on the right, then select Create new Client ID
  • Google will ask you to configure consent screen, you just fill out the information request Google, then press Save .
  • In the window Create Client ID , you fill in the details of the application you want to create as below and press the Create Client ID

Create one web app using Ruby on Rails

  • Create 1 new Rails application using the command rails new
rails new googleapirails
  • Add the following gem on Gemfile and run bundle install
gem 'google-api-client', :require => 'google/api_client'
gem 'omniauth'
gem 'omniauth-google-oauth2'

We will use the gem omniauth and omniauth-google-OAuth2 to authenticate users and gem google-api-client to work with Google API.

  • Create New File config/initializers/ominauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
        provider :google_oauth2, CLIENT_ID, CLIENT_SECRET,
        {
            scope: ["plus.login", "plus.me", "userinfo.email", "userinfo.profile", "https://mail.google.com/",
                "gmail.compose", "gmail.modify", "gmail.readonly"],
            access_type: 'offline'
        }
end
  • ** ** CLIENT_ID, CLIENT_SECRET is the client id and client secret that you created in step above
  • scope is the user right that you want for your application. (You can see a list of books that each API should in OAuth 2.0 Playground )
  • access_type: 'offline' : This allows custom applications to access your Google data even if all that is not a Google account to access Google on your browser.
  • Configuration file config/routes.rb Omniauth will automatically give you the path localhost:3000/auth/google_oauth2. When users visit this link, Omniauth will redirect users to Google to verify the account and apply for access. After successful authentication, Google redirects the user back to your web application and enclose access_token. So you need to set the callback URL for your application as under:
resource :sessions
root to: "sessions#new"
match "/auth/:provider/callback", to: "sessions#create", via: :get
  • Create SessionsController in files app/controllers/sessions_controller.rb
class SessionsController < ApplicationController
        def new
        end

        def create
            auth = request.env['omniauth.auth']
        end
end

This is only a temporary one controller, is responsible for reading authentication information that Google returned for your web application. In the information including user access token that you need to manipulate the data of users on Google through Google APIs. Following this article will guide you how to use the Google API.

Using the Google API to retrieve data Google+ and Gmail

  • First you need to read the access token that Google has given you
token = auth['credentials']['token']
  • 1 GoogeAPIClient initialized and set access token
client = Google::APIClient.new
client.authorization.access_token = token
  • Get data from Google+:

Initialize the Google+ APIs

plus = client.discovered_api('plus')
result = client.execute(api_method: plus.people.get, parameters: {userId: 'me'}).data
  • Get data from Gmail: Gmail API initialization
gmail = client.discovered_api('gmail')
result = client.execute(api_method: gmail.users.threads.list, parameters: {userId: 'me'}).data.threads

In the above example we show about how to get data from google plus gmail.... the API method you need to call to retrieve the corresponding information. You can see more about the API methods of the API in the APIs Explorer .


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí