Skip to content

Instantly share code, notes, and snippets.

@jackkinsella
Last active August 29, 2015 14:01
Show Gist options
  • Save jackkinsella/43691a079f35b94ccdcc to your computer and use it in GitHub Desktop.
Save jackkinsella/43691a079f35b94ccdcc to your computer and use it in GitHub Desktop.
Google Analytics API usage
# Initialize the client & Google+ API
require 'google/api_client'
require "json"
client = Google::APIClient.new
analytics = client.discovered_api("analytics", "v3")
client = Google::APIClient.new
OUTPUT_FILE = "analytics.json"
FILE_WITH_KEY = "client.p12"
FILE_PASSWORD = "notasecret"
GOOGLE_ANALYTICS_SERVICE_ACCOUNT_EMAIL = '{YOUR_NUMBER}@developer.gserviceaccount.com'
key = Google::APIClient::PKCS12.load_key(FILE_WITH_KEY, FILE_PASSWORD)
service_account = Google::APIClient::JWTAsserter.new(
GOOGLE_ANALYTICS_SERVICE_ACCOUNT_EMAIL,
'https://www.googleapis.com/auth/analytics',
key)
client.authorization = service_account.authorize
# Wait for authorization code then exchange for token
client.authorization.code = '....'
client.authorization.fetch_access_token!
result = client.execute(api_method: analytics.data.ga.get, parameters: {
"ids" => "ga:{YOUR_ID}",
"start-date" => "2013-10-03",
"end-date" => "2013-11-03",
"dimensions" => "ga:browser,ga:browserVersion,ga:operatingSystem,ga:operatingSystemVersion",
"metrics" => "ga:visits"
}).body
user_agents = JSON.parse(result)["rows"].reduce({}) do |histogram, (browser, browser_version, os, os_version, combination_count)|
histogram["#{browser}/#{browser_version} (#{os}/#{os_version})"]=combination_count
histogram
end.sort_by do |combination, combination_count|
combination_count.to_i
end.reverse
File.open("user_agents.json", "w") do |f|
f.write(JSON.generate(user_agents))
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment