Skip to content

Instantly share code, notes, and snippets.

@tadyjp
Created November 19, 2014 00:43
Show Gist options
  • Save tadyjp/3c7d0708eeaa30bb99e5 to your computer and use it in GitHub Desktop.
Save tadyjp/3c7d0708eeaa30bb99e5 to your computer and use it in GitHub Desktop.
Google Analytics API by ruby
{
"installed": {
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"client_secret": "xxxxxxxxxxxxx-xxxxxxxxxxxxxxx",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"client_email": "",
"redirect_uris": [
"urn:ietf:wg:oauth:2.0:oob",
"oob"
],
"client_x509_cert_url": "",
"client_id": "xxxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs"
}
}
source "https://rubygems.org"
gem "google-api-client", git: '[email protected]:google/google-api-ruby-client.git'
require 'google/api_client'
require 'google/api_client/client_secrets'
require 'google/api_client/auth/installed_app'
require 'google/api_client/auth/file_storage'
# profile id is not tracking id.
# 'aXXXXXXXwYYYYYYYYpZZZZZZZZ' => 'ZZZZZZZZ' is profile id.
GA_PROFILE_ID = 'xxxxxxxx'
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_secret.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
analytics = client.discovered_api('analytics', 'v3')
p count = client.execute(api_method: analytics.data.ga.get, parameters: {
'ids' => "ga:#{GA_PROFILE_ID}",
'start-date' => '2014-10-01',
'end-date' => '2014-10-31',
'dimensions' => "ga:pageTitle,ga:pagePath",
'metrics' => "ga:visitors,ga:visits,ga:pageviews",
'sort' => "-ga:pageviews"
})
count.data.rows.each do |row|
puts "path:#{row[1]}, count:#{row[2]}"
end
@gbailey4
Copy link

Where do you put the credentials file?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment