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
@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