Search code examples
rubygoogle-analytics-api

How to query google analytics api using the google api ruby gem?


The documentation of the google api ruby client lacks of practical examples, it only documents the classes and methods, so it's very hard to guess how should we use the gem in real life. For example, I'm trying to obtain all purchases from enhanced ecommerce to see where they came from (Acquisition Channel or Channel Grouping), but im only interested on transactions that took 5 sessions to convert the transaction ( our unconvinced clients).


Solution

  • First you will need your analytics view_id, can be obtained in the url at the end, after the letter p

    enter image description here

    Then you need to export the route to the credentials: In your terminal:

    export GOOGLE_APPLICATION_CREDENTIALS = 'folder/yourproject-a91723dsa8974.json'

    For more info about credentials see google-auth-gem documentation

    After setting this, you can query the api like this

    require 'googleauth'
    require 'google/apis/analyticsreporting_v4'
    
    scopes = ['https://www.googleapis.com/auth/analytics']
    date_from = 10.days.ago
    date_to = 2.days.ago
    authorization = Google::Auth.get_application_default(scopes)
    analytics = Google::Apis::AnalyticsreportingV4::AnalyticsReportingService.new
    analytics.authorization = authorization
    view_id = '189761131'
    date_range = Google::Apis::AnalyticsreportingV4::DateRange.new(start_date: date_from.strftime('%Y-%m-%d'), end_date: date_to.strftime('%Y-%m-%d'))
    metric = Google::Apis::AnalyticsreportingV4::Metric.new(expression: 'ga:transactions')
    transaction_id_dimension = Google::Apis::AnalyticsreportingV4::Dimension.new(name: 'ga:transactionID')
    adquisition_dimension = Google::Apis::AnalyticsreportingV4::Dimension.new(name: 'ga:channelGrouping')
    filters = 'ga:sessionsToTransaction==5'
    
    request = Google::Apis::AnalyticsreportingV4::GetReportsRequest.new(
      report_requests: [Google::Apis::AnalyticsreportingV4::ReportRequest.new(
        view_id: view_id,
        metrics: [metric],
        dimensions: [transaction_id_dimension, adquisition_dimension],
        date_ranges: [date_range],
        filters_expression: filters
      )]
    )
    response = analytics.batch_get_reports(request)
    response.reports.first.data.rows.each do |row|
      dimensions = row.dimensions
      puts "TransactionID: #{dimensions[0]} - Channel: #{dimensions[1]}"
    end
    

    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 semicolons (;) mean AND (where OR takes precedence over AND)

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

    Here is filters documentation

    If the report brings more than 1000 rows (default max rows), a next_page_token attribute will appear.

    response.reports.first.next_page_token
    => "1000"
    

    You will have to store that number to use it in the next ReportRequest

    next_request = Google::Apis::AnalyticsreportingV4::GetReportsRequest.new(
      report_requests: [Google::Apis::AnalyticsreportingV4::ReportRequest.new(
        view_id: view_id,
        metrics: [metric],
        dimensions: [transaction_id_dimension, adquisition_dimension],
        date_ranges: [date_range],
        filters_expression: filters,
        page_token: "1000"
      )]
    )
    

    until

    next_response.reports.first.next_page_toke
    => nil
    

    Alternatively you can change the default page size of the report request by adding page_size: 10_000 for example.