Skip to content

Instantly share code, notes, and snippets.

@andrewhaines
Last active July 6, 2023 08:50
Show Gist options
  • Save andrewhaines/1f976c6007240c4b0f9345ea897f17c0 to your computer and use it in GitHub Desktop.
Save andrewhaines/1f976c6007240c4b0f9345ea897f17c0 to your computer and use it in GitHub Desktop.
Using Google Analytics Reporting API v4 in Rails with Oauth2
# This summary shows how to set up a basic request to Google's Analytics Reporting API v4 from a Rails app.
# Gemfile
gem 'google-api-client', # v. 0.11
gem 'omniauth-google-oauth2' # v. 0.4.1 with Devise
# In a model or controller somewhere...
analytics = Google::Apis::AnalyticsreportingV4::AnalyticsReportingService.new
analytics.authorization = current_user.token # See: https://github.com/zquestz/omniauth-google-oauth2
date_range = Google::Apis::AnalyticsreportingV4::DateRange.new(start_date: '7DaysAgo', end_date: 'today')
metric = Google::Apis::AnalyticsreportingV4::Metric.new(expression: 'ga:sessions', alias: 'sessions')
dimension = Google::Apis::AnalyticsreportingV4::Dimension.new(name: 'ga:browser')
request = Google::Apis::AnalyticsreportingV4::GetReportsRequest.new(
report_requests: [Google::Apis::AnalyticsreportingV4::ReportRequest.new(
view_id: 'VIEW_ID_FROM_ANALYTICS_PROPERTY',
metrics: [metric],
dimensions: [dimension],
date_ranges: [date_range]
)]
) # thanks to @9mm: https://github.com/google/google-api-ruby-client/issues/489
response = analytics.batch_get_reports(request)
response.reports
@chaadow
Copy link

chaadow commented Jan 27, 2019

@maurymmarques you should also require the v3 to look for management info, like listing accounts, properties and views. V4 is solely focused on providing a reporting API for the moment.

@silva96
Copy link

silva96 commented Nov 21, 2019

filters can be simplified like this:

request = Google::Apis::AnalyticsreportingV4::GetReportsRequest.new(
  report_requests: [Google::Apis::AnalyticsreportingV4::ReportRequest.new(
    view_id: view_id,
    metrics: [metric],
    dimensions: [dimension1, dimension2],
    date_ranges: [date_range],
    filters_expression: filters
  )]
)

note filters_expression: filters

Where filters variable is in the form of ga:medium==cpc,ga:medium==organic;ga:source==bing,ga:source==google

Where commas (,) mean OR and simicolons (;) mean AND (where OR takes precedence over AND

you can check the query explorer to play around with filters.

Here is filters documentation

@santucorephp
Copy link

Hi, sir
I'm unable to authorize the reporting API because I have a rake task that everyday runs and collects data but in the rake, task authorization is required without a consent screen and I have not added omniauth gem but with google-api-client gem I have to make request to reporting API. why does authorization fail?

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