Create a reportStay organized with collectionsSave 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 therunReportmethod.
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 usinglimitandoffsetparameters 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 using
the Google Analytics Data API v1. Reports from the Data API v1 are similar to
the reports you can generate in theReportssection of theGoogle Analytics
UI.
This guide covers core reporting, the general reporting feature of the Data
API. The Data API v1 also has specializedRealtime
reportingandFunnel reporting.
runReportis the recommended method
for queries, and is used in all examples throughout this guide. Seeadvanced
featuresfor an overview of other core reporting methods. Try theQuery Explorerto test your
queries.
Reports overview
Reportsare tables of event data for aGoogle Analytics property. Each report table has the
dimensions and metrics requested in your query, with data in individual rows.
Usefiltersto return only rows matching a certain condition, andpaginationto 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
EveryrunReportrequest requires you to specify aGoogle Analytics property
ID. The Analytics property you specify is used as the dataset for
that query. Here's an example:
POST https://analyticsdata.googleapis.com/v1beta/properties/GA_PROPERTY_ID:runReport
The response from this request includes only data from the Analytics property
you specify as theGA_PROPERTY_ID.
If you use theData API client libraries, specify the data
source in thepropertyparameter, in the form ofproperties/GA_PROPERTY_ID. See thequick start guidefor examples of using the
client libraries.
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}")
// 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();
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 bydate 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)
// 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, and
73.0841 Total Revenue in your Analytics property's currency on the date20231025(October 25, 2023).
Dimensionsare qualitative attributes you can use
to group and filter your data. For example, thecitydimension indicates the
city, likeParisorNew York, where each event originated. Dimensions are
optional forrunReportrequests, and you can use up to nine dimensions per
request.
See theAPI dimensionsfor a full list of the
dimensions you can use to group and filter your data.
Group
Here's a sample request that groups active users into three dimensions:
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)
// 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 there
were 47 active users during the specified date range with events from Cape Town,
South Africa.
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 seriesreport 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/DateRangefor 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)
// 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 anotherFilterExpressionexample,
whereandGroupincludes only data that meets all criteria in the expressions
list. ThisdimensionFilterselects for when bothbrowserisChromeandcountryIdisUS:
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/DateRangefor 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)
// 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}`,);});}
AnorGroupincludes data that meets any of the criteria in the expressions
list.
AnotExpressionexcludes data that matches its inner expression. Here's adimensionFilterthat returns data for only when thepageTitleisn'tMy
Homepage. The report shows event data for everypageTitleother thanMy
Homepage:
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 filterselects 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/DateRangefor 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)
// 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}`,);});}
AninListFiltermatches data for any of the values in the list. Here's adimensionFilterthat returns event data whereeventNameis any ofpurchase,in_app_purchase, andapp_store_subscription_renew:
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 namesspecified in the query.This sample uses relative date range values. See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRangefor 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)
// 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}`,);});}
By default, the report contains only the first 10,000 rows of event data. To
view up to 250,000 rows in the report, you can include"limit": 250000in
theRunReportRequest.
For reports with more than 250,000 rows, you have to send a series of requests
and page through the results. For example, here's a request for the first
250,000 rows:
TherowCountparameter in the response indicates the total number of rows,
independent of thelimitandoffsetvalues in the request. For example, if
the 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, andmetricsshould be the same as the first
request.
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)
// 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 multipledateRangesin a request, adateRangecolumn is
automatically added to the response. When thedateRangecolumn isdate_range_0, that row's data is for the first date range. When thedateRangecolumn isdate_range_1, that row's data is for the second date
range.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2026-03-30 UTC."],[],["The document details how to use the Google Analytics Data API to create reports by employing the `runReport` method. This involves specifying a property ID, `dateRanges`, `dimensions` (qualitative attributes), and `metrics` (quantitative measurements). Key functionalities include grouping data by multiple dimensions, filtering using `FilterExpression` (with `andGroup` and `notExpression`), and retrieving reports with multiple metrics. The API supports pagination (using `limit` and `offset`) and multiple date ranges. Code examples are provided in Java, PHP, Python, and Node.js.\n"]]