LoginSignup
24
25

More than 5 years have passed since last update.

Google Analytics の Real Time Reporting API を Ruby から使う

Last updated at Posted at 2014-10-11

事前準備

Google Analytics の Real Time Reporting API の利用申請をする

Real Time Reporting API のページに行くと、以下のような申請フォームへのリンクが現れると思います。

Real_Time_Data__get_-_Google_Analytics_—_Google_Developers 3.png

申請してからどれぐらいで使えるようになるのかはちょっと分からず。とりあえず申請だけしておいて、翌日とかに使ってみるといいかも。

Developers Console から Analytics API の利用を許可しておきます。

Google_Developers_Console 2.png

APIs Explorer で試してみる

計測したいビューIDをメモする

Google_Analytics.png

APIs Explorer で試す

Real_Time_Data__get_-_Google_Analytics_—_Google_Developers.png

とりあえず metrics として activeUsers を入れて、現在のリアルタイムのアクティブユーザー数を取得してみます。

OAuth を on にすると以下のフォームが出ます。デフォルトでもいいですし、readonly だけにしてもいいです。

Real_Time_Data__get_-_Google_Analytics_—_Google_Developers 2.png

最後 Execute で実行してみてください。

結果の中に以下のような JSON が含まれていれば成功です。

"totalsForAllResults": {
  "rt:activeUsers": "15" // これがアクティブユーザー数
}

Ruby で取得する

google-api-ruby-client gem を入れる

OAuth 周りのサンプル

Github の README もいいのですが、Google Developers の説明も参考になりました。

今回は Installed application として実施します。

client_secret.json を取得する

Google_Developers_Console.png

OAuth 周りのコード

client_secret.json は作成する Ruby の実行ファイルと同じディレクトリに client_secrets.json にリネームしてから保存しておいてください。

require 'google/api_client'
require 'google/api_client/client_secrets'
require 'google/api_client/auth/installed_app'
require 'google/api_client/auth/file_storage'

CREDENTIAL_STORE_FILE = "#{$0}-oauth2.json"

client = Google::APIClient.new(
  :application_name => 'Example Ruby application',
  :application_version => '1.0.0'
)

file_storage = Google::APIClient::FileStorage.new(CREDENTIAL_STORE_FILE)

if file_storage.authorization.nil?
  # client_secrets.json を読み込む
  client_secrets = Google::APIClient::ClientSecrets.load

  flow = Google::APIClient::InstalledAppFlow.new(
    client_id: client_secrets.client_id,
    client_secret: client_secrets.client_secret,
    scope: [
      'https://www.googleapis.com/auth/analytics.readonly'
    ]
  )

  client.authorization = flow.authorize(file_storage)
else
  client.authorization = file_storage.authorization
end

最初の一回はブラウザが立ち上がり許可を求められますが、2 度目の実行からは認証情報をファイルに保存されているものから復元するのでブラウザは立ち上がりません。

リアルタイムなアクティブユーザー数を取得する

先ほど APIs Explorer で試した通りになります。

analytics = client.discovered_api('analytics', 'v3')

count = client.execute(api_method: analytics.data.realtime.get, parameters: {
  ids: "ga:xxxxx",
  dimensions: 'rt:medium',
  metrics: 'rt:activeUsers'
})

active_users_count = count.data.totals_for_all_results['rt:activeUsers']

例えば ページ毎のユーザー数を取得したければ以下のようになります。

count = client.execute(api_method: analytics.data.realtime.get, parameters: {
  ids: "ga:xxxxx",
  dimensions: 'rt:medium,rt:pagePath',
  metrics: 'rt:activeUsers'
})

count.data.rows.each do |row|
  puts "path:#{row[1]}, count:#{row[2]}"
end

dimensions と metrics のパターンについては以下を見ると一覧できます。

24
25
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
25