Create a gist now

Instantly share code, notes, and snippets.

An example of calling the Analytics API using machine creds and the V4 API from Ruby
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 = ''
@client =
#Using the "Server to Server auth mechanism as documented at
@creds = ServiceAccountCredentials.make_creds({:json_key_io =>'client_secrets.json'),
:scope => SCOPE})
@client.authorization = @creds
grr =
rr =
rr.view_id = VIEW_ID
#put a filter which only returns results for the root page
#We want the number of sessions
metric =
metric.expression = "ga:sessions"
rr.metrics = [metric]
#We want this for the last 7 days
range =
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
gordonjl commented Dec 5, 2016

This gist answered my problems, thanks! Biggest nightmare I was having with this was my request's body was never populated. The kicker for me was that I see you have to use the GetReportsRequest class (?!!!).

Thanks again for this very helpful gist.


Thats Greats.. Thanks.. its solve my probs..


Great gist, thank you!
Maybe adding a little help to create the service account and giving it access to Analytics might be useful. This guy does exactly that:

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