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 sasharevzin/29ca467a17ea2d872a741f9be8335ca2 to your computer and use it in GitHub Desktop.
Save sasharevzin/29ca467a17ea2d872a741f9be8335ca2 to your computer and use it in GitHub Desktop.
Google Analytics API (server-to-server) using Ruby

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:

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

  require 'google/api_client'
  require 'date'

  client = Google::APIClient.new(:application_name => 'something you like', :application_version => '1')
  key_file = File.join('SOME PATH', 'KEY_FILE')
  key = Google::APIClient::PKCS12.load_key(key_file, 'notasecret')
  service_account = Google::APIClient::JWTAsserter.new(
      SERVICE_ACCOUNT_EMAIL,
      ['https://www.googleapis.com/auth/analytics.readonly', 'https://www.googleapis.com/auth/prediction'],
      key)
  client.authorization = service_account.authorize

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

  result = client.execute(:api_method => analytics.management.accounts.list)
  result.data.items.first.id

  parameters = {
        'ids'         => "ga:SOME_ID",
        'start-date'  => (Date.today - 30).strftime("%Y-%m-%d"),
        'end-date'    => Time.now.strftime("%Y-%m-%d"),
        'metrics'     => "ga:avgTimeOnPage",
        'filters'     => "ga:pagePath=~/"
      }
  result = client.execute(:api_method => analytics.data.ga.get, :parameters => parameters)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment