How to Retrieve Data from Google Analytics (GA4) Using gem google-api-client and Query Explorer with Rails

How to Retrieve Data from Google Analytics (GA4) Using gem google-api-client and Query Explorer with Rails
Learn how to retrieve data from Google Analytics (GA4) in this tutorial. Discover how to use the gem 'google-api-client' to obtain the data and modify the code according to your needs. Follow step-by-step instructions on how to create a JSON file, get the GA4 property ID, test your query using Query Explorer before coding.
Created:

How to Access Google Analytics Data (GA4) in Ruby on Rails?

To retrieve data from Google Analytics, you can utilize the website https://ga-dev-tools.google/ga4/query-explorer/ to execute queries. On this website, you will find a link to the “Google Analytics Data API (GA4) runReport” documentation at https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport. Currently, gem 'google-api-client' does not support POST https://analyticsdata.googleapis.com/v1beta/{property=properties/*}:runReport but only v1alpha. However, I will demonstrate how to obtain Google Analytics Data and still use 'google-api-client'.

In this tutorial, I declare two environment variables in the .env file.
ANALYTICS_DATA_CREDENTIALS="config/vulehuan-ga.json"
GA4_PROPERTY_ID="307325329"

To create the service file, you can use the following code for app/services/my_analytics_data_service.rb:
# frozen_string_literal: true
require 'google/apis/analyticsdata_v1alpha'

class MyAnalyticsDataService < Google::Apis::AnalyticsdataV1alpha::AnalyticsDataService
  def run_report(run_report_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
    command = make_simple_command(:post, "v1beta/properties/#{ENV['GA4_PROPERTY_ID']}:runReport", options)
    command.request_representation = Google::Apis::AnalyticsdataV1alpha::RunReportRequest::Representation
    command.request_object = run_report_request_object
    command.response_representation = Google::Apis::AnalyticsdataV1alpha::RunReportResponse::Representation
    command.response_class = Google::Apis::AnalyticsdataV1alpha::RunReportResponse
    command.query['fields'] = fields unless fields.nil?
    command.query['quotaUser'] = quota_user unless quota_user.nil?
    execute_or_queue_command(command, &block)
  end
end

This file only changes the API path in the run_report function of Google::Apis::AnalyticsdataV1alpha::AnalyticsDataService to v1beta/properties/#{ENV['GA4_PROPERTY_ID']}:runReport.

The sample code below retrieves pageViews within 28 days and saves it to the google_analytic_reports table. Depending on your needs, you can modify the code accordingly. Please test it at https://ga-dev-tools.google/ga4/query-explorer/ before coding. When testing, you will receive values to input in the code, such as metrics screenPageViews, order_bys with type ALPHANUMERIC, and where the dimensions date come from. Simply test on https://ga-dev-tools.google/ga4/query-explorer/, select the appropriate query, see what data is available, and update your code accordingly.

# Set up authentication
scopes = [Google::Apis::AnalyticsdataV1alpha::AUTH_ANALYTICS_READONLY]
credentials = Google::Auth::ServiceAccountCredentials.make_creds(
  json_key_io: File.open("#{Rails.root}/#{ENV['ANALYTICS_DATA_CREDENTIALS']}"),
  scope: scopes
)
client = MyAnalyticsDataService.new
client.authorization = credentials

# Set the date range for the report
end_date = Date.today.prev_day # Set the end date to yesterday
start_date = end_date - 27 # Set the start date to 28 days ago
# Build the request https://ga-dev-tools.google/ga4/query-explorer/ OR https://ga-dev-tools.google/query-explorer/
request = Google::Apis::AnalyticsdataV1alpha::RunReportRequest.new(
  dimensions: [Google::Apis::AnalyticsdataV1alpha::Dimension.new(name: 'date')],
  metrics: [
    Google::Apis::AnalyticsdataV1alpha::Metric.new(
      name: 'screenPageViews',
    )
  ],
  date_ranges: [
    Google::Apis::AnalyticsdataV1alpha::DateRange.new(
      start_date: start_date.strftime('%Y-%m-%d'),
      end_date: end_date.strftime('%Y-%m-%d')
    )
  ],
  order_bys: [
    Google::Apis::AnalyticsdataV1alpha::OrderBy.new(
      dimension: Google::Apis::AnalyticsdataV1alpha::DimensionOrderBy.new(dimension_name: 'date', order_type: 'ALPHANUMERIC'),
      desc: false
    )
  ]
)
response = client.run_report(request)
GoogleAnalyticReport.create(
  response.rows.map do |row|
    date = Date.strptime(row.dimension_values.first.value, '%Y%m%d')
    sessions = row.metric_values.first.value.to_i
    { report_date: date, total_views: sessions }
  end
)

Explain my code and how to use it

In the above code, I use client = MyAnalyticsDataService.new. As previously mentioned, MyAnalyticsDataService overrides the run_report function with the intention of calling POST https://analyticsdata.googleapis.com/v1beta/{property=properties/*}:runReport and receiving the resulting data.

Next, I will provide instructions on how to create the JSON file or obtain the value of the GA4 property ID (the two environment variables mentioned at the beginning of this tutorial).
ANALYTICS_DATA_CREDENTIALS="config/vulehuan-ga.json"
GA4_PROPERTY_ID="307325329"

ANALYTICS_DATA_CREDENTIALS is the path to the JSON file generated from the Google Console. In the code, json_key_io: File.open("#{Rails.root}/#{ENV['ANALYTICS_DATA_CREDENTIALS']}"), I used Rails.root and placed the JSON file in the config folder. You can modify both the environment variable and the code where json_key_io is appropriate.

To create the above JSON file, navigate to https://developers.google.com/analytics/devguides/reporting/data/v1/quickstart-client-libraries and select 'Enable the Google Analytics Data API v1'. Follow the provided steps, and in the resulting dialog, click DOWNLOAD CLIENT CONFIGURATION and save the file credentials.json to your working directory.

Using a text editor, open the credentials.json file you downloaded in the previous step and search for the client_email field to obtain the service account email address. It should look similar to [email protected]. Use this email address to add a user to the Google Analytics 4 property you want to access via the Google Analytics Data API v1. For this tutorial, only Viewer permissions are required.

You can obtain the GA4_PROPERTY_ID same as the screenshot bellow:

Conclusion

In conclusion, retrieving data from Google Analytics can be accomplished using the website https://ga-dev-tools.google/ga4/query-explorer/ to execute queries. Although the gem 'google-api-client' currently only supports v1alpha and not POST https://analyticsdata.googleapis.com/v1beta/{property=properties/*}:runReport, we can still obtain Google Analytics data by overriding the run_report function of Google::Apis::AnalyticsdataV1alpha::AnalyticsDataService to v1beta/properties/#{ENV['GA4_PROPERTY_ID']}:runReport. By declaring environment variables in the .env file and using the provided code, we can retrieve the desired data and save it to our database. To obtain the necessary credentials, follow the steps provided in the tutorial, and test the query on https://ga-dev-tools.google/ga4/query-explorer/ before coding.
 

Greetings! You already read an article titled How to Retrieve Data from Google Analytics (GA4) Using gem google-api-client and Query Explorer with Rails which has been authored by Huan Vu Le. In case you wish to gather more insights about the author, you may consider visiting https://vulehuan.com/en/profile/vulehuan.html.
I'm excited to share that my website is completely free to use, and I'm dedicated to providing helpful resources to my users. If you find my website useful and want to support me, you can now donate. Donations go directly to my bank account and help me continue to provide quality content.
Military Commercial Joint Stock Bank
SWIFT code: MSCBVNVX
Account number: 22-11-1986-68
Account name: VU LE HUAN
Thank you for your support!
You can also contribute to me by signing up for these services:
Please Login to post comment.
Search
Analytics
Resources
BibleCatholic PrayersOur Assessment QuizzesEnglishLearn to code
Tools
Sleepy timePomodoroYoutubeOne Time LinkCompound Interest CalculatorCombinations Calculator (nCr)Contrast checkerChisanbop FingermathGoogle cached page
Huan Vu Le's Blog
IT & Software - Operating Systems & Servers - Software - Other IT & SoftwareProgramming Languages - Ruby on Rails - Other Programming LanguagesSkills - Improve Your Work PerformanceRoman Catholicism
CategoriesLog in