Skip to content

Instantly share code, notes, and snippets.

@carloslopes
Forked from joost/ruby_google_analytics_server_to_server.md
Last active September 3, 2017 09:44
Show Gist options
  • Save carloslopes/6306255 to your computer and use it in GitHub Desktop.
Save carloslopes/6306255 to your computer and use it in GitHub Desktop.
Google Analytics API (server-to-server) using Ruby

There are many (old) clients available:

All are abandoned and you should not use them. The Google Analytics API is at v3 and they are all using an earlier version.

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'
  
  SERVICE_ACCOUNT_EMAIL = 'something_long@developer.gserviceaccount.com'

  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')

  parameters = {
    'accountId': '~all',
    'webPropertyId': '~all'
  }

  result   = client.execute(:api_method => analytics.management.profiles.list, parameters: parameters)
  profiles = result.data.items

  parameters = {
        'ids'         => "ga:#{profiles.first.id}",
        'start-date'  => (Date.today - 30).strftime("%Y-%m-%d"),
        'end-date'    => Date.today.strftime("%Y-%m-%d"),
        'metrics'     => "ga:avgTimeOnPage",
        'filters'     => "ga:pagePath=~/"
      }
  result = client.execute(:api_method => analytics.data.ga.get, :parameters => parameters)
@jojo89
Copy link

jojo89 commented Jan 10, 2014

how do I find an accounts web properties?

@jlfenaux
Copy link

jlfenaux commented Jun 3, 2015

Thanks, I was stuck without you.

@imaginationcoder
Copy link

Thanks, It really helped us.

@arjunmenon
Copy link

You know the latest version of this gem throws up the error on
key = Google::APIClient::PKCS12.load_key(key_file, 'notasecret')
Uninitialized constant Google::APIClient(name error)

What is the new method for loading the P12/JSON file?

@fabdelgado
Copy link

fabdelgado commented Dec 1, 2016

Hi, I get this error when I run.

rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
	from test.rb:1:in `<main>'

My require
require 'google/api_client' require 'date'

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