There are many (old) clients available:
- https://github.com/tpitale/legato (active, supports API v3)
- https://github.com/activenetwork/gattica
- https://github.com/vigetlabs/garb
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 '[email protected]'.
- 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 [email protected]
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