Create a report Stay organized with collections Save and categorize content based on your preferences.
Page Summary
The Google Analytics Data API v1 allows you to create basic reports similar to the Google Analytics UI using the
runReportmethod.Reports are tables containing dimensions and metrics, which can be filtered and paginated.
To generate a report, you need to specify a property ID and include date ranges, at least one dimension, and at least one metric in your request.
You can use up to nine dimensions to group and filter your data, applying inclusion and exclusion criteria.
Pagination using
limitandoffsetparameters allows retrieving more than the default 10,000 rows, and multiple date ranges can be included for comparison.
This guide explains how to create a basic report for your Analytics data usingthe Google Analytics Data API v1. Reports from the Data API v1 are similar tothe reports you can generate in theReports section of theGoogle AnalyticsUI.
This guide covers core reporting, the general reporting feature of the DataAPI. The Data API v1 also has specializedRealtimereporting andFunnel reporting.
runReport is the recommended methodfor queries, and is used in all examples throughout this guide. Seeadvancedfeatures for an overview of other core reporting methods. Try theQuery Explorer to test yourqueries.
Reports overview
Reports are tables of event data for aGoogle Analytics property. Each report table has thedimensions and metrics requested in your query, with data in individual rows.
Usefilters to return only rows matching a certain condition, andpagination to navigate through results.
Here's a sample report table that shows one dimension (Country) and one metric(activeUsers):
| Country | Active Users |
|---|---|
| Japan | 2541 |
| France | 12 |
Specify a data source
EveryrunReport request requires you to specify aGoogle Analytics propertyID. The Analytics property you specify is used as the dataset forthat query. Here's an example:
POST https://analyticsdata.googleapis.com/v1beta/properties/GA_PROPERTY_ID:runReportThe response from this request includes only data from the Analytics propertyyou specify as theGA_PROPERTY_ID.
If you use theData API client libraries, specify the datasource in theproperty parameter, in the form ofproperties/GA_PROPERTY_ID. See thequick start guide for examples of using theclient libraries.
SeeSend Measurement Protocol events to GoogleAnalytics if youwant to include Measurement Protocol events in your reports.
Generate a report
To generate a report, construct aRunReportRequest object.We recommend starting with the following parameters:
- A valid entry in the
dateRangesfield. - At least one valid entry in the
dimensionsfield. - At least one valid entry in the
metricsfield.
Here's a sample request with the recommended fields:
HTTP
POSThttps://analyticsdata.googleapis.com/v1beta/properties/GA_PROPERTY_ID:runReport{"dateRanges":[{"startDate":"2023-09-01"", "endDate": "2023-09-15" }], "dimensions": [{ "name": "country" }], "metrics": [{ "name": "activeUsers" }] }Java
importcom.google.analytics.data.v1beta.BetaAnalyticsDataClient;importcom.google.analytics.data.v1beta.DateRange;importcom.google.analytics.data.v1beta.Dimension;importcom.google.analytics.data.v1beta.DimensionHeader;importcom.google.analytics.data.v1beta.Metric;importcom.google.analytics.data.v1beta.MetricHeader;importcom.google.analytics.data.v1beta.Row;importcom.google.analytics.data.v1beta.RunReportRequest;importcom.google.analytics.data.v1beta.RunReportResponse;/** * Google Analytics Data API sample application demonstrating the creation of a basic report. * * <p>See * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport * for more information. * * <p>Before you start the application, please review the comments starting with "TODO(developer)" * and update the code to use correct values. * * <p>To run this sample using Maven: * * <pre>{@code * cd google-analytics-data * mvn compile exec:java -Dexec.mainClass="com.google.analytics.data.samples.RunReportSample" * }</pre> */publicclassRunReportSample{publicstaticvoidmain(String...args)throwsException{/** * TODO(developer): Replace this variable with your Google Analytics 4 property ID before * running the sample. */StringpropertyId="YOUR-GA4-PROPERTY-ID";sampleRunReport(propertyId);}// Runs a report of active users grouped by country.staticvoidsampleRunReport(StringpropertyId)throwsException{// Using a default constructor instructs the client to use the credentials// specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.try(BetaAnalyticsDataClientanalyticsData=BetaAnalyticsDataClient.create()){RunReportRequestrequest=RunReportRequest.newBuilder().setProperty("properties/"+propertyId).addDimensions(Dimension.newBuilder().setName("country")).addMetrics(Metric.newBuilder().setName("activeUsers")).addDateRanges(DateRange.newBuilder().setStartDate("2020-09-01").setEndDate("2020-09-15")).build();// Make the request.RunReportResponseresponse=analyticsData.runReport(request);printRunResponseResponse(response);}}// Prints results of a runReport call.staticvoidprintRunResponseResponse(RunReportResponseresponse){System.out.printf("%s rows received%n",response.getRowsList().size());for(DimensionHeaderheader:response.getDimensionHeadersList()){System.out.printf("Dimension header name: %s%n",header.getName());}for(MetricHeaderheader:response.getMetricHeadersList()){System.out.printf("Metric header name: %s (%s)%n",header.getName(),header.getType());}System.out.println("Report result:");for(Rowrow:response.getRowsList()){System.out.printf("%s, %s%n",row.getDimensionValues(0).getValue(),row.getMetricValues(0).getValue());}}}
PHP
use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient;use Google\Analytics\Data\V1beta\DateRange;use Google\Analytics\Data\V1beta\Dimension;use Google\Analytics\Data\V1beta\Metric;use Google\Analytics\Data\V1beta\MetricType;use Google\Analytics\Data\V1beta\RunReportRequest;use Google\Analytics\Data\V1beta\RunReportResponse;/** * @param string $propertyId Your GA-4 Property ID */function run_report(string $propertyId){ // Create an instance of the Google Analytics Data API client library. $client = new BetaAnalyticsDataClient(); // Make an API call. $request = (new RunReportRequest()) ->setProperty('properties/' . $propertyId) ->setDateRanges([ new DateRange([ 'start_date' => '2020-09-01', 'end_date' => '2020-09-15', ]), ]) ->setDimensions([ new Dimension([ 'name' => 'country', ]), ]) ->setMetrics([ new Metric([ 'name' => 'activeUsers', ]), ]); $response = $client->runReport($request); printRunReportResponse($response);}/** * Print results of a runReport call. * @param RunReportResponse $response */function printRunReportResponse(RunReportResponse $response){ printf('%s rows received%s', $response->getRowCount(), PHP_EOL); foreach ($response->getDimensionHeaders() as $dimensionHeader) { printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL); } foreach ($response->getMetricHeaders() as $metricHeader) { printf( 'Metric header name: %s (%s)%s', $metricHeader->getName(), MetricType::name($metricHeader->getType()), PHP_EOL ); } print 'Report result: ' . PHP_EOL; foreach ($response->getRows() as $row) { print $row->getDimensionValues()[0]->getValue() . ' ' . $row->getMetricValues()[0]->getValue() . PHP_EOL; }}
Python
fromgoogle.analytics.data_v1betaimportBetaAnalyticsDataClientfromgoogle.analytics.data_v1beta.typesimport(DateRange,Dimension,Metric,MetricType,RunReportRequest,)defrun_sample():"""Runs the sample."""# TODO(developer): Replace this variable with your Google Analytics 4# property ID before running the sample.property_id="YOUR-GA4-PROPERTY-ID"run_report(property_id)defrun_report(property_id="YOUR-GA4-PROPERTY-ID"):"""Runs a report of active users grouped by country."""client=BetaAnalyticsDataClient()request=RunReportRequest(property=f"properties/{property_id}",dimensions=[Dimension(name="country")],metrics=[Metric(name="activeUsers")],date_ranges=[DateRange(start_date="2020-09-01",end_date="2020-09-15")],)response=client.run_report(request)print_run_report_response(response)defprint_run_report_response(response):"""Prints results of a runReport call."""print(f"{response.row_count} rows received")fordimensionHeaderinresponse.dimension_headers:print(f"Dimension header name:{dimensionHeader.name}")formetricHeaderinresponse.metric_headers:metric_type=MetricType(metricHeader.type_).nameprint(f"Metric header name:{metricHeader.name} ({metric_type})")print("Report result:")forrowIdx,rowinenumerate(response.rows):print(f"\nRow{rowIdx}")fori,dimension_valueinenumerate(row.dimension_values):dimension_name=response.dimension_headers[i].nameprint(f"{dimension_name}:{dimension_value.value}")fori,metric_valueinenumerate(row.metric_values):metric_name=response.metric_headers[i].nameprint(f"{metric_name}:{metric_value.value}")
Node.js
// TODO(developer): Uncomment this variable and replace with your// Google Analytics 4 property ID before running the sample.// propertyId = 'YOUR-GA4-PROPERTY-ID';// Imports the Google Analytics Data API client library.const{BetaAnalyticsDataClient}=require('@google-analytics/data');// Initialize client that will be used to send requests. This client only// needs to be created once, and can be reused for multiple requests.constanalyticsDataClient=newBetaAnalyticsDataClient();// Runs a report of active users grouped by country.asyncfunctionrunReport(){const[response]=awaitanalyticsDataClient.runReport({property:`properties/${propertyId}`,dimensions:[{name:'country',},],metrics:[{name:'activeUsers',},],dateRanges:[{startDate:'2020-09-01',endDate:'2020-09-15',},],});printRunReportResponse(response);}// Prints results of a runReport call.functionprintRunReportResponse(response){console.log(`${response.rowCount} rows received`);response.dimensionHeaders.forEach(dimensionHeader=>{console.log(`Dimension header name:${dimensionHeader.name}`);});response.metricHeaders.forEach(metricHeader=>{console.log(`Metric header name:${metricHeader.name} (${metricHeader.type})`);});console.log('Report result:');response.rows.forEach(row=>{console.log(`${row.dimensionValues[0].value},${row.metricValues[0].value}`);});}runReport();
Query for metrics
Metrics are the quantitative measurements of yourevent data. You must specify at least one metric in yourrunReport requests.
SeeAPI Metrics for a full list of metrics you can query.
Here's a sample request that shows three metrics,grouped by thedimensiondate:
HTTP
POSThttps://analyticsdata.googleapis.com/v1beta/properties/GA_PROPERTY_ID:runReport{"dateRanges":[{"startDate":"7daysAgo","endDate":"yesterday"}],"dimensions":[{"name":"date"}],"metrics":[{"name":"activeUsers"},{"name":"newUsers"},{"name":"totalRevenue"}],}Java
importcom.google.analytics.data.v1beta.BetaAnalyticsDataClient;importcom.google.analytics.data.v1beta.DateRange;importcom.google.analytics.data.v1beta.Dimension;importcom.google.analytics.data.v1beta.Metric;importcom.google.analytics.data.v1beta.RunReportRequest;importcom.google.analytics.data.v1beta.RunReportResponse;/** * Google Analytics Data API sample application demonstrating the creation of a basic report. * * <p>See * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport * for more information. * * <p>Before you start the application, please review the comments starting with "TODO(developer)" * and update the code to use correct values. * * <p>To run this sample using Maven: * * <pre>{@code * cd google-analytics-data * mvn compile exec:java -Dexec.mainClass="com.google.analytics.data.samples.RunReportWithMultipleMetricsSample" * }</pre> */publicclassRunReportWithMultipleMetricsSample{publicstaticvoidmain(String...args)throwsException{// TODO(developer): Replace with your Google Analytics 4 property ID before running the sample.StringpropertyId="YOUR-GA4-PROPERTY-ID";sampleRunReportWithMultipleMetrics(propertyId);}// Runs a report of active users, new users and total revenue grouped by date dimension.staticvoidsampleRunReportWithMultipleMetrics(StringpropertyId)throwsException{// Initialize client that will be used to send requests. This client only needs to be created// once, and can be reused for multiple requests. After completing all of your requests, call// the "close" method on the client to safely clean up any remaining background resources.try(BetaAnalyticsDataClientanalyticsData=BetaAnalyticsDataClient.create()){RunReportRequestrequest=RunReportRequest.newBuilder().setProperty("properties/"+propertyId).addDimensions(Dimension.newBuilder().setName("date")).addMetrics(Metric.newBuilder().setName("activeUsers")).addMetrics(Metric.newBuilder().setName("newUsers")).addMetrics(Metric.newBuilder().setName("totalRevenue")).addDateRanges(DateRange.newBuilder().setStartDate("7daysAgo").setEndDate("today")).build();// Make the request.RunReportResponseresponse=analyticsData.runReport(request);// Prints the response using a method in RunReportSample.javaRunReportSample.printRunResponseResponse(response);}}}
PHP
use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient;use Google\Analytics\Data\V1beta\DateRange;use Google\Analytics\Data\V1beta\Dimension;use Google\Analytics\Data\V1beta\Metric;use Google\Analytics\Data\V1beta\MetricType;use Google\Analytics\Data\V1beta\RunReportRequest;use Google\Analytics\Data\V1beta\RunReportResponse;/** * @param string $propertyID Your GA-4 Property ID * Runs a report of active users grouped by three metrics. */function run_report_with_multiple_metrics(string $propertyId){ // Create an instance of the Google Analytics Data API client library. $client = new BetaAnalyticsDataClient(); // Make an API call. $request = (new RunReportRequest()) ->setProperty('properties/' . $propertyId) ->setDimensions([new Dimension(['name' => 'date'])]) ->setMetrics([ new Metric(['name' => 'activeUsers']), new Metric(['name' => 'newUsers']), new Metric(['name' => 'totalRevenue']) ]) ->setDateRanges([ new DateRange([ 'start_date' => '7daysAgo', 'end_date' => 'today', ]) ]); $response = $client->runReport($request); printRunReportResponseWithMultipleMetrics($response);}/** * Print results of a runReport call. * @param RunReportResponse $response */function printRunReportResponseWithMultipleMetrics(RunReportResponse $response){ printf('%s rows received%s', $response->getRowCount(), PHP_EOL); foreach ($response->getDimensionHeaders() as $dimensionHeader) { printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL); } foreach ($response->getMetricHeaders() as $metricHeader) { printf( 'Metric header name: %s (%s)' . PHP_EOL, $metricHeader->getName(), MetricType::name($metricHeader->getType()) ); } print 'Report result: ' . PHP_EOL; foreach ($response->getRows() as $row) { printf( '%s %s' . PHP_EOL, $row->getDimensionValues()[0]->getValue(), $row->getMetricValues()[0]->getValue() ); }}
Python
fromgoogle.analytics.data_v1betaimportBetaAnalyticsDataClientfromgoogle.analytics.data_v1beta.typesimport(DateRange,Dimension,Metric,RunReportRequest,)fromrun_reportimportprint_run_report_responsedefrun_sample():"""Runs the sample."""# TODO(developer): Replace this variable with your Google Analytics 4# property ID before running the sample.property_id="YOUR-GA4-PROPERTY-ID"run_report_with_multiple_metrics(property_id)defrun_report_with_multiple_metrics(property_id="YOUR-GA4-PROPERTY-ID"):"""Runs a report of active users, new users and total revenue grouped by date dimension."""client=BetaAnalyticsDataClient()# Runs a report of active users grouped by three dimensions.request=RunReportRequest(property=f"properties/{property_id}",dimensions=[Dimension(name="date")],metrics=[Metric(name="activeUsers"),Metric(name="newUsers"),Metric(name="totalRevenue"),],date_ranges=[DateRange(start_date="7daysAgo",end_date="today")],)response=client.run_report(request)print_run_report_response(response)
Node.js
// TODO(developer): Uncomment this variable and replace with your// Google Analytics 4 property ID before running the sample.// propertyId = 'YOUR-GA4-PROPERTY-ID';// Imports the Google Analytics Data API client library.const{BetaAnalyticsDataClient}=require('@google-analytics/data');// Initialize client that will be used to send requests. This client only// needs to be created once, and can be reused for multiple requests.constanalyticsDataClient=newBetaAnalyticsDataClient();// Runs a report of active users grouped by three metrics.asyncfunctionrunReportWithMultipleMetrics(){const[response]=awaitanalyticsDataClient.runReport({property:`properties/${propertyId}`,dimensions:[{name:'date',},],metrics:[{name:'activeUsers',},{name:'newUsers',},{name:'totalRevenue',},],dateRanges:[{startDate:'7daysAgo',endDate:'today',},],});printRunReportResponse(response);}runReportWithMultipleMetrics();// Prints results of a runReport call.functionprintRunReportResponse(response){console.log(`${response.rowCount} rows received`);response.dimensionHeaders.forEach(dimensionHeader=>{console.log(`Dimension header name:${dimensionHeader.name}`);});response.metricHeaders.forEach(metricHeader=>{console.log(`Metric header name:${metricHeader.name} (${metricHeader.type})`);});console.log('Report result:');response.rows.forEach(row=>{console.log(`${row.dimensionValues[0].value},${row.metricValues[0].value}`);});}
Here's a sample response that shows 1135 Active Users, 512 New Users, and73.0841 Total Revenue in your Analytics property's currency on the date20231025 (October 25, 2023).
"rows":[...{"dimensionValues":[{"value":"20231025"}],"metricValues":[{"value":"1135"},{"value":"512"},{"value":"73.0841"}]},...],Read the response
Thereport response contains a header androws of data. The header consists ofDimensionHeaders andMetricHeaders, which list the columns in thereport. Each row consists ofDimensionValues andMetricValues. The order of thecolumns is consistent in the request, header, and rows.
Here's a sample response for the previous sample request:
{"dimensionHeaders":[{"name":"country"}],"metricHeaders":[{"name":"activeUsers","type":"TYPE_INTEGER"}],"rows":[{"dimensionValues":[{"value":"Japan"}],"metricValues":[{"value":"2541"}]},{"dimensionValues":[{"value":"France"}],"metricValues":[{"value":"12"}]}],"metadata":{},"rowCount":2}Group and filter data
Dimensions are qualitative attributes you can useto group and filter your data. For example, thecity dimension indicates thecity, likeParis orNew York, where each event originated. Dimensions areoptional forrunReport requests, and you can use up to nine dimensions perrequest.
See theAPI dimensions for a full list of thedimensions you can use to group and filter your data.
Group
Here's a sample request that groups active users into three dimensions:
HTTP
POSThttps://analyticsdata.googleapis.com/v1beta/properties/GA_PROPERTY_ID:runReport{"dateRanges":[{"startDate":"7daysAgo","endDate":"yesterday"}],"dimensions":[{"name":"country"},{"name":"region"},{"name":"city"}],"metrics":[{"name":"activeUsers"}]}```Java
importcom.google.analytics.data.v1beta.BetaAnalyticsDataClient;importcom.google.analytics.data.v1beta.DateRange;importcom.google.analytics.data.v1beta.Dimension;importcom.google.analytics.data.v1beta.Metric;importcom.google.analytics.data.v1beta.RunReportRequest;importcom.google.analytics.data.v1beta.RunReportResponse;/** * Google Analytics Data API sample application demonstrating the creation of a basic report. * * <p>See * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport * for more information. * * <p>Before you start the application, please review the comments starting with "TODO(developer)" * and update the code to use correct values. * * <p>To run this sample using Maven: * * <pre>{@code * cd google-analytics-data * mvn compile exec:java -Dexec.mainClass="com.google.analytics.data.samples.RunReportWithMultipleDimensionsSample" * }</pre> */publicclassRunReportWithMultipleDimensionsSample{publicstaticvoidmain(String...args)throwsException{// TODO(developer): Replace with your Google Analytics 4 property ID before running the sample.StringpropertyId="YOUR-GA4-PROPERTY-ID";sampleRunReportWithMultipleDimensions(propertyId);}// Runs a report of active users grouped by three dimensions.staticvoidsampleRunReportWithMultipleDimensions(StringpropertyId)throwsException{// Initialize client that will be used to send requests. This client only needs to be created// once, and can be reused for multiple requests. After completing all of your requests, call// the "close" method on the client to safely clean up any remaining background resources.try(BetaAnalyticsDataClientanalyticsData=BetaAnalyticsDataClient.create()){RunReportRequestrequest=RunReportRequest.newBuilder().setProperty("properties/"+propertyId).addDimensions(Dimension.newBuilder().setName("country")).addDimensions(Dimension.newBuilder().setName("region")).addDimensions(Dimension.newBuilder().setName("city")).addMetrics(Metric.newBuilder().setName("activeUsers")).addDateRanges(DateRange.newBuilder().setStartDate("7daysAgo").setEndDate("today")).build();// Make the request.RunReportResponseresponse=analyticsData.runReport(request);// Prints the response using a method in RunReportSample.javaRunReportSample.printRunResponseResponse(response);}}}
PHP
use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient;use Google\Analytics\Data\V1beta\DateRange;use Google\Analytics\Data\V1beta\Dimension;use Google\Analytics\Data\V1beta\Metric;use Google\Analytics\Data\V1beta\MetricType;use Google\Analytics\Data\V1beta\RunReportRequest;use Google\Analytics\Data\V1beta\RunReportResponse;/** * @param string $propertyID Your GA-4 Property ID * Runs a report of active users grouped by three dimensions. */function run_report_with_multiple_dimensions(string $propertyId){ // Create an instance of the Google Analytics Data API client library. $client = new BetaAnalyticsDataClient(); // Make an API call. $request = (new RunReportRequest()) ->setProperty('properties/' . $propertyId) ->setDimensions([ new Dimension(['name' => 'country']), new Dimension(['name' => 'region']), new Dimension(['name' => 'city']), ]) ->setMetrics([new Metric(['name' => 'activeUsers'])]) ->setDateRanges([ new DateRange([ 'start_date' => '7daysAgo', 'end_date' => 'today', ]) ]); $response = $client->runReport($request); printRunReportResponseWithMultipleDimensions($response);}/** * Print results of a runReport call. * @param RunReportResponse $response */function printRunReportResponseWithMultipleDimensions(RunReportResponse $response){ printf('%s rows received%s', $response->getRowCount(), PHP_EOL); foreach ($response->getDimensionHeaders() as $dimensionHeader) { printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL); } foreach ($response->getMetricHeaders() as $metricHeader) { printf( 'Metric header name: %s (%s)' . PHP_EOL, $metricHeader->getName(), MetricType::name($metricHeader->getType()) ); } print 'Report result: ' . PHP_EOL; foreach ($response->getRows() as $row) { printf( '%s %s' . PHP_EOL, $row->getDimensionValues()[0]->getValue(), $row->getMetricValues()[0]->getValue() ); }}
Python
fromgoogle.analytics.data_v1betaimportBetaAnalyticsDataClientfromgoogle.analytics.data_v1beta.typesimport(DateRange,Dimension,Metric,RunReportRequest,)fromrun_reportimportprint_run_report_responsedefrun_sample():"""Runs the sample."""# TODO(developer): Replace this variable with your Google Analytics 4# property ID before running the sample.property_id="YOUR-GA4-PROPERTY-ID"run_report_with_multiple_dimensions(property_id)defrun_report_with_multiple_dimensions(property_id="YOUR-GA4-PROPERTY-ID"):"""Runs a report of active users grouped by three dimensions."""client=BetaAnalyticsDataClient()request=RunReportRequest(property=f"properties/{property_id}",dimensions=[Dimension(name="country"),Dimension(name="region"),Dimension(name="city"),],metrics=[Metric(name="activeUsers")],date_ranges=[DateRange(start_date="7daysAgo",end_date="today")],)response=client.run_report(request)print_run_report_response(response)
Node.js
// TODO(developer): Uncomment this variable and replace with your// Google Analytics 4 property ID before running the sample.// propertyId = 'YOUR-GA4-PROPERTY-ID';// Imports the Google Analytics Data API client library.const{BetaAnalyticsDataClient}=require('@google-analytics/data');// Initialize client that will be used to send requests. This client only// needs to be created once, and can be reused for multiple requests.constanalyticsDataClient=newBetaAnalyticsDataClient();// Runs a report of active users grouped by three dimensions.asyncfunctionrunReportWithMultipleDimensions(){const[response]=awaitanalyticsDataClient.runReport({property:`properties/${propertyId}`,dimensions:[{name:'country',},{name:'region',},{name:'city',},],metrics:[{name:'activeUsers',},],dateRanges:[{startDate:'7daysAgo',endDate:'today',},],});printRunReportResponse(response);}runReportWithMultipleDimensions();// Prints results of a runReport call.functionprintRunReportResponse(response){console.log(`${response.rowCount} rows received`);response.dimensionHeaders.forEach(dimensionHeader=>{console.log(`Dimension header name:${dimensionHeader.name}`);});response.metricHeaders.forEach(metricHeader=>{console.log(`Metric header name:${metricHeader.name} (${metricHeader.type})`);});console.log('Report result:');response.rows.forEach(row=>{console.log(`${row.dimensionValues[0].value},${row.metricValues[0].value}`);});}
Here's a sample report row for the previous request. This row shows that therewere 47 active users during the specified date range with events from Cape Town,South Africa.
"rows":[...{"dimensionValues":[{"value":"South Africa"},{"value":"Western Cape"},{"value":"Cape Town"}],"metricValues":[{"value":"47"}]},...],Filter
You generate reports with data for only specific dimension values. To filterdimensions, specify aFilterExpressionin thedimensionFilterfield.
Here's an example that returns a time series report ofeventCount, wheneventName isfirst_open for eachdate :
HTTP
POSThttps://analyticsdata.googleapis.com/v1beta/properties/GA_PROPERTY_ID:runReport{"dateRanges":[{"startDate":"7daysAgo","endDate":"yesterday"}],"dimensions":[{"name":"date"}],"metrics":[{"name":"eventCount"}],"dimensionFilter":{"filter":{"fieldName":"eventName","stringFilter":{"value":"first_open"}}},}Java
importcom.google.analytics.data.v1beta.BetaAnalyticsDataClient;importcom.google.analytics.data.v1beta.DateRange;importcom.google.analytics.data.v1beta.Dimension;importcom.google.analytics.data.v1beta.Filter;importcom.google.analytics.data.v1beta.FilterExpression;importcom.google.analytics.data.v1beta.Metric;importcom.google.analytics.data.v1beta.RunReportRequest;importcom.google.analytics.data.v1beta.RunReportResponse;/** * Google Analytics Data API sample application demonstrating the usage of dimension and metric * filters in a report. * * <p>See * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.dimension_filter * for more information. * * <p>Before you start the application, please review the comments starting with "TODO(developer)" * and update the code to use correct values. * * <p>To run this sample using Maven: * * <pre>{@code * cd google-analytics-data * mvn compile exec:java -Dexec.mainClass="com.google.analytics.data.samples.RunReportWithDimensionFilterSample" * }</pre> */publicclassRunReportWithDimensionFilterSample{publicstaticvoidmain(String...args)throwsException{// TODO(developer): Replace with your Google Analytics 4 property ID before running the sample.StringpropertyId="YOUR-GA4-PROPERTY-ID";sampleRunReportWithDimensionFilter(propertyId);}// Runs a report using a dimension filter. The call returns a time series report of `eventCount`// when `eventName` is `first_open` for each date.// This sample uses relative date range values.// See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange// for more information.staticvoidsampleRunReportWithDimensionFilter(StringpropertyId)throwsException{// Initialize client that will be used to send requests. This client only needs to be created// once, and can be reused for multiple requests. After completing all of your requests, call// the "close" method on the client to safely clean up any remaining background resources.try(BetaAnalyticsDataClientanalyticsData=BetaAnalyticsDataClient.create()){RunReportRequestrequest=RunReportRequest.newBuilder().setProperty("properties/"+propertyId).addDimensions(Dimension.newBuilder().setName("date")).addMetrics(Metric.newBuilder().setName("eventCount")).addDateRanges(DateRange.newBuilder().setStartDate("7daysAgo").setEndDate("yesterday")).setDimensionFilter(FilterExpression.newBuilder().setFilter(Filter.newBuilder().setFieldName("eventName").setStringFilter(Filter.StringFilter.newBuilder().setValue("first_open")))).build();// Make the request.RunReportResponseresponse=analyticsData.runReport(request);// Prints the response using a method in RunReportSample.javaRunReportSample.printRunResponseResponse(response);}}}
PHP
use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient;use Google\Analytics\Data\V1beta\DateRange;use Google\Analytics\Data\V1beta\Dimension;use Google\Analytics\Data\V1beta\Filter;use Google\Analytics\Data\V1beta\Filter\StringFilter;use Google\Analytics\Data\V1beta\FilterExpression;use Google\Analytics\Data\V1beta\Metric;use Google\Analytics\Data\V1beta\MetricType;use Google\Analytics\Data\V1beta\RunReportRequest;use Google\Analytics\Data\V1beta\RunReportResponse;/** * @param string $propertyId Your GA-4 Property ID * Runs a report using a dimension filter. The call returns a time series * report of `eventCount` when `eventName` is `first_open` for each date. * This sample uses relative date range values. See * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange * for more information. */function run_report_with_dimension_filter(string $propertyId){ // Create an instance of the Google Analytics Data API client library. $client = new BetaAnalyticsDataClient(); // Make an API call. $request = (new RunReportRequest()) ->setProperty('properties/' . $propertyId) ->setDimensions([new Dimension(['name' => 'date'])]) ->setMetrics([new Metric(['name' => 'eventCount'])]) ->setDateRanges([ new DateRange([ 'start_date' => '7daysAgo', 'end_date' => 'yesterday', ]) ]) ->setDimensionFilter(new FilterExpression([ 'filter' => new Filter([ 'field_name' => 'eventName', 'string_filter' => new StringFilter([ 'value' => 'first_open' ]), ]), ])); $response = $client->runReport($request); printRunReportResponseWithDimensionFilter($response);}/** * Print results of a runReport call. * @param RunReportResponse $response */function printRunReportResponseWithDimensionFilter(RunReportResponse $response){ printf('%s rows received%s', $response->getRowCount(), PHP_EOL); foreach ($response->getDimensionHeaders() as $dimensionHeader) { printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL); } foreach ($response->getMetricHeaders() as $metricHeader) { printf( 'Metric header name: %s (%s)' . PHP_EOL, $metricHeader->getName(), MetricType::name($metricHeader->getType()) ); } print 'Report result: ' . PHP_EOL; foreach ($response->getRows() as $row) { printf( '%s %s' . PHP_EOL, $row->getDimensionValues()[0]->getValue(), $row->getMetricValues()[0]->getValue() ); }}
Python
fromgoogle.analytics.data_v1betaimportBetaAnalyticsDataClientfromgoogle.analytics.data_v1beta.typesimport(DateRange,Dimension,Filter,FilterExpression,Metric,RunReportRequest,)fromrun_reportimportprint_run_report_responsedefrun_sample():"""Runs the sample."""# TODO(developer): Replace this variable with your Google Analytics 4# property ID before running the sample.property_id="YOUR-GA4-PROPERTY-ID"run_report_with_dimension_filter(property_id)defrun_report_with_dimension_filter(property_id="YOUR-GA4-PROPERTY-ID"):"""Runs a report using a dimension filter. The call returns a time series report of `eventCount` when `eventName` is `first_open` for each date. This sample uses relative date range values. See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange for more information. """client=BetaAnalyticsDataClient()request=RunReportRequest(property=f"properties/{property_id}",dimensions=[Dimension(name="date")],metrics=[Metric(name="eventCount")],date_ranges=[DateRange(start_date="7daysAgo",end_date="yesterday")],dimension_filter=FilterExpression(filter=Filter(field_name="eventName",string_filter=Filter.StringFilter(value="first_open"),)),)response=client.run_report(request)print_run_report_response(response)
Node.js
// TODO(developer): Uncomment this variable and replace with your// Google Analytics 4 property ID before running the sample.// propertyId = 'YOUR-GA4-PROPERTY-ID';// Imports the Google Analytics Data API client library.const{BetaAnalyticsDataClient}=require('@google-analytics/data');// Initialize client that will be used to send requests. This client only// needs to be created once, and can be reused for multiple requests.constanalyticsDataClient=newBetaAnalyticsDataClient();// Runs a report using a dimension filter. The call returns a time series// report of `eventCount` when `eventName` is `first_open` for each date.// This sample uses relative date range values. See// https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange// for more information.asyncfunctionrunReportWithDimensionFilter(){const[response]=awaitanalyticsDataClient.runReport({property:`properties/${propertyId}`,dimensions:[{name:'date',},],metrics:[{name:'eventCount',},],dateRanges:[{startDate:'7daysAgo',endDate:'yesterday',},],dimensionFilter:{filter:{fieldName:'eventName',stringFilter:{value:'first_open',},},},});printRunReportResponse(response);}runReportWithDimensionFilter();// Prints results of a runReport call.functionprintRunReportResponse(response){console.log(`${response.rowCount} rows received`);response.dimensionHeaders.forEach(dimensionHeader=>{console.log(`Dimension header name:${dimensionHeader.name}`);});response.metricHeaders.forEach(metricHeader=>{console.log(`Metric header name:${metricHeader.name} (${metricHeader.type})`);});console.log('Report result:');response.rows.forEach(row=>{console.log(`${row.dimensionValues[0].value},${row.metricValues[0].value}`);});}
Here's anotherFilterExpression example,whereandGroup includes only data that meets all criteria in the expressionslist. ThisdimensionFilter selects for when bothbrowser isChrome andcountryId isUS:
HTTP
..."dimensionFilter":{"andGroup":{"expressions":[{"filter":{"fieldName":"browser","stringFilter":{"value":"Chrome"}}},{"filter":{"fieldName":"countryId","stringFilter":{"value":"US"}}}]}},...Java
importcom.google.analytics.data.v1beta.BetaAnalyticsDataClient;importcom.google.analytics.data.v1beta.DateRange;importcom.google.analytics.data.v1beta.Dimension;importcom.google.analytics.data.v1beta.Filter;importcom.google.analytics.data.v1beta.FilterExpression;importcom.google.analytics.data.v1beta.FilterExpressionList;importcom.google.analytics.data.v1beta.Metric;importcom.google.analytics.data.v1beta.RunReportRequest;importcom.google.analytics.data.v1beta.RunReportResponse;/** * Google Analytics Data API sample application demonstrating the usage of dimension and metric * filters in a report. * * <p>See * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.dimension_filter * for more information. * * <p>Before you start the application, please review the comments starting with "TODO(developer)" * and update the code to use correct values. * * <p>To run this sample using Maven: * * <pre>{@code * cd google-analytics-data * mvn compile exec:java -Dexec.mainClass="com.google.analytics.data.samples.RunReportWithMultipleDimensionFiltersSample" * }</pre> */publicclassRunReportWithMultipleDimensionFiltersSample{publicstaticvoidmain(String...args)throwsException{// TODO(developer): Replace with your Google Analytics 4 property ID before running the sample.StringpropertyId="YOUR-GA4-PROPERTY-ID";sampleRunReportWithMultipleDimensionFilters(propertyId);}// Runs a report using multiple dimension filters joined as `and_group` expression. The filter// selects for when both `browser` is `Chrome` and `countryId` is `US`.// This sample uses relative date range values.// See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange// for more information.staticvoidsampleRunReportWithMultipleDimensionFilters(StringpropertyId)throwsException{// Initialize client that will be used to send requests. This client only needs to be created// once, and can be reused for multiple requests. After completing all of your requests, call// the "close" method on the client to safely clean up any remaining background resources.try(BetaAnalyticsDataClientanalyticsData=BetaAnalyticsDataClient.create()){RunReportRequestrequest=RunReportRequest.newBuilder().setProperty("properties/"+propertyId).addDimensions(Dimension.newBuilder().setName("browser")).addMetrics(Metric.newBuilder().setName("activeUsers")).addDateRanges(DateRange.newBuilder().setStartDate("7daysAgo").setEndDate("yesterday")).setDimensionFilter(FilterExpression.newBuilder().setAndGroup(FilterExpressionList.newBuilder().addExpressions(FilterExpression.newBuilder().setFilter(Filter.newBuilder().setFieldName("browser").setStringFilter(Filter.StringFilter.newBuilder().setValue("Chrome")))).addExpressions(FilterExpression.newBuilder().setFilter(Filter.newBuilder().setFieldName("countryId").setStringFilter(Filter.StringFilter.newBuilder().setValue("US")))))).build();// Make the request.RunReportResponseresponse=analyticsData.runReport(request);// Prints the response using a method in RunReportSample.javaRunReportSample.printRunResponseResponse(response);}}}
PHP
use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient;use Google\Analytics\Data\V1beta\DateRange;use Google\Analytics\Data\V1beta\Dimension;use Google\Analytics\Data\V1beta\Filter;use Google\Analytics\Data\V1beta\Filter\StringFilter;use Google\Analytics\Data\V1beta\FilterExpression;use Google\Analytics\Data\V1beta\FilterExpressionList;use Google\Analytics\Data\V1beta\Metric;use Google\Analytics\Data\V1beta\MetricType;use Google\Analytics\Data\V1beta\RunReportRequest;use Google\Analytics\Data\V1beta\RunReportResponse;/** * @param string $propertyId Your GA-4 Property ID * Runs a report using multiple dimension filters joined as `and_group` * expression. The filter selects for when both `browser` is `Chrome` and * `countryId` is `US`. * This sample uses relative date range values. See * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange * for more information. */function run_report_with_multiple_dimension_filters(string $propertyId){ // Create an instance of the Google Analytics Data API client library. $client = new BetaAnalyticsDataClient(); // Make an API call. $request = (new RunReportRequest()) ->setProperty('properties/' . $propertyId) ->setDimensions([new Dimension(['name' => 'browser'])]) ->setMetrics([new Metric(['name' => 'activeUsers'])]) ->setDateRanges([ new DateRange([ 'start_date' => '7daysAgo', 'end_date' => 'yesterday', ]), ]) ->setDimensionFilter(new FilterExpression([ 'and_group' => new FilterExpressionList([ 'expressions' => [ new FilterExpression([ 'filter' => new Filter([ 'field_name' => 'browser', 'string_filter' => new StringFilter([ 'value' => 'Chrome', ]) ]), ]), new FilterExpression([ 'filter' => new Filter([ 'field_name' => 'countryId', 'string_filter' => new StringFilter([ 'value' => 'US', ]) ]), ]), ], ]), ])); $response = $client->runReport($request); printRunReportResponseWithMultipleDimensionFilters($response);}/** * Print results of a runReport call. * @param RunReportResponse $response */function printRunReportResponseWithMultipleDimensionFilters(RunReportResponse $response){ printf('%s rows received%s', $response->getRowCount(), PHP_EOL); foreach ($response->getDimensionHeaders() as $dimensionHeader) { printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL); } foreach ($response->getMetricHeaders() as $metricHeader) { printf( 'Metric header name: %s (%s)' . PHP_EOL, $metricHeader->getName(), MetricType::name($metricHeader->getType()) ); } print 'Report result: ' . PHP_EOL; foreach ($response->getRows() as $row) { printf( '%s %s' . PHP_EOL, $row->getDimensionValues()[0]->getValue(), $row->getMetricValues()[0]->getValue() ); }}
Python
fromgoogle.analytics.data_v1betaimportBetaAnalyticsDataClientfromgoogle.analytics.data_v1beta.typesimport(DateRange,Dimension,Filter,FilterExpression,FilterExpressionList,Metric,RunReportRequest,)fromrun_reportimportprint_run_report_responsedefrun_sample():"""Runs the sample."""# TODO(developer): Replace this variable with your Google Analytics 4# property ID before running the sample.property_id="YOUR-GA4-PROPERTY-ID"run_report_with_multiple_dimension_filters(property_id)defrun_report_with_multiple_dimension_filters(property_id="YOUR-GA4-PROPERTY-ID"):"""Runs a report using multiple dimension filters joined as `and_group` expression. The filter selects for when both `browser` is `Chrome` and `countryId` is `US`. This sample uses relative date range values. See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange for more information. """client=BetaAnalyticsDataClient()request=RunReportRequest(property=f"properties/{property_id}",dimensions=[Dimension(name="browser")],metrics=[Metric(name="activeUsers")],date_ranges=[DateRange(start_date="7daysAgo",end_date="yesterday")],dimension_filter=FilterExpression(and_group=FilterExpressionList(expressions=[FilterExpression(filter=Filter(field_name="browser",string_filter=Filter.StringFilter(value="Chrome"),)),FilterExpression(filter=Filter(field_name="countryId",string_filter=Filter.StringFilter(value="US"),)),])),)response=client.run_report(request)print_run_report_response(response)
Node.js
// TODO(developer): Uncomment this variable and replace with your// Google Analytics 4 property ID before running the sample.// propertyId = 'YOUR-GA4-PROPERTY-ID';// Imports the Google Analytics Data API client library.const{BetaAnalyticsDataClient}=require('@google-analytics/data');// Initialize client that will be used to send requests. This client only// needs to be created once, and can be reused for multiple requests.constanalyticsDataClient=newBetaAnalyticsDataClient();// Runs a report using multiple dimension filters joined as `and_group`// expression. The filter selects for when both `browser` is `Chrome` and// `countryId` is `US`.// This sample uses relative date range values. See// https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange// for more information.asyncfunctionrunReportWithMultipleDimensionFilters(){const[response]=awaitanalyticsDataClient.runReport({property:`properties/${propertyId}`,dimensions:[{name:'browser',},],metrics:[{name:'activeUsers',},],dateRanges:[{startDate:'7daysAgo',endDate:'yesterday',},],dimensionFilter:{andGroup:{expressions:[{filter:{fieldName:'browser',stringFilter:{value:'Chrome',},},},{filter:{fieldName:'countryId',stringFilter:{value:'US',},},},],},},});printRunReportResponse(response);}runReportWithMultipleDimensionFilters();// Prints results of a runReport call.functionprintRunReportResponse(response){console.log(`${response.rowCount} rows received`);response.dimensionHeaders.forEach(dimensionHeader=>{console.log(`Dimension header name:${dimensionHeader.name}`);});response.metricHeaders.forEach(metricHeader=>{console.log(`Metric header name:${metricHeader.name} (${metricHeader.type})`);});console.log('Report result:');response.rows.forEach(row=>{console.log(`${row.dimensionValues[0].value},${row.metricValues[0].value}`);});}
AnorGroup includes data that meets any of the criteria in the expressionslist.
AnotExpression excludes data that matches its inner expression. Here's adimensionFilter that returns data for only when thepageTitle isn'tMyHomepage. The report shows event data for everypageTitle other thanMyHomepage:
HTTP
..."dimensionFilter": { "notExpression": { "filter": { "fieldName": "pageTitle", "stringFilter": { "value": "My Homepage" } } }},...Java
importcom.google.analytics.data.v1beta.BetaAnalyticsDataClient;importcom.google.analytics.data.v1beta.DateRange;importcom.google.analytics.data.v1beta.Dimension;importcom.google.analytics.data.v1beta.Filter;importcom.google.analytics.data.v1beta.FilterExpression;importcom.google.analytics.data.v1beta.Metric;importcom.google.analytics.data.v1beta.RunReportRequest;importcom.google.analytics.data.v1beta.RunReportResponse;/** * Google Analytics Data API sample application demonstrating the usage of dimension and metric * filters in a report. * * <p>See * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.dimension_filter * for more information. * * <p>Before you start the application, please review the comments starting with "TODO(developer)" * and update the code to use correct values. * * <p>To run this sample using Maven: * * <pre>{@code * cd google-analytics-data * mvn compile exec:java -Dexec.mainClass="com.google.analytics.data.samples.RunReportWithDimensionExcludeFilterSample" * }</pre> */publicclassRunReportWithDimensionExcludeFilterSample{publicstaticvoidmain(String...args)throwsException{// TODO(developer): Replace with your Google Analytics 4 property ID before running the sample.StringpropertyId="YOUR-GA4-PROPERTY-ID";sampleRunReportWithDimensionExcludeFilter(propertyId);}// Runs a report using a filter with `not_expression`. The dimension filter selects for when// `pageTitle` is not `My Homepage`.// This sample uses relative date range values.// See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange// for more information.staticvoidsampleRunReportWithDimensionExcludeFilter(StringpropertyId)throwsException{// Initialize client that will be used to send requests. This client only needs to be created// once, and can be reused for multiple requests. After completing all of your requests, call// the "close" method on the client to safely clean up any remaining background resources.try(BetaAnalyticsDataClientanalyticsData=BetaAnalyticsDataClient.create()){RunReportRequestrequest=RunReportRequest.newBuilder().setProperty("properties/"+propertyId).addDimensions(Dimension.newBuilder().setName("pageTitle")).addMetrics(Metric.newBuilder().setName("sessions")).addDateRanges(DateRange.newBuilder().setStartDate("7daysAgo").setEndDate("yesterday")).setDimensionFilter(FilterExpression.newBuilder().setNotExpression(FilterExpression.newBuilder().setFilter(Filter.newBuilder().setFieldName("pageTitle").setStringFilter(Filter.StringFilter.newBuilder().setValue("My Homepage"))))).build();// Make the request.RunReportResponseresponse=analyticsData.runReport(request);// Prints the response using a method in RunReportSample.javaRunReportSample.printRunResponseResponse(response);}}}
PHP
use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient;use Google\Analytics\Data\V1beta\DateRange;use Google\Analytics\Data\V1beta\Dimension;use Google\Analytics\Data\V1beta\Filter;use Google\Analytics\Data\V1beta\Filter\StringFilter;use Google\Analytics\Data\V1beta\FilterExpression;use Google\Analytics\Data\V1beta\Metric;use Google\Analytics\Data\V1beta\MetricType;use Google\Analytics\Data\V1beta\RunReportRequest;use Google\Analytics\Data\V1beta\RunReportResponse;/** * Runs a report using a filter with `not_expression`. The dimension filter * selects for when `pageTitle` is not `My Homepage`. * This sample uses relative date range values. See * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange * for more information. * @param string $propertyId Your GA-4 Property ID */function run_report_with_dimension_exclude_filter(string $propertyId){ // Create an instance of the Google Analytics Data API client library. $client = new BetaAnalyticsDataClient(); // Make an API call. $request = (new RunReportRequest()) ->setProperty('properties/' . $propertyId) ->setDimensions([new Dimension(['name' => 'pageTitle'])]) ->setMetrics([new Metric(['name' => 'sessions'])]) ->setDateRanges([new DateRange([ 'start_date' => '7daysAgo', 'end_date' => 'yesterday', ]) ]) ->setDimensionFilter(new FilterExpression([ 'not_expression' => new FilterExpression([ 'filter' => new Filter([ 'field_name' => 'pageTitle', 'string_filter' => new StringFilter([ 'value' => 'My Homepage', ]), ]), ]), ])); $response = $client->runReport($request); printRunReportResponseWithDimensionExcludeFilter($response);}/** * Print results of a runReport call. * @param RunReportResponse $response */function printRunReportResponseWithDimensionExcludeFilter(RunReportResponse $response){ printf('%s rows received%s', $response->getRowCount(), PHP_EOL); foreach ($response->getDimensionHeaders() as $dimensionHeader) { printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL); } foreach ($response->getMetricHeaders() as $metricHeader) { printf( 'Metric header name: %s (%s)' . PHP_EOL, $metricHeader->getName(), MetricType::name($metricHeader->getType()) ); } print 'Report result: ' . PHP_EOL; foreach ($response->getRows() as $row) { printf( '%s %s' . PHP_EOL, $row->getDimensionValues()[0]->getValue(), $row->getMetricValues()[0]->getValue() ); }}
Python
fromgoogle.analytics.data_v1betaimportBetaAnalyticsDataClientfromgoogle.analytics.data_v1beta.typesimport(DateRange,Dimension,Filter,FilterExpression,Metric,RunReportRequest,)fromrun_reportimportprint_run_report_responsedefrun_sample():"""Runs the sample."""# TODO(developer): Replace this variable with your Google Analytics 4# property ID before running the sample.property_id="YOUR-GA4-PROPERTY-ID"run_report_with_dimension_exclude_filter(property_id)defrun_report_with_dimension_exclude_filter(property_id="YOUR-GA4-PROPERTY-ID"):"""Runs a report using a filter with `not_expression`. The dimension filter selects for when `pageTitle` is not `My Homepage`. This sample uses relative date range values. See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange for more information. """client=BetaAnalyticsDataClient()request=RunReportRequest(property=f"properties/{property_id}",dimensions=[Dimension(name="pageTitle")],metrics=[Metric(name="sessions")],date_ranges=[DateRange(start_date="7daysAgo",end_date="yesterday")],dimension_filter=FilterExpression(not_expression=FilterExpression(filter=Filter(field_name="pageTitle",string_filter=Filter.StringFilter(value="My Homepage"),))),)response=client.run_report(request)print_run_report_response(response)
Node.js
// TODO(developer): Uncomment this variable and replace with your// Google Analytics 4 property ID before running the sample.// propertyId = 'YOUR-GA4-PROPERTY-ID';// Imports the Google Analytics Data API client library.const{BetaAnalyticsDataClient}=require('@google-analytics/data');// Initialize client that will be used to send requests. This client only// needs to be created once, and can be reused for multiple requests.constanalyticsDataClient=newBetaAnalyticsDataClient();// Runs a report using a filter with `not_expression`. The dimension filter// selects for when `pageTitle` is not `My Homepage`.// This sample uses relative date range values. See// https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange// for more information.asyncfunctionrunReportWithDimensionExcludeFilter(){const[response]=awaitanalyticsDataClient.runReport({property:`properties/${propertyId}`,dimensions:[{name:'pageTitle',},],metrics:[{name:'sessions',},],dateRanges:[{startDate:'7daysAgo',endDate:'yesterday',},],dimensionFilter:{notExpression:{filter:{fieldName:'pageTitle',stringFilter:{value:'My Homepage',},},},},});printRunReportResponse(response);}runReportWithDimensionExcludeFilter();// Prints results of a runReport call.functionprintRunReportResponse(response){console.log(`${response.rowCount} rows received`);response.dimensionHeaders.forEach(dimensionHeader=>{console.log(`Dimension header name:${dimensionHeader.name}`);});response.metricHeaders.forEach(metricHeader=>{console.log(`Metric header name:${metricHeader.name} (${metricHeader.type})`);});console.log('Report result:');response.rows.forEach(row=>{console.log(`${row.dimensionValues[0].value},${row.metricValues[0].value}`);});}
AninListFilter matches data for any of the values in the list. Here's adimensionFilter that returns event data whereeventName is any ofpurchase,in_app_purchase, andapp_store_subscription_renew:
HTTP
..."dimensionFilter":{"filter":{"fieldName":"eventName","inListFilter":{"values":["purchase","in_app_purchase","app_store_subscription_renew"]}}},...Java
importcom.google.analytics.data.v1beta.BetaAnalyticsDataClient;importcom.google.analytics.data.v1beta.DateRange;importcom.google.analytics.data.v1beta.Dimension;importcom.google.analytics.data.v1beta.Filter;importcom.google.analytics.data.v1beta.FilterExpression;importcom.google.analytics.data.v1beta.Metric;importcom.google.analytics.data.v1beta.RunReportRequest;importcom.google.analytics.data.v1beta.RunReportResponse;importjava.util.ArrayList;/** * Google Analytics Data API sample application demonstrating the usage of dimension and metric * filters in a report. * * <p>See * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.dimension_filter * for more information. * * <p>Before you start the application, please review the comments starting with "TODO(developer)" * and update the code to use correct values. * * <p>To run this sample using Maven: * * <pre>{@code * cd google-analytics-data * mvn compile exec:java -Dexec.mainClass="com.google.analytics.data.samples.RunReportWithDimensionInListFilterSample" * }</pre> */publicclassRunReportWithDimensionInListFilterSample{publicstaticvoidmain(String...args)throwsException{// TODO(developer): Replace with your Google Analytics 4 property ID before running the sample.StringpropertyId="YOUR-GA4-PROPERTY-ID";sampleRunReportWithDimensionInListFilter(propertyId);}// Runs a report using a dimension filter with `in_list_filter` expression. The filter selects for// when `eventName` is set to one of three event names specified in the query.// This sample uses relative date range values.// See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange// for more information.staticvoidsampleRunReportWithDimensionInListFilter(StringpropertyId)throwsException{// Initialize client that will be used to send requests. This client only needs to be created// once, and can be reused for multiple requests. After completing all of your requests, call// the "close" method on the client to safely clean up any remaining background resources.try(BetaAnalyticsDataClientanalyticsData=BetaAnalyticsDataClient.create()){RunReportRequestrequest=RunReportRequest.newBuilder().setProperty("properties/"+propertyId).addDimensions(Dimension.newBuilder().setName("eventName")).addMetrics(Metric.newBuilder().setName("sessions")).addDateRanges(DateRange.newBuilder().setStartDate("7daysAgo").setEndDate("yesterday")).setDimensionFilter(FilterExpression.newBuilder().setFilter(Filter.newBuilder().setFieldName("eventName").setInListFilter(Filter.InListFilter.newBuilder().addAllValues(newArrayList<String>(){{add("purchase");add("in_app_purchase");add("app_store_subscription_renew");}}).build()))).build();// Make the request.RunReportResponseresponse=analyticsData.runReport(request);// Prints the response using a method in RunReportSample.javaRunReportSample.printRunResponseResponse(response);}}}
PHP
use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient;use Google\Analytics\Data\V1beta\DateRange;use Google\Analytics\Data\V1beta\Dimension;use Google\Analytics\Data\V1beta\Filter;use Google\Analytics\Data\V1beta\Filter\InListFilter;use Google\Analytics\Data\V1beta\FilterExpression;use Google\Analytics\Data\V1beta\Metric;use Google\Analytics\Data\V1beta\MetricType;use Google\Analytics\Data\V1beta\RunReportRequest;use Google\Analytics\Data\V1beta\RunReportResponse;/** * Runs a report using a dimension filter with `in_list_filter` expression. * The filter selects for when `eventName` is set to one of three event names * specified in the query. * This sample uses relative date range values. See * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange * for more information. * @param string $propertyId Your GA-4 Property ID */function run_report_with_dimension_in_list_filter(string $propertyId){ // Create an instance of the Google Analytics Data API client library. $client = new BetaAnalyticsDataClient(); // Make an API call. $request = (new RunReportRequest()) ->setProperty('properties/' . $propertyId) ->setDimensions([new Dimension(['name' => 'eventName'])]) ->setMetrics([new Metric(['name' => 'sessions'])]) ->setDateRanges([new DateRange([ 'start_date' => '7daysAgo', 'end_date' => 'yesterday', ]) ]) ->setDimensionFilter(new FilterExpression([ 'filter' => new Filter([ 'field_name' => 'eventName', 'in_list_filter' => new InListFilter([ 'values' => [ 'purchase', 'in_app_purchase', 'app_store_subscription_renew', ], ]), ]), ])); $response = $client->runReport($request); printRunReportResponseWithDimensionInListFilter($response);}/** * Print results of a runReport call. * @param RunReportResponse $response */function printRunReportResponseWithDimensionInListFilter(RunReportResponse $response){ printf('%s rows received%s', $response->getRowCount(), PHP_EOL); foreach ($response->getDimensionHeaders() as $dimensionHeader) { printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL); } foreach ($response->getMetricHeaders() as $metricHeader) { printf( 'Metric header name: %s (%s)' . PHP_EOL, $metricHeader->getName(), MetricType::name($metricHeader->getType()) ); } print 'Report result: ' . PHP_EOL; foreach ($response->getRows() as $row) { printf( '%s %s' . PHP_EOL, $row->getDimensionValues()[0]->getValue(), $row->getMetricValues()[0]->getValue() ); }}
Python
fromgoogle.analytics.data_v1betaimportBetaAnalyticsDataClientfromgoogle.analytics.data_v1beta.typesimport(DateRange,Dimension,Filter,FilterExpression,Metric,RunReportRequest,)fromrun_reportimportprint_run_report_responsedefrun_sample():"""Runs the sample."""# TODO(developer): Replace this variable with your Google Analytics 4# property ID before running the sample.property_id="YOUR-GA4-PROPERTY-ID"run_report_with_dimension_in_list_filter(property_id)defrun_report_with_dimension_in_list_filter(property_id="YOUR-GA4-PROPERTY-ID"):"""Runs a report using a dimension filter with `in_list_filter` expression. The filter selects for when `eventName` is set to one of three event names specified in the query. This sample uses relative date range values. See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange for more information. """client=BetaAnalyticsDataClient()request=RunReportRequest(property=f"properties/{property_id}",dimensions=[Dimension(name="eventName")],metrics=[Metric(name="sessions")],date_ranges=[DateRange(start_date="7daysAgo",end_date="yesterday")],dimension_filter=FilterExpression(filter=Filter(field_name="eventName",in_list_filter=Filter.InListFilter(values=["purchase","in_app_purchase","app_store_subscription_renew",]),)),)response=client.run_report(request)print_run_report_response(response)
Node.js
// TODO(developer): Uncomment this variable and replace with your// Google Analytics 4 property ID before running the sample.// propertyId = 'YOUR-GA4-PROPERTY-ID';// Imports the Google Analytics Data API client library.const{BetaAnalyticsDataClient}=require('@google-analytics/data');// Initialize client that will be used to send requests. This client only// needs to be created once, and can be reused for multiple requests.constanalyticsDataClient=newBetaAnalyticsDataClient();// Runs a report using a dimension filter with `in_list_filter` expression.// The filter selects for when `eventName` is set to one of three event names// specified in the query.// This sample uses relative date range values. See// https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange// for more information.asyncfunctionrunReportWithDimensionInListFilter(){const[response]=awaitanalyticsDataClient.runReport({property:`properties/${propertyId}`,dimensions:[{name:'eventName',},],metrics:[{name:'sessions',},],dateRanges:[{startDate:'7daysAgo',endDate:'yesterday',},],dimensionFilter:{filter:{fieldName:'eventName',inListFilter:{values:['purchase','in_app_purchase','app_store_subscription_renew',],},},},});printRunReportResponse(response);}runReportWithDimensionInListFilter();// Prints results of a runReport call.functionprintRunReportResponse(response){console.log(`${response.rowCount} rows received`);response.dimensionHeaders.forEach(dimensionHeader=>{console.log(`Dimension header name:${dimensionHeader.name}`);});response.metricHeaders.forEach(metricHeader=>{console.log(`Metric header name:${metricHeader.name} (${metricHeader.type})`);});console.log('Report result:');response.rows.forEach(row=>{console.log(`${row.dimensionValues[0].value},${row.metricValues[0].value}`);});}
Navigate long reports
By default, the report contains only the first 10,000 rows of event data. Toview up to 250,000 rows in the report, you can include"limit": 250000 intheRunReportRequest.
For reports with more than 250,000 rows, you have to send a series of requestsand page through the results. For example, here's a request for the first250,000 rows:
HTTP
POSThttps://analyticsdata.googleapis.com/v1beta/properties/GA_PROPERTY_ID:runReport{..."limit":250000,"offset":0}Java
importcom.google.analytics.data.v1beta.BetaAnalyticsDataClient;importcom.google.analytics.data.v1beta.DateRange;importcom.google.analytics.data.v1beta.Dimension;importcom.google.analytics.data.v1beta.Metric;importcom.google.analytics.data.v1beta.RunReportRequest;importcom.google.analytics.data.v1beta.RunReportResponse;/** * Google Analytics Data API sample application demonstrating the use of pagination to retrieve * large result sets. * * <p>See * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.offset * for more information. * * <p>Before you start the application, please review the comments starting with "TODO(developer)" * and update the code to use correct values. * * <p>To run this sample using Maven: * * <pre>{@code * cd google-analytics-data * mvn compile exec:java -Dexec.mainClass="com.google.analytics.data.samples.RunReportWithPaginationSample" * }</pre> */publicclassRunReportWithPaginationSample{publicstaticvoidmain(String...args)throwsException{// TODO(developer): Replace with your Google Analytics 4 property ID before running the sample.StringpropertyId="YOUR-GA4-PROPERTY-ID";sampleRunReportWithPagination(propertyId);}// Runs a report several times, each time retrieving a portion of result using pagination.staticvoidsampleRunReportWithPagination(StringpropertyId)throwsException{// Initialize client that will be used to send requests. This client only needs to be created// once, and can be reused for multiple requests. After completing all of your requests, call// the "close" method on the client to safely clean up any remaining background resources.try(BetaAnalyticsDataClientanalyticsData=BetaAnalyticsDataClient.create()){RunReportRequestrequest=RunReportRequest.newBuilder().setProperty("properties/"+propertyId).addDateRanges(DateRange.newBuilder().setStartDate("365daysAgo").setEndDate("yesterday")).addDimensions(Dimension.newBuilder().setName("firstUserSource")).addDimensions(Dimension.newBuilder().setName("firstUserMedium")).addDimensions(Dimension.newBuilder().setName("firstUserCampaignName")).addMetrics(Metric.newBuilder().setName("sessions")).addMetrics(Metric.newBuilder().setName("keyEvents")).addMetrics(Metric.newBuilder().setName("totalRevenue")).setLimit(100000).setOffset(0).build();// Make the request.RunReportResponseresponse=analyticsData.runReport(request);RunReportSample.printRunResponseResponse(response);// Run the same report with a different offset value to retrieve the second page of a// response.request=RunReportRequest.newBuilder().setProperty("properties/"+propertyId).addDateRanges(DateRange.newBuilder().setStartDate("365daysAgo").setEndDate("yesterday")).addDimensions(Dimension.newBuilder().setName("firstUserSource")).addDimensions(Dimension.newBuilder().setName("firstUserMedium")).addDimensions(Dimension.newBuilder().setName("firstUserCampaignName")).addMetrics(Metric.newBuilder().setName("sessions")).addMetrics(Metric.newBuilder().setName("keyEvents")).addMetrics(Metric.newBuilder().setName("totalRevenue")).setLimit(100000).setOffset(100000).build();// Make the request.response=analyticsData.runReport(request);// Prints the response using a method in RunReportSample.javaRunReportSample.printRunResponseResponse(response);}}}
PHP
// Make an API call. $request = (new RunReportRequest()) ->setProperty('properties/' . $propertyId) ->setDateRanges([ new DateRange([ 'start_date' => '350daysAgo', 'end_date' => 'yesterday', ]) ]) ->setDimensions([ new Dimension(['name' => 'firstUserSource']), new Dimension(['name' => 'firstUserMedium']), new Dimension(['name' => 'firstUserCampaignName']), ]) ->setMetrics([ new Metric(['name' => 'sessions']), new Metric(['name' => 'keyEvents']), new Metric(['name' => 'totalRevenue']), ]) ->setLimit(100000) ->setOffset(0); $requestCount = 1; printf('Sending request #%d' . PHP_EOL, $requestCount); $response = $client->runReport($request);
Python
request=RunReportRequest(property=f"properties/{property_id}",date_ranges=[DateRange(start_date="365daysAgo",end_date="yesterday")],dimensions=[Dimension(name="firstUserSource"),Dimension(name="firstUserMedium"),Dimension(name="firstUserCampaignName"),],metrics=[Metric(name="sessions"),Metric(name="keyEvents"),Metric(name="totalRevenue"),],limit=100000,offset=0,)response=client.run_report(request)
Node.js
const[response]=awaitanalyticsDataClient.runReport({property:`properties/${propertyId}`,dateRanges:[{startDate:'350daysAgo',endDate:'yesterday',},],dimensions:[{name:'firstUserSource',},{name:'firstUserMedium',},{name:'firstUserCampaignName',},],metrics:[{name:'sessions',},{name:'keyEvents',},{name:'totalRevenue',},],limit:100000,offset:0,});
TherowCount parameter in the response indicates the total number of rows,independent of thelimit andoffset values in the request. For example, ifthe response shows"rowCount": 572345, you need three requests:
| offset | limit | Range of row indexes returned |
|---|---|---|
0 | 250000 | [ 0, 249999] |
250000 | 250000 | [250000, 499999] |
500000 | 250000 | [500000, 572345] |
Here's a sample request for the next 250,000 rows. All other parameters, such asdateRange,dimensions, andmetrics should be the same as the firstrequest.
HTTP
POSThttps://analyticsdata.googleapis.com/v1beta/properties/GA_PROPERTY_ID:runReport{..."limit":250000,"offset":250000}Java
request=RunReportRequest.newBuilder().setProperty("properties/"+propertyId).addDateRanges(DateRange.newBuilder().setStartDate("365daysAgo").setEndDate("yesterday")).addDimensions(Dimension.newBuilder().setName("firstUserSource")).addDimensions(Dimension.newBuilder().setName("firstUserMedium")).addDimensions(Dimension.newBuilder().setName("firstUserCampaignName")).addMetrics(Metric.newBuilder().setName("sessions")).addMetrics(Metric.newBuilder().setName("keyEvents")).addMetrics(Metric.newBuilder().setName("totalRevenue")).setLimit(100000).setOffset(100000).build();// Make the request.response=analyticsData.runReport(request);// Prints the response using a method in RunReportSample.javaRunReportSample.printRunResponseResponse(response);
PHP
$rowsReceived = count($response->getRows()); $totalRows = $response->getRowCount(); // Run the same report with an increased offset value to retrieve each additional // page until all rows are received. while ($rowsReceived < $totalRows) { $request = $request->setOffset($rowsReceived); $requestCount++; printf('Sending request #%d' . PHP_EOL, $requestCount); $response = $client->runReport($request); $rowsReceived += count($response->getRows()); printRunReportResponseWithPagination($response, $requestCount); }
Python
request=RunReportRequest(property=f"properties/{property_id}",date_ranges=[DateRange(start_date="365daysAgo",end_date="yesterday")],dimensions=[Dimension(name="firstUserSource"),Dimension(name="firstUserMedium"),Dimension(name="firstUserCampaignName"),],metrics=[Metric(name="sessions"),Metric(name="keyEvents"),Metric(name="totalRevenue"),],limit=100000,offset=100000,)response=client.run_report(request)
Node.js
const[secondResponse]=awaitanalyticsDataClient.runReport({property:`properties/${propertyId}`,dateRanges:[{startDate:'350daysAgo',endDate:'yesterday',},],dimensions:[{name:'firstUserSource',},{name:'firstUserMedium',},{name:'firstUserCampaignName',},],metrics:[{name:'sessions',},{name:'keyEvents',},{name:'totalRevenue',},],limit:100000,offset:100000,});
Use multiple date ranges
One report request can retrieve data for multipledateRanges. For example, this report comparesthe first two weeks for August in 2022 and 2023:
HTTP
POSThttps://analyticsdata.googleapis.com/v1beta/properties/GA_PROPERTY_ID:runReport{"dateRanges":[{"startDate":"2022-08-01","endDate":"2022-08-14"},{"startDate":"2023-08-01","endDate":"2023-08-14"}],"dimensions":[{"name":"platform"}],"metrics":[{"name":"activeUsers"}]}Java
importcom.google.analytics.data.v1beta.BetaAnalyticsDataClient;importcom.google.analytics.data.v1beta.DateRange;importcom.google.analytics.data.v1beta.Dimension;importcom.google.analytics.data.v1beta.Metric;importcom.google.analytics.data.v1beta.RunReportRequest;importcom.google.analytics.data.v1beta.RunReportResponse;/** * Google Analytics Data API sample application demonstrating the usage of date ranges in a report. * * <p>See * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.date_ranges * for more information. * * <p>Before you start the application, please review the comments starting with "TODO(developer)" * and update the code to use correct values. * * <p>To run this sample using Maven: * * <pre>{@code * cd google-analytics-data * mvn compile exec:java -Dexec.mainClass="com.google.analytics.data.samples.RunReportWithDateRangesSample" * }</pre> */publicclassRunReportWithDateRangesSample{publicstaticvoidmain(String...args)throwsException{// TODO(developer): Replace with your Google Analytics 4 property ID before running the sample.StringpropertyId="YOUR-GA4-PROPERTY-ID";sampleRunReportWithDateRanges(propertyId);}// Runs a report using two date ranges.staticvoidsampleRunReportWithDateRanges(StringpropertyId)throwsException{// Initialize client that will be used to send requests. This client only needs to be created// once, and can be reused for multiple requests. After completing all of your requests, call// the "close" method on the client to safely clean up any remaining background resources.try(BetaAnalyticsDataClientanalyticsData=BetaAnalyticsDataClient.create()){RunReportRequestrequest=RunReportRequest.newBuilder().setProperty("properties/"+propertyId).addDateRanges(DateRange.newBuilder().setStartDate("2019-08-01").setEndDate("2019-08-14")).addDateRanges(DateRange.newBuilder().setStartDate("2020-08-01").setEndDate("2020-08-14")).addDimensions(Dimension.newBuilder().setName("platform")).addMetrics(Metric.newBuilder().setName("activeUsers")).build();// Make the request.RunReportResponseresponse=analyticsData.runReport(request);// Prints the response using a method in RunReportSample.javaRunReportSample.printRunResponseResponse(response);}}}
PHP
use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient;use Google\Analytics\Data\V1beta\DateRange;use Google\Analytics\Data\V1beta\Dimension;use Google\Analytics\Data\V1beta\Metric;use Google\Analytics\Data\V1beta\MetricType;use Google\Analytics\Data\V1beta\RunReportRequest;use Google\Analytics\Data\V1beta\RunReportResponse;/** * @param string $propertyID Your GA-4 Property ID * Runs a report using two date ranges. */function run_report_with_date_ranges(string $propertyId){ // Create an instance of the Google Analytics Data API client library. $client = new BetaAnalyticsDataClient(); // Make an API call. $request = (new RunReportRequest()) ->setProperty('properties/' . $propertyId) ->setDateRanges([ new DateRange([ 'start_date' => '2019-08-01', 'end_date' => '2019-08-14', ]), new DateRange([ 'start_date' => '2020-08-01', 'end_date' => '2020-08-14', ]), ]) ->setDimensions([new Dimension(['name' => 'platform'])]) ->setMetrics([new Metric(['name' => 'activeUsers'])]); $response = $client->runReport($request); printRunReportResponseWithDateRanges($response);}/** * Print results of a runReport call. * @param RunReportResponse $response */function printRunReportResponseWithDateRanges(RunReportResponse $response){ printf('%s rows received%s', $response->getRowCount(), PHP_EOL); foreach ($response->getDimensionHeaders() as $dimensionHeader) { printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL); } foreach ($response->getMetricHeaders() as $metricHeader) { printf( 'Metric header name: %s (%s)' . PHP_EOL, $metricHeader->getName(), MetricType::name($metricHeader->getType()) ); } print 'Report result: ' . PHP_EOL; foreach ($response->getRows() as $row) { printf( '%s %s' . PHP_EOL, $row->getDimensionValues()[0]->getValue(), $row->getMetricValues()[0]->getValue() ); }}
Python
fromgoogle.analytics.data_v1betaimportBetaAnalyticsDataClientfromgoogle.analytics.data_v1beta.typesimport(DateRange,Dimension,Metric,RunReportRequest,)fromrun_reportimportprint_run_report_responsedefrun_sample():"""Runs the sample."""# TODO(developer): Replace this variable with your Google Analytics 4# property ID before running the sample.property_id="YOUR-GA4-PROPERTY-ID"run_report_with_date_ranges(property_id)defrun_report_with_date_ranges(property_id="YOUR-GA4-PROPERTY-ID"):"""Runs a report using two date ranges."""client=BetaAnalyticsDataClient()request=RunReportRequest(property=f"properties/{property_id}",date_ranges=[DateRange(start_date="2019-08-01",end_date="2019-08-14"),DateRange(start_date="2020-08-01",end_date="2020-08-14"),],dimensions=[Dimension(name="platform")],metrics=[Metric(name="activeUsers")],)response=client.run_report(request)print_run_report_response(response)
Node.js
// TODO(developer): Uncomment this variable and replace with your// Google Analytics 4 property ID before running the sample.// propertyId = 'YOUR-GA4-PROPERTY-ID';// Imports the Google Analytics Data API client library.const{BetaAnalyticsDataClient}=require('@google-analytics/data');// Initialize client that will be used to send requests. This client only// needs to be created once, and can be reused for multiple requests.constanalyticsDataClient=newBetaAnalyticsDataClient();// Runs a report using two date ranges.asyncfunctionrunReportWithDateRanges(){const[response]=awaitanalyticsDataClient.runReport({property:`properties/${propertyId}`,dateRanges:[{startDate:'2019-08-01',endDate:'2019-08-14',},{startDate:'2020-08-01',endDate:'2020-08-14',},],dimensions:[{name:'platform',},],metrics:[{name:'activeUsers',},],});printRunReportResponse(response);}runReportWithDateRanges();// Prints results of a runReport call.functionprintRunReportResponse(response){console.log(`${response.rowCount} rows received`);response.dimensionHeaders.forEach(dimensionHeader=>{console.log(`Dimension header name:${dimensionHeader.name}`);});response.metricHeaders.forEach(metricHeader=>{console.log(`Metric header name:${metricHeader.name} (${metricHeader.type})`);});console.log('Report result:');response.rows.forEach(row=>{console.log(`${row.dimensionValues[0].value},${row.metricValues[0].value}`);});}
When you include multipledateRanges in a request, adateRange column isautomatically added to the response. When thedateRange column isdate_range_0, that row's data is for the first date range. When thedateRange column isdate_range_1, that row's data is for the second daterange.
Here's a sample response for two date ranges:
{"dimensionHeaders":[{"name":"platform"},{"name":"dateRange"}],"metricHeaders":[{"name":"activeUsers","type":"TYPE_INTEGER"}],"rows":[{"dimensionValues":[{"value":"iOS"},{"value":"date_range_0"}],"metricValues":[{"value":"774"}]},{"dimensionValues":[{"value":"Android"},{"value":"date_range_1"}],"metricValues":[{"value":"335"}]},...],}Next steps
Seeadvanced features andrealtime reporting foran overview of more advanced reporting features of the Data API v1.
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-05-15 UTC.