I have been trying to query GA4 for page counts using the code below which I got from this article and linked git. I can get results using the dimension “pagePath” but this only gives me the URL before “?”. I need the full page URL so this isn’t enough. I can get data using the dimension “fullPageUrl” in the GA4 Query Explorer but the API returns no data without errors.
How can I get a count of page views from the ruby GA4 API using the full page URL?
#!/usr/bin/ruby
require 'google/analytics/data'
require './environment' # Replace with the path to your environment file
require 'time'
module GoogleAnalytics
class Report
attr_reader :metrics
attr_reader :property_id
attr_reader :client
def initialize(metrics: nil, property_id: nil, client: nil)
@metrics = metrics
@property_id = property_id || PROPERTY_ID
@client = client || analytics_data_client
end
def get(page_path:, start_date:, end_date:)
request = GoogleAnalytics::ReportRequest.new(
page_path: page_path,
start_date: start_date,
end_date: end_date,
property_id: property_id
).generate
client.run_report(request)
end
private
def analytics_data_client
Google::Analytics::Data.analytics_data do |config|
config.credentials = SERVICE_ACCOUNT_KEY_FILE
end
end
end
require 'google/analytics/data/v1beta'
class ReportRequest
DEFAULT_METRICS = ['screenPageViews'].freeze
BEGINS_WITH_MATCH_TYPE = Google::Analytics::Data::V1beta::Filter::StringFilter::MatchType::BEGINS_WITH
attr_reader :property_id
attr_reader :page_path
attr_reader :start_date
attr_reader :end_date
attr_reader :metrics
def initialize(page_path:, start_date:, end_date:, property_id:)
@page_path = page_path
@start_date = start_date
@end_date = end_date
@property_id = property_id
@metrics = metrics || DEFAULT_METRICS
end
def generate
Google::Analytics::Data::V1beta::RunReportRequest.new(
property: "properties/#{property_id}",
# dimensions: [{ name: 'pagePath' }],
dimensions: [{ name: 'fullPageUrl' }],
dimension_filter: dimension_filter(page_path),
metrics: report_metrics,
date_ranges: [{ start_date: start_date.to_s, end_date: end_date.to_s }],
)
end
private
def report_metrics
metrics.map { |metric| { name: metric } } # DEFAULT_METRICS
end
def dimension_filter(page_path)
{
filter: {
field_name: 'fullPageUrl',
# field_name: 'pagePath',
string_filter: {
match_type: BEGINS_WITH_MATCH_TYPE,
value: page_path,
case_sensitive: false
}
}
}
end
end
end