その他
    ホーム 技術発信 DoRuby Google APIの使い方について

    Google APIの使い方について

    この記事はアピリッツの技術ブログ「DoRuby」から移行した記事です。情報が古い可能性がありますのでご注意ください。

    GoogleのAPIを使用する方法について

     Projectの作成

    Project作成

    Google Developers Console(https://code.google.com/apis/console/)で新しいプロジェクトを作成します。

    APIの有効化

    API一覧から使用するAPIを選択し有効化(statusをEnable)します。

     トークンの取得

    メールアドレス登録

    Credentials(サイドメニュー) → OAuth consent screen(メイン画面タブ) から、Eメールアドレス(Email address)とProduct name shown to users(適当な文字列を入力)を登録します。

    クライアントIDの発行

    Credentials(サイドメニュー) → Credentials(メイン画面タブ)の

    Create credentialsから「OAuth Client ID」を選択後、アプリケーションの種類を選択(Other)してクライアントIDを発行します。

    登録が完了すると、画面にClient ID, Client Secretが表示されます(2016/07現在、Redirect URIsは表示されなくなった: http://localhost)

    Authorization Codeを取得

    ブラウザ上で以下のURLを入力します。リダイレクトURIとクライアントIDは上記で取得したものを入力します。

    https://accounts.google.com/o/oauth2/auth?
    scope=https://www.googleapis.com/auth/androidpublisher
    &response_type=code
    &access_type=offline
    &redirect_uri=<redirect uri>
    &client_id=<client id>
    

    「<product name shown to usersで入力した文字列>が次の許可をリクエストしています」

    と画面に表示されるので、「許可」ボタン(以前は承認するだったので名前は変わる可能性あり)を押下します。

    ボタンを押した後リダイレクト先で、ブラウザのアドレスバーを確認します。

    code=以降にAuthorization Code が入っています。

    http://localhost/?code=<authorizationcode>
    

    アクセストークンの取得

    アクセストークンを取得するために、Authorization Code, Client ID, Client Secret, Redirect URI をPOST でリクエストを送ります。

    curl -v -X POST 'https://accounts.google.com/o/oauth2/token' 
    -d 'grant_type=authorization_code
    &code=< Authorization Code >
    &client_id=< Client ID >
    &client_secret=< Client Secret >
    &redirect_uri=< Redirect URI >'
    

    レスポンスとして、アクセストークンとリフレッシュトークンが帰ってきます。

    {
    "access_token" : " アクセストークン",
    "token_type" : "Bearer",
    "expires_in" : 3600,
    "refresh_token" : "リフレッシュトークン"
    }
    

     サーバ側設定

    Gem

    google API Client のGemを使用

    https://github.com/google/google-api-ruby-client

    使い方

    require 'google/api_client'
    
    # 初期化
    client = Google::APIClient.new(
      auto_refresh_token:  true,
      application_name:    xxx,   # アプリケーション名やバージョン名を
      application_version: xxx    # 指定する場合は初期化時に入力
    )
    
    # 認証情報設定
    client.authorization.client_id      = <取得したクライアントID>
    client.authorization.client_secret  = <取得したクライアントシークレット>
    # リフレッシュトークンにより, アクセストークンは都度取得する
    client.authorization.refresh_token  = <取得したリフレッシュトークン>
    
    # 使用するAPIとバージョンを指定
    api_publisher = client.discovered_api("hogeAPI", "v1.1")
    
    # API呼び出し
    client.authorization.fetch_access_token!
    
    response = client.execute(
      api_method: <api のメソッドを指定>,
      # パラメータを渡す場合はhashで指定
      parameters: {
        "xxx" => xxx,
        "yyy" => xxx,
        "zzz" => xxx
      }
    )
    

    responseにAPIのレスポンスが格納されます。