Skip to content

Instantly share code, notes, and snippets.

@andrewhaines
Last active July 6, 2023 08:50
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • 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
@mmotherwell
Copy link

I struggled with Filters, and this is the format I used to get dimension filters working to match search traffic:

https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/reports/batchGet#Operator has more details on the :operator options (defaults to REGEXP and just the first array value for expressions): single array

filters = []
filters << Google::Apis::AnalyticsreportingV4::DimensionFilter.new(dimension_name: 'ga:source', operator: 'IN_LIST', expressions: ['bing', 'google'])
filters << Google::Apis::AnalyticsreportingV4::DimensionFilter.new(dimension_name: 'ga:medium', operator: 'IN_LIST', expressions: ['cpc', 'organic'])

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],
     dimension_filter_clauses: [operator: 'AND', filters: filters]
  )]
)

@maurymmarques
Copy link

maurymmarques commented Sep 20, 2018

Hi,

It will return something like this:

{:reports=>
  [{:column_header=>{:dimensions=>["ga:browser"], :metric_header=>{:metric_header_entries=>[{:type=>"INTEGER", :name=>"sessions"}]}},
    :data=>
     {:row_count=>24,
      :maximums=>[{:values=>["95666"]}],
      :minimums=>[{:values=>["1"]}],
      :rows=>
       [{:dimensions=>["Amazon Silk"], :metrics=>[{:values=>["43"]}]},
        {:dimensions=>["Android Browser"], :metrics=>[{:values=>["4642"]}]},
        {:dimensions=>["Android Webview"], :metrics=>[{:values=>["6372"]}]},
        {:dimensions=>["BlackBerry"], :metrics=>[{:values=>["8"]}]},
        {:dimensions=>["Camino"], :metrics=>[{:values=>["1"]}]},
        {:dimensions=>["Chrome"], :metrics=>[{:values=>["35649"]}]},
        {:dimensions=>["Coc Coc"], :metrics=>[{:values=>["1"]}]},
        {:dimensions=>["DoCoMo"], :metrics=>[{:values=>["42"]}]},
        {:dimensions=>["Edge"], :metrics=>[{:values=>["7255"]}]},
        {:dimensions=>["Firefox"], :metrics=>[{:values=>["1664"]}]},
        {:dimensions=>["IE with Chrome Frame"], :metrics=>[{:values=>["3"]}]},
        {:dimensions=>["Internet Explorer"], :metrics=>[{:values=>["22139"]}]},
        {:dimensions=>["Iron"], :metrics=>[{:values=>["3"]}]},
        {:dimensions=>["Lunascape"], :metrics=>[{:values=>["12"]}]},
        {:dimensions=>["Mozilla"], :metrics=>[{:values=>["1"]}]},
        {:dimensions=>["Mozilla Compatible Agent"], :metrics=>[{:values=>["2"]}]},
        {:dimensions=>["Nintendo Browser"], :metrics=>[{:values=>["11"]}]},
        {:dimensions=>["Opera"], :metrics=>[{:values=>["87"]}]},
        {:dimensions=>["Opera Mini"], :metrics=>[{:values=>["18"]}]},
        {:dimensions=>["Playstation Vita Browser"], :metrics=>[{:values=>["7"]}]},
        {:dimensions=>["Puffin"], :metrics=>[{:values=>["9"]}]},
        {:dimensions=>["Safari"], :metrics=>[{:values=>["95666"]}]},
        {:dimensions=>["Safari (in-app)"], :metrics=>[{:values=>["7624"]}]},
        {:dimensions=>["UC Browser"], :metrics=>[{:values=>["3"]}]}],
      :totals=>[{:values=>["181262"]}]}}]}

How could I get more information like the UA-XXXXXXXX-X?
I was able to get this information with Analytics API V3, but I could not do the same with the V4

Thank you.

@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