Accessing the Google Analytics API via Ruby is very easy, if you read the github page of the google-api-ruby-client carefully. Hereby I am presenting you my learnings:

Step by Step

Read https://github.com/google/google-api-ruby-client carefully. Since we are looking to find information on “server to server” interactions, this bit is very important:

For server-to-server interactions, like those between a web application and Google Cloud Storage, Prediction, or BigQuery APIs, use service accounts.

So when creating a new Client ID it is important to check “Service account”. Otherwise it will not genereate a private/public key, and you will not be able to download the .p12 key file.

Creating new Client ID

Configuration of authorization

These are the variables you will need to set: (needs to be updated with your details):

SERVICE_ACCOUNT_EMAIL_ADDRESS = '...'
PATH_TO_KEY_FILE              = '...'
PROFILE                       = '...' 
# your GA profile id, looks like 'ga:12345'

Obviously this is just for demo purposes. If you want to know how to set those properly in production code, follow this guide: http://railsapps.github.io/rails-environment-variables.html

Example of an action

Once we have downloaded the key file and configured our app like above, we move on to an action in our app/controllers/analytics_controller.rb What we are going to get from the api here is the visitor count on a weekly basis.

...

respond_to :json

def visitors

  # 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::KeyUtils.load_from_pkcs12(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'        => PROFILE,
      'start-date' => "28daysAgo",
      'end-date'   => "today",
      'dimensions' => 'ga:week',
      'metrics'    => 'ga:users'
  })

  respond_with result.data.rows
end

...

How to find the Google Analytics Profile-ID

Go to your Google Analytics account, and click on "View Settings":

Google Analytics Account

Then you will see a number below "View ID". That's the number you need.

Google Analytics Account with Profile ID