Created
February 22, 2017 20:55
-
-
Save ewlarson/a2b6aa48d03fca02b5eab418fbb6aca3 to your computer and use it in GitHub Desktop.
Using the google-api-ruby-client gem, here is an example for fetching Google Analytics Reporting API V4 data.
This file contains hidden or 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' | |
analytics = Google::Apis::AnalyticsreportingV4::AnalyticsReportingService.new | |
# Authentication / Authorization | |
# via credentials.json | |
# | |
# File downloaded via Google's API Manager | |
# - Create a Service Account | |
# - Add the service account's email address to your Google Analytics account | |
# - Download and save json credentials locally | |
# | |
credentials = Google::Auth::ServiceAccountCredentials.make_creds(json_key_io: IO.new(IO.sysopen('credentials.json'))) | |
credentials.scope = 'https://www.googleapis.com/auth/analytics.readonly' | |
analytics.authorization = credentials.fetch_access_token!({})["access_token"] | |
request = { | |
report_requests:[ | |
{ | |
metric:[ | |
{ | |
expession: "ga:totalEvents" | |
} | |
], | |
dimensions:[ | |
{ name:"ga:eventCategory" }, | |
{ name: "ga:eventAction" }, | |
{ name:"ga:eventLabel" }, | |
{ name: "ga:deviceCategory" } | |
], | |
dimension_filter_clauses:[ | |
{ | |
operator: "AND", # Default is 'OR' | |
filters: [ | |
{ | |
dimension_name: "ga:eventCategory", | |
operator: "EXACT", | |
expressions: ["Links"] # Filter to Links | |
}, | |
{ | |
dimension_name: "ga:eventLabel", | |
operator: "REGEXP", | |
expressions: ["hostname"] # Filter label values | |
}, | |
] | |
} | |
], | |
date_ranges:[ | |
{ | |
start_date: "2017-01-01", | |
end_date: "2017-01-02" | |
} | |
], | |
view_id:"ga:XXXXXX" # Find your own view | |
}]} | |
results = analytics.batch_get_reports Google::Apis::AnalyticsreportingV4::GetReportsRequest.new(request) | |
pp results |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment