Last active
May 1, 2020 02:19
-
-
Save peterclark/df7e68e62cb97385beb46685c66a8606 to your computer and use it in GitHub Desktop.
Authentication with the Ruby Google API Client and Google Analytics API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Friend...this gist just saved my bacon!
Thanks so much for clarifying google-api-client's opaque auth mechanisms.