Skip to content

Instantly share code, notes, and snippets.

@peterclark
Last active May 1, 2020 02:19
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peterclark/df7e68e62cb97385beb46685c66a8606 to your computer and use it in GitHub Desktop.
Save peterclark/df7e68e62cb97385beb46685c66a8606 to your computer and use it in GitHub Desktop.
Authentication with the Ruby Google API Client and Google Analytics API
# Create credentials json file
# 1. Go to Google API Console
# 2. Create credentials (Service Account Key). Note 'Service account ID'
# 3. Download key as 'google_auth.json'
# 4. Go to Google Analytics -> Admin -> View Settings. Note 'View ID'
# 5. Go to User Management -> Add permissions for: (Service account ID) [Read & Analyze]
# Terminal
export GOOGLE_APPLICATION_CREDENTIALS='config/google_auth.json'
gem install googleauth
gem install google-api-client
# IRB
require 'googleauth'
require 'google/apis/analytics_v3'
scopes = ['https://www.googleapis.com/auth/analytics.readonly']
stats = Google::Apis::AnalyticsV3::AnalyticsService.new
stats.authorization = Google::Auth.get_application_default(scopes)
stats.get_ga_data('ga:XXXXXXXXX', '7daysAgo', 'today', 'ga:pageviews', dimensions: 'ga:city')
# XXXXXXXXX is 'View ID' from step 4
# RAILS (using Figaro for env variables)
# in Gemfile
gem 'google-api-client', '~> 0.9.10', require: ['google/apis/analytics_v3', 'googleauth', 'google/api_client/client_secrets']
# in intializer
scopes = ['https://www.googleapis.com/auth/analytics.readonly']
json = StringIO.new(Figaro.env.google_auth_json)
auth = Google::Auth::ServiceAccountCredentials.make_creds(json_key_io: json, scope: scopes)
stats = Google::Apis::AnalyticsV3::AnalyticsService.new
stats.authorization = auth
stats.get_ga_data('ga:XXXXXXXXX', '7daysAgo', 'today', 'ga:pageviews', dimensions: 'ga:pagePath')
@nodanaonlyzuul
Copy link

Friend...this gist just saved my bacon!
Thanks so much for clarifying google-api-client's opaque auth mechanisms.

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