Last active
July 18, 2023 21:01
-
-
Save CoryFoy/9edf1e039e174c00c209e930a1720ce0 to your computer and use it in GitHub Desktop.
An example of calling the Analytics API using machine creds and the V4 API from Ruby
This file contains 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
require 'google/apis/analyticsreporting_v4' | |
require 'googleauth' | |
include Google::Apis::AnalyticsreportingV4 | |
include Google::Auth | |
VIEW_ID = "12345678" #your profile ID from your Analytics Profile | |
SCOPE = 'https://www.googleapis.com/auth/analytics.readonly' | |
@client = AnalyticsReportingService.new | |
#Using the "Server to Server auth mechanism as documented at | |
#https://developers.google.com/api-client-library/ruby/auth/service-accounts | |
@creds = ServiceAccountCredentials.make_creds({:json_key_io => File.open('client_secrets.json'), | |
:scope => SCOPE}) | |
@client.authorization = @creds | |
grr = GetReportsRequest.new | |
rr = ReportRequest.new | |
rr.view_id = VIEW_ID | |
#put a filter which only returns results for the root page | |
rr.filters_expression="ga:pagePath==/" | |
#We want the number of sessions | |
metric = Metric.new | |
metric.expression = "ga:sessions" | |
rr.metrics = [metric] | |
#We want this for the last 7 days | |
range = DateRange.new | |
range.start_date = "7daysAgo" | |
range.end_date = "today" | |
rr.date_ranges = [range] | |
grr.report_requests = [rr] | |
response = @client.batch_get_reports(grr) | |
puts response.inspect | |
puts response.reports.inspect |
Quick question. Do you add this file into config
folder? Or in the helper
or controller
folder?
Also, is the Profile ID
, as mentioned in the comment section is considered the View ID
in view settings?
Thank you so much for this gist. This should be an example in the official docs, rather than the other confusing mess...
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks @CoryFoy !
@aldrienht when you create the service account at https://console.developers.google.com/iam-admin/serviceaccounts you should be given the option to download the JSON file & it should be in the file. In the file, the type should be service_account, the project_id should be whatever project name you provided it like abc123, and the client_email should be like [email protected]
To satisfy the
forbidden
error, you need to add that service account email to an account or property or view (at https://analytics.google.com/analytics, -> Admin page/gear icon -> User Management -> plus sign + -> Add new users. Needs at least Read & Analyze permissions).