Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peter-leonov/0334e4ba019f8c8a3382 to your computer and use it in GitHub Desktop.
Save peter-leonov/0334e4ba019f8c8a3382 to your computer and use it in GitHub Desktop.

There are many (old) clients available:

The Google Analytics API is at v3 (at time of writing).

This example uses Google's Ruby API client to access Analytics. Use https://github.com/google/google-api-ruby-client (Google supported).

For server-to-server Analytics API:

  • Go to your project at https://code.google.com/apis/console/
  • Enable Analytics under APIs & auth / APIs
  • Create new Client ID as Service Account under APIs & auth / Credentials
  • Download the key p12 file to your project [KEY_FILE]
  • Go to you Analytics account and add the API client email address to your account [SERVICE_ACCOUNT_EMAIL] under Admin. It should be something like 'something-long@developer.gserviceaccount.com'.
  • Find View ID (Profile ID) in admin in Account / Property / View

Now get access to the Analytics API in your Ruby/Rails app:

# you need to set this according to your situation/needs
SERVICE_ACCOUNT_EMAIL_ADDRESS = '...' # looks like 12345@developer.gserviceaccount.com
PATH_TO_KEY_FILE              = '...' # the path to the downloaded .p12 key file
PROFILE                       = '...' # your GA profile id (View ID), looks like 'ga:12345'


require 'google/api_client'

# set up a client instance
client  = Google::APIClient.new

client.authorization = Signet::OAuth2::Client.new(
  :token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
  :audience             => 'https://accounts.google.com/o/oauth2/token',
  :scope                => 'https://www.googleapis.com/auth/analytics.readonly',
  :issuer               => SERVICE_ACCOUNT_EMAIL_ADDRESS,
  :signing_key          => Google::APIClient::PKCS12.load_key(PATH_TO_KEY_FILE, 'notasecret')
).tap { |auth| auth.fetch_access_token! }

api_method = client.discovered_api('analytics','v3').data.ga.get


# make queries
result = client.execute(:api_method => api_method, :parameters => {
  'ids'        => PROILE,
  'start-date' => Date.new(1970,1,1).to_s,
  'end-date'   => Date.today.to_s,
  'dimensions' => 'ga:pagePath',
  'metrics'    => 'ga:pageviews',
  'filters'    => 'ga:pagePath==/url/to/user'
})

puts result.data.rows.inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment