### Install Go SDK for Google Analytics Data API v1beta Source: https://developers.google.com/analytics/devguides/reporting/data/v1/quickstart?account_type=user This command installs the Go client library for the Google Analytics Data API v1beta. Ensure you have Go installed and configured in your environment. ```go go get google.golang.org/genproto/googleapis/analytics/data/v1beta ``` -------------------------------- ### Install Go SDK and Configure Environment Variables Source: https://developers.google.com/analytics/devguides/reporting/data/v1/quickstart Commands to install the Google Analytics Data API Go client library and set the required project and property ID environment variables. ```bash go get google.golang.org/genproto/googleapis/analytics/data/v1beta export PROJECT_ID=PROJECT_ID export PROPERTY_ID=PROPERTY_ID ``` -------------------------------- ### Install Go Client Library for Google Analytics Data API v1beta Source: https://developers.google.com/analytics/devguides/reporting/data/v1/client-libraries This snippet shows how to install the Go client library for the Google Analytics Data API v1beta using the go get command. This command fetches the necessary packages to start using the library in your Go projects. Ensure you have Go installed and configured. ```go go get google.golang.org/genproto/googleapis/analytics/data/v1beta ``` -------------------------------- ### Run a basic report using Google Analytics Data API Source: https://developers.google.com/analytics/devguides/reporting/data/v1/quickstart?hl=zh-tw Demonstrates how to initialize the client and request a report for active users grouped by city or country. These examples require a valid GA4 property ID and appropriate authentication credentials. ```python dimensions=[Dimension(name="city")], metrics=[Metric(name="activeUsers")], date_ranges=[DateRange(start_date="2020-03-31", end_date="today")], ) response = client.run_report(request) print("Report result:") for row in response.rows: print(row.dimension_values[0].value, row.metric_values[0].value) ``` ```javascript const {BetaAnalyticsDataClient} = require('@google-analytics/data'); const analyticsDataClient = new BetaAnalyticsDataClient(); async function runReport() { const [response] = await analyticsDataClient.runReport({ property: `properties/${propertyId}`, dateRanges: [{ startDate: '2020-03-31', endDate: 'today' }], dimensions: [{ name: 'city' }], metrics: [{ name: 'activeUsers' }], }); console.log('Report result:'); response.rows.forEach((row) => { console.log(row.dimensionValues[0], row.metricValues[0]); }); } runReport(); ``` ```csharp BetaAnalyticsDataClient client = BetaAnalyticsDataClient.Create(); RunReportRequest request = new RunReportRequest { Property = "properties/" + propertyId, Dimensions = { new Dimension { Name = "city" } }, Metrics = { new Metric { Name = "activeUsers" } }, DateRanges = { new DateRange { StartDate = "2020-03-31", EndDate = "today" } }, }; RunReportResponse response = client.RunReport(request); foreach (Row row in response.Rows) { Console.WriteLine("{0}, {1}", row.DimensionValues[0].Value, row.MetricValues[0].Value); } ``` ```bash curl -X POST \ -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \ -H "x-goog-user-project: ${PROJECT_ID}" \ -H "Content-Type: application/json" \ -d '{ "dateRanges": [{"startDate": "2025-01-01", "endDate": "2025-02-01"}], "dimensions": [{"name": "country"}], "metrics": [{"name": "activeUsers"}] }' https://analyticsdata.googleapis.com/v1beta/properties/${PROPERTY_ID}:runReport ``` -------------------------------- ### Run Report API Source: https://developers.google.com/analytics/devguides/reporting/data/v1/quickstart-client-libraries?hl=pl This section details how to run a report using the Google Analytics Data API v1beta. It includes examples in Python, JavaScript, C#, and a direct REST API call using curl. ```APIDOC ## POST /v1beta/properties/{propertyId}:runReport ### Description Runs a report request and returns report data. This method is used to retrieve aggregated data from a Google Analytics property based on specified dimensions, metrics, and date ranges. ### Method POST ### Endpoint `https://analyticsdata.googleapis.com/v1beta/properties/{propertyId}:runReport` ### Parameters #### Path Parameters - **propertyId** (string) - Required - The Google Analytics 4 property ID for which to run the report. #### Query Parameters None #### Request Body - **dateRanges** (array[object]) - Required - The date ranges for which to run the report. Each object should contain `startDate` and `endDate`. - **startDate** (string) - Required - The start date in 'YYYY-MM-DD' format. - **endDate** (string) - Required - The end date in 'YYYY-MM-DD' format. - **dimensions** (array[object]) - Optional - The dimensions to include in the report. Each object should contain a `name`. - **name** (string) - Required - The name of the dimension (e.g., "city", "country"). - **metrics** (array[object]) - Required - The metrics to include in the report. Each object should contain a `name`. - **name** (string) - Required - The name of the metric (e.g., "activeUsers"). ### Request Example (REST) ```json { "dateRanges": [ { "startDate": "2025-01-01", "endDate": "2025-02-01" } ], "dimensions": [ { "name": "country" } ], "metrics": [ { "name": "activeUsers" } ] } ``` ### Response #### Success Response (200) - **dimensionHeaders** (array[object]) - Headers for the dimensions in the report. - **name** (string) - The name of the dimension. - **metricHeaders** (array[object]) - Headers for the metrics in the report. - **name** (string) - The name of the metric. - **type** (string) - The data type of the metric (e.g., "TYPE_INTEGER"). - **rows** (array[object]) - Rows of data for the report. - **dimensionValues** (array[object]) - Values for the dimensions in a row. - **value** (string) - The dimension value. - **metricValues** (array[object]) - Values for the metrics in a row. - **value** (string) - The metric value. #### Response Example ```json { "dimensionHeaders": [ { "name": "country" } ], "metricHeaders": [ { "name": "activeUsers", "type": "TYPE_INTEGER" } ], "rows": [ { "dimensionValues": [ { "value": "United States" } ], "metricValues": [ { "value": "3242" } ] }, { "dimensionValues": [ { "value": "(not set)" } ], "metricValues": [ { "value": "1500" } ] } ] } ``` ### Client Library Examples #### Python ```python from google.analytics.data_v1beta import BetaAnalyticsDataClient from google.analytics.data_v1beta.types import DateRange, Dimension, Metric, RunReportRequest # TODO(developer): Uncomment this variable and replace with your Google Analytics 4 property ID. # property_id = "YOUR_PROPERTY_ID" client = BetaAnalyticsDataClient() request = RunReportRequest( property=f"properties/{property_id}", dimensions=[Dimension(name="city")], metrics=[Metric(name="activeUsers")], date_ranges=[DateRange(start_date="2020-03-31", end_date="today")], ) response = client.run_report(request) print("Report result:") for row in response.rows: print(row.dimension_values[0].value, row.metric_values[0].value) ``` #### Node.js ```javascript /** * TODO(developer): Uncomment this variable and replace with your * Google Analytics 4 property ID before running the sample. */ // const propertyId = 'YOUR-GA4-PROPERTY-ID'; // Imports the Google Analytics Data API client library. const {BetaAnalyticsDataClient} = require('@google-analytics/data'); const analyticsDataClient = new BetaAnalyticsDataClient(); async function runReport() { const [response] = await analyticsDataClient.runReport({ property: `properties/${propertyId}`, dateRanges: [ { startDate: '2020-03-31', endDate: 'today', }, ], dimensions: [ { name: 'city', }, ], metrics: [ { name: 'activeUsers', }, ], }); console.log('Report result:'); response.rows.forEach((row) => { console.log(row.dimensionValues[0], row.metricValues[0]); }); } runReport(); ``` #### C# ```csharp using System; using Google.Analytics.Data.V1Beta; namespace AnalyticsSamples { class QuickStart { static void SampleRunReport(string propertyId = "YOUR-GA4-PROPERTY-ID") { /** * TODO(developer): Uncomment this variable and replace with your * Google Analytics 4 property ID before running the sample. */ // propertyId = "YOUR-GA4-PROPERTY-ID"; BetaAnalyticsDataClient client = BetaAnalyticsDataClient.Create(); RunReportRequest request = new RunReportRequest { Property = "properties/" + propertyId, Dimensions = { new Dimension { Name = "city" } }, Metrics = { new Metric { Name = "activeUsers" } }, DateRanges = { new DateRange { StartDate = "2020-03-31", EndDate = "today" }, }, }; RunReportResponse response = client.RunReport(request); Console.WriteLine("Report result:"); foreach (Row row in response.Rows) { Console.WriteLine( "{0}, {1}", row.DimensionValues[0].Value, row.MetricValues[0].Value ); } } static int Main(string[] args) { if (args.Length > 0) { SampleRunReport(args[0]); } else { SampleRunReport(); } return 0; } } } ``` ### cURL Example ```bash curl -X POST \ -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \ -H "x-goog-user-project: ${PROJECT_ID}" \ -H "Content-Type: application/json" \ -d \ '{ "dateRanges": [ { "startDate": "2025-01-01", "endDate": "2025-02-01" } ], "dimensions": [ { "name": "country" } ], "metrics": [ { "name": "activeUsers" } ] }' https://analyticsdata.googleapis.com/v1beta/properties/${PROPERTY_ID}:runReport ``` ``` -------------------------------- ### Run Report API Endpoint Source: https://developers.google.com/analytics/devguides/reporting/data/v1/quickstart?account_type=user&hl=pt-br This section details the `runReport` endpoint for the Google Analytics Data API v1beta, explaining its purpose, parameters, and providing examples. ```APIDOC ## POST /v1beta/properties/${PROPERTY_ID}:runReport ### Description Retrieves a report from the Google Analytics Data API. This endpoint allows you to fetch aggregated data based on specified dimensions, metrics, and date ranges. ### Method POST ### Endpoint `https://analyticsdata.googleapis.com/v1beta/properties/${PROPERTY_ID}:runReport` ### Parameters #### Query Parameters - **${PROPERTY_ID}** (string) - Required - The Google Analytics 4 property ID. #### Request Body - **dateRanges** (array of objects) - Required - Specifies the date range(s) for the report. Each object should have `startDate` and `endDate` (string, format: YYYY-MM-DD). - **startDate** (string) - Required - The start date for the report. - **endDate** (string) - Required - The end date for the report. - **dimensions** (array of objects) - Required - A list of dimensions to include in the report. Each object should have a `name` (string). - **name** (string) - Required - The name of the dimension (e.g., "city", "country"). - **metrics** (array of objects) - Required - A list of metrics to include in the report. Each object should have a `name` (string). - **name** (string) - Required - The name of the metric (e.g., "activeUsers"). ### Request Example ```json { "dateRanges": [ { "startDate": "2025-01-01", "endDate": "2025-02-01" } ], "dimensions": [ { "name": "country" } ], "metrics": [ { "name": "activeUsers" } ] } ``` ### Response #### Success Response (200) - **dimensionHeaders** (array of objects) - Headers for the dimensions in the report. - **name** (string) - The name of the dimension. - **metricHeaders** (array of objects) - Headers for the metrics in the report. - **name** (string) - The name of the metric. - **type** (string) - The data type of the metric (e.g., "TYPE_INTEGER"). - **rows** (array of objects) - Rows of data returned by the report. - **dimensionValues** (array of objects) - Values for the dimensions in a row. - **value** (string) - The dimension value. - **metricValues** (array of objects) - Values for the metrics in a row. - **value** (string) - The metric value. #### Response Example ```json { "dimensionHeaders": [ { "name": "country" } ], "metricHeaders": [ { "name": "activeUsers", "type": "TYPE_INTEGER" } ], "rows": [ { "dimensionValues": [ { "value": "United States" } ], "metricValues": [ { "value": "3242" } ] }, { "dimensionValues": [ { "value": "(not set)" } ], "metricValues": [ { "value": "3015" } ] } ] } ``` ``` -------------------------------- ### Run Report API Source: https://developers.google.com/analytics/devguides/reporting/data/v1/quickstart-client-libraries?hl=vi This section details how to run a report using the Google Analytics Data API v1beta. It includes examples for making the request and understanding the response. ```APIDOC ## POST /v1beta/properties/${PROPERTY_ID}:runReport ### Description Runs a report on the specified Google Analytics property, returning requested metrics and dimensions for a given date range. ### Method POST ### Endpoint https://analyticsdata.googleapis.com/v1beta/properties/${PROPERTY_ID}:runReport ### Parameters #### Query Parameters - **PROJECT_ID** (string) - Required - The Google Cloud project ID. - **PROPERTY_ID** (string) - Required - The Google Analytics 4 property ID. #### Request Body - **dateRanges** (array) - Required - The date ranges for the report. - **startDate** (string) - Required - The start date in 'YYYY-MM-DD' format. - **endDate** (string) - Required - The end date in 'YYYY-MM-DD' format. - **dimensions** (array) - Required - The dimensions to include in the report. - **name** (string) - Required - The name of the dimension (e.g., "city", "country"). - **metrics** (array) - Required - The metrics to include in the report. - **name** (string) - Required - The name of the metric (e.g., "activeUsers"). ### Request Example ```json { "dateRanges": [ { "startDate": "2025-01-01", "endDate": "2025-02-01" } ], "dimensions": [ { "name": "country" } ], "metrics": [ { "name": "activeUsers" } ] } ``` ### Response #### Success Response (200) - **dimensionHeaders** (array) - Headers for the dimensions in the report. - **name** (string) - The name of the dimension. - **metricHeaders** (array) - Headers for the metrics in the report. - **name** (string) - The name of the metric. - **type** (string) - The type of the metric (e.g., "TYPE_INTEGER"). - **rows** (array) - Rows of data for the report. - **dimensionValues** (array) - Values for the dimensions in a row. - **value** (string) - The dimension value. - **metricValues** (array) - Values for the metrics in a row. - **value** (string) - The metric value. #### Response Example ```json { "dimensionHeaders": [ { "name": "country" } ], "metricHeaders": [ { "name": "activeUsers", "type": "TYPE_INTEGER" } ], "rows": [ { "dimensionValues": [ { "value": "United States" } ], "metricValues": [ { "value": "3242" } ] }, { "dimensionValues": [ { "value": "(not set)" } ], "metricValues": [ { "value": "3015" } ] } ] } ``` ``` -------------------------------- ### Run GA4 Report via Analytics Data API Source: https://developers.google.com/analytics/devguides/reporting/data/v1/quickstart-client-libraries?hl=pl Demonstrates how to authenticate and execute a report request to fetch active users grouped by a specific dimension. The examples rely on the GOOGLE_APPLICATION_CREDENTIALS environment variable for authentication. ```python from google.analytics.data_v1beta import BetaAnalyticsDataClient from google.analytics.data_v1beta.types import RunReportRequest, Dimension, Metric, DateRange client = BetaAnalyticsDataClient() request = RunReportRequest( property=f"properties/{property_id}", dimensions=[Dimension(name="city")], metrics=[Metric(name="activeUsers")], date_ranges=[DateRange(start_date="2020-03-31", end_date="today")], ) response = client.run_report(request) for row in response.rows: print(row.dimension_values[0].value, row.metric_values[0].value) ``` ```javascript const {BetaAnalyticsDataClient} = require('@google-analytics/data'); const analyticsDataClient = new BetaAnalyticsDataClient(); async function runReport() { const [response] = await analyticsDataClient.runReport({ property: `properties/${propertyId}`, dateRanges: [{ startDate: '2020-03-31', endDate: 'today' }], dimensions: [{ name: 'city' }], metrics: [{ name: 'activeUsers' }], }); response.rows.forEach((row) => { console.log(row.dimensionValues[0], row.metricValues[0]); }); } runReport(); ``` ```csharp using Google.Analytics.Data.V1Beta; BetaAnalyticsDataClient client = BetaAnalyticsDataClient.Create(); RunReportRequest request = new RunReportRequest { Property = "properties/" + propertyId, Dimensions = { new Dimension { Name = "city" } }, Metrics = { new Metric { Name = "activeUsers" } }, DateRanges = { new DateRange { StartDate = "2020-03-31", EndDate = "today" } }, }; RunReportResponse response = client.RunReport(request); foreach (Row row in response.Rows) { Console.WriteLine("{0}, {1}", row.DimensionValues[0].Value, row.MetricValues[0].Value); } ``` ```bash curl -X POST \ -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \ -H "x-goog-user-project: ${PROJECT_ID}" \ -H "Content-Type: application/json" \ -d '{ "dateRanges": [{"startDate": "2025-01-01", "endDate": "2025-02-01"}], "dimensions": [{"name": "country"}], "metrics": [{"name": "activeUsers"}] }' https://analyticsdata.googleapis.com/v1beta/properties/${PROPERTY_ID}:runReport ``` -------------------------------- ### Run GA4 Report using Google Analytics Data API Source: https://developers.google.com/analytics/devguides/reporting/data/v1/quickstart-client-libraries?hl=vi Demonstrates how to initialize the client and execute a basic report request for active users grouped by city or country. These examples require setting the GOOGLE_APPLICATION_CREDENTIALS environment variable for authentication. ```python from google.analytics.data_v1beta import BetaAnalyticsDataClient from google.analytics.data_v1beta.types import RunReportRequest, DateRange, Metric, Dimension client = BetaAnalyticsDataClient() request = RunReportRequest( property=f"properties/{property_id}", dimensions=[Dimension(name="city")], metrics=[Metric(name="activeUsers")], date_ranges=[DateRange(start_date="2020-03-31", end_date="today")], ) response = client.run_report(request) for row in response.rows: print(row.dimension_values[0].value, row.metric_values[0].value) ``` ```javascript const {BetaAnalyticsDataClient} = require('@google-analytics/data'); const analyticsDataClient = new BetaAnalyticsDataClient(); async function runReport() { const [response] = await analyticsDataClient.runReport({ property: `properties/${propertyId}`, dateRanges: [{ startDate: '2020-03-31', endDate: 'today' }], dimensions: [{ name: 'city' }], metrics: [{ name: 'activeUsers' }], }); response.rows.forEach((row) => { console.log(row.dimensionValues[0], row.metricValues[0]); }); } runReport(); ``` ```csharp using Google.Analytics.Data.V1Beta; BetaAnalyticsDataClient client = BetaAnalyticsDataClient.Create(); RunReportRequest request = new RunReportRequest { Property = "properties/" + propertyId, Dimensions = { new Dimension { Name = "city" } }, Metrics = { new Metric { Name = "activeUsers" } }, DateRanges = { new DateRange { StartDate = "2020-03-31", EndDate = "today" } }, }; RunReportResponse response = client.RunReport(request); foreach (Row row in response.Rows) { Console.WriteLine("{0}, {1}", row.DimensionValues[0].Value, row.MetricValues[0].Value); } ``` ```bash curl -X POST \ -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \ -H "x-goog-user-project: ${PROJECT_ID}" \ -H "Content-Type: application/json" \ -d '{ "dateRanges": [{"startDate": "2025-01-01", "endDate": "2025-02-01"}], "dimensions": [{"name": "country"}], "metrics": [{"name": "activeUsers"}] }' https://analyticsdata.googleapis.com/v1beta/properties/${PROPERTY_ID}:runReport ``` -------------------------------- ### Authenticate with Google Cloud CLI (gcloud) Source: https://developers.google.com/analytics/devguides/reporting/data/v1/quickstart?account_type=user This command generates Application Default Credentials and assigns the necessary scopes for accessing Google Cloud services, including Google Analytics read-only access. It requires the gcloud CLI to be installed and initialized. ```bash gcloud auth application-default login --scopes="https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/analytics.readonly" ``` -------------------------------- ### Run GA4 Report with Multiple Metrics Source: https://developers.google.com/analytics/devguides/reporting/data/v1/basics Demonstrates how to initialize the Analytics Data client, construct a report request with specific dimensions and metrics, and iterate through the response data. The examples cover PHP, Python, and Node.js implementations. ```php 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 from google.analytics.data_v1beta import BetaAnalyticsDataClient from google.analytics.data_v1beta.types import DateRange, Dimension, Metric, RunReportRequest def run_report_with_multiple_metrics(property_id="YOUR-GA4-PROPERTY-ID"): client = BetaAnalyticsDataClient() 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) return response ``` ```javascript const {BetaAnalyticsDataClient} = require('@google-analytics/data'); const analyticsDataClient = new BetaAnalyticsDataClient(); async function runReportWithMultipleMetrics(propertyId) { const [response] = await analyticsDataClient.runReport({ property: `properties/${propertyId}`, dimensions: [{name: 'date'}], metrics: [ {name: 'activeUsers'}, {name: 'newUsers'}, {name: 'totalRevenue'} ], dateRanges: [{startDate: '7daysAgo', endDate: 'today'}] }); return response; } ``` -------------------------------- ### Run Report API Call Source: https://developers.google.com/analytics/devguides/reporting/data/v1/quickstart This section details how to make an API call to the `runReport` method to retrieve active users for a specified Google Analytics 4 property. Examples are provided in Java, PHP, and Python. ```APIDOC ## POST /v1beta/analyticsdata.runReport ### Description Runs a report on the specified Google Analytics 4 property. This method allows you to retrieve metrics and dimensions for your property. ### Method POST ### Endpoint /v1beta/analyticsdata.runReport ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **property** (string) - Required - The name of the property to run the report on, in the format `properties/{propertyId}`. - **dateRanges** (array of DateRange) - Required - The date ranges for which to run the report. - **startDate** (string) - Required - The start date for the date range in 'YYYY-MM-DD' format. - **endDate** (string) - Required - The end date for the date range in 'YYYY-MM-DD' format. - **dimensions** (array of Dimension) - Optional - The dimensions to include in the report. - **name** (string) - Required - The name of the dimension (e.g., 'city', 'country'). - **metrics** (array of Metric) - Required - The metrics to include in the report. - **name** (string) - Required - The name of the metric (e.g., 'activeUsers', 'sessions'). ### Request Example (Java) ```java import com.google.analytics.data.v1beta.BetaAnalyticsDataClient; import com.google.analytics.data.v1beta.DateRange; import com.google.analytics.data.v1beta.Dimension; import com.google.analytics.data.v1beta.Metric; import com.google.analytics.data.v1beta.RunReportRequest; import com.google.analytics.data.v1beta.RunReportResponse; // ... inside a method ... String propertyId = "YOUR-GA4-PROPERTY-ID"; try (BetaAnalyticsDataClient analyticsData = BetaAnalyticsDataClient.create()) { RunReportRequest request = RunReportRequest.newBuilder() .setProperty("properties/" + propertyId) .addDimensions(Dimension.newBuilder().setName("city")) .addMetrics(Metric.newBuilder().setName("activeUsers")) .addDateRanges(DateRange.newBuilder().setStartDate("2020-03-31").setEndDate("today")) .build(); RunReportResponse response = analyticsData.runReport(request); } ``` ### Request Example (PHP) ```php require 'vendor/autoload.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\RunReportRequest; // ... inside a method ... $property_id = 'YOUR-GA4-PROPERTY-ID'; $client = new BetaAnalyticsDataClient(); $request = (new RunReportRequest()) ->setProperty('properties/' . $property_id) ->setDateRanges([ new DateRange([ 'start_date' => '2020-03-31', 'end_date' => 'today', ]), ]) ->setDimensions([new Dimension([ 'name' => 'city', ]) ]) ->setMetrics([new Metric([ 'name' => 'activeUsers', ]) ]); $response = $client->runReport($request); ``` ### Request Example (Python) ```python from google.analytics.data_v1beta import BetaAnalyticsDataClient from google.analytics.data_v1beta.types import ( DateRange, Dimension, Metric, RunReportRequest, ) # ... inside a method ... def sample_run_report(property_id="YOUR-GA4-PROPERTY-ID"): # ... client = BetaAnalyticsDataClient() request = RunReportRequest( property=f"properties/{property_id}", dimensions=[ Dimension(name="city") ], metrics=[ Metric(name="activeUsers") ], date_ranges=[ DateRange(start_date="2020-03-31", end_date="today") ], ) response = client.run_report(request) ``` ### Response #### Success Response (200) - **dimensionHeaders** (array of DimensionHeader) - The header information for dimensions. - **metricHeaders** (array of MetricHeader) - The header information for metrics. - **rows** (array of Row) - The rows of report data. - **dimensionValues** (array of DimensionValue) - Values for the dimensions in this row. - **metricValues** (array of MetricValue) - Values for the metrics in this row. - **rowCount** (integer) - The total number of rows in the result. - **metadata** (Metadata) - Metadata for the report. - **propertyQuota** (PropertyQuota) - Quotas related to this property. #### Response Example (Java) ```java // Assuming 'response' is a RunReportResponse object from the API call System.out.println("Report result:"); for (Row row : response.getRowsList()) { System.out.printf("%s, %s%n", row.getDimensionValues(0).getValue(), row.getMetricValues(0).getValue()); } ``` #### Response Example (PHP) ```php // Assuming '$response' is the result of client->runReport($request) print 'Report result: ' . PHP_EOL; foreach ($response->getRows() as $row) { print $row->getDimensionValues()[0]->getValue() . ' ' . $row->getMetricValues()[0]->getValue() . PHP_EOL; } ``` #### Response Example (Python) ```python # Assuming 'response' is the result of client.run_report(request) print("Report result:") for row in response.rows: print(f"{row.dimension_values[0].value} {row.metric_values[0].value}") ``` ``` -------------------------------- ### runFunnelReport - Raw Response Example Source: https://developers.google.com/analytics/devguides/reporting/data/v1/funnels This snippet shows an example of the raw data returned by the `runFunnelReport` query. It includes details about funnel steps, device categories, active users, completion rates, and abandonment metrics. ```APIDOC ## POST /v1/properties/{propertyId}:runFunnelReport ### Description This endpoint returns a raw funnel report, detailing user progression through defined funnel steps and associated metrics. It can include breakdowns by dimensions like device category. ### Method POST ### Endpoint /v1/properties/{propertyId}:runFunnelReport ### Parameters #### Path Parameters - **propertyId** (string) - Required - The ID of the Google Analytics property to retrieve data from. #### Query Parameters None #### Request Body (The request body is not detailed in the provided text, but would typically include dimensions, metrics, and date ranges for the report.) ### Request Example ```json { "dimensions": [ {"name": "funnelStepName"}, {"name": "deviceCategory"} ], "metrics": [ {"name": "activeUsers"}, {"name": "funnelStepCompletionRate"}, {"name": "funnelStepAbandonments"}, {"name": "funnelStepAbandonmentRate"} ], "dateRanges": [ {"startDate": "2023-01-01", "endDate": "2023-01-31"} ], "funnel": { "name": "YourFunnelName", "steps": [ {"name": "1. First open/visit"}, {"name": "2. Added to cart"}, {"name": "3. Started checkout"} ] } } ``` ### Response #### Success Response (200) - **funnelTable** (object) - Contains the detailed funnel report data, including dimension and metric headers, and rows of data. - **dimensionHeaders** (array) - Headers for the dimensions in the report. - **metricHeaders** (array) - Headers for the metrics in the report. - **rows** (array) - An array of objects, where each object represents a row of data with dimension and metric values. - **metadata** (object) - Contains metadata about the report, such as sampling information. - **funnelVisualization** (object) - A simplified view of the funnel, often used for visualization purposes. - **kind** (string) - The type of resource, typically "analyticsData#runFunnelReport". #### Response Example ```json { "funnelTable": { "dimensionHeaders": [ {"name": "funnelStepName"}, {"name": "deviceCategory"} ], "metricHeaders": [ {"name": "activeUsers", "type": "TYPE_INTEGER"}, {"name": "funnelStepCompletionRate", "type": "TYPE_INTEGER"}, {"name": "funnelStepAbandonments", "type": "TYPE_INTEGER"}, {"name": "funnelStepAbandonmentRate", "type": "TYPE_INTEGER"} ], "rows": [ { "dimensionValues": [ {"value": "1. First open/visit"}, {"value": "RESERVED_TOTAL"} ], "metricValues": [ {"value": "4621565"}, {"value": "0.27780178359495106"}, {"value": "3337686"}, {"value": "0.72219821640504889"} ] } ], "metadata": { "samplingMetadatas": [ {"samplesReadCount": "9917254", "samplingSpaceSize": "1162365416"} ] } }, "funnelVisualization": { "dimensionHeaders": [ {"name": "funnelStepName"} ], "metricHeaders": [ {"name": "activeUsers", "type": "TYPE_INTEGER"} ], "rows": [ { "dimensionValues": [ {"value": "1. First open/visit"} ], "metricValues": [ {"value": "4621565"} ] } ], "metadata": { "samplingMetadatas": [ {"samplesReadCount": "9917254", "samplingSpaceSize": "1162365416"} ] } }, "kind": "analyticsData#runFunnelReport" } ``` ``` -------------------------------- ### Execute and Print GA4 Reports Source: https://developers.google.com/analytics/devguides/reporting/data/v1/basics?hl=ja Demonstrates how to initialize the Analytics Data client, construct a runReport request with dimensions and metrics, and iterate through the response headers and row data. These examples require a valid GA4 property ID and the appropriate language-specific client library. ```php 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 def run_report(property_id="YOUR-GA4-PROPERTY-ID"): 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) ``` ```javascript async function runReport() { const [response] = await analyticsDataClient.runReport({ property: `properties/${propertyId}`, dimensions: [{ name: 'country' }], metrics: [{ name: 'activeUsers' }], dateRanges: [{ startDate: '2020-09-01', endDate: '2020-09-15' }] }); printRunReportResponse(response); } ``` -------------------------------- ### Run Analytics Report across languages Source: https://developers.google.com/analytics/devguides/reporting/data/v1/quickstart-client-libraries Demonstrates how to initialize the BetaAnalyticsDataClient and execute a runReport request to fetch active users by city. These examples require the GOOGLE_APPLICATION_CREDENTIALS environment variable to be set for authentication. ```python from google.analytics.data_v1beta import BetaAnalyticsDataClient from google.analytics.data_v1beta.types import RunReportRequest, Dimension, Metric, DateRange client = BetaAnalyticsDataClient() request = RunReportRequest( property=f"properties/{property_id}", dimensions=[Dimension(name="city")], metrics=[Metric(name="activeUsers")], date_ranges=[DateRange(start_date="2020-03-31", end_date="today")], ) response = client.run_report(request) for row in response.rows: print(row.dimension_values[0].value, row.metric_values[0].value) ``` ```javascript const {BetaAnalyticsDataClient} = require('@google-analytics/data'); const analyticsDataClient = new BetaAnalyticsDataClient(); async function runReport() { const [response] = await analyticsDataClient.runReport({ property: `properties/${propertyId}`, dateRanges: [{ startDate: '2020-03-31', endDate: 'today' }], dimensions: [{ name: 'city' }], metrics: [{ name: 'activeUsers' }], }); response.rows.forEach((row) => { console.log(row.dimensionValues[0], row.metricValues[0]); }); } runReport(); ``` ```csharp using Google.Analytics.Data.V1Beta; BetaAnalyticsDataClient client = BetaAnalyticsDataClient.Create(); RunReportRequest request = new RunReportRequest { Property = "properties/" + propertyId, Dimensions = { new Dimension { Name = "city" } }, Metrics = { new Metric { Name = "activeUsers" } }, DateRanges = { new DateRange { StartDate = "2020-03-31", EndDate = "today" } }, }; RunReportResponse response = client.RunReport(request); foreach (Row row in response.Rows) { Console.WriteLine("{0}, {1}", row.DimensionValues[0].Value, row.MetricValues[0].Value); } ``` -------------------------------- ### Run Report with PHP Source: https://developers.google.com/analytics/devguides/reporting/data/v1/basics?hl=vi This PHP code snippet demonstrates how to use the Google Analytics Data API client library to run a report. It specifies dimensions, metrics, and date ranges, and then prints the response. Ensure the Google Analytics client library for PHP is installed. ```php "properties/" . $property_id, 'dimensions' => [new Dimension(['name' => 'country'])] , 'metrics' => [new Metric(['name' => 'activeUsers'])] , 'date_ranges' => [new DateRange(['start_date' => '2020-09-01', 'end_date' => '2020-09-15'])] , ]); $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; } } run_report_example(); ``` -------------------------------- ### Run Report with Python Source: https://developers.google.com/analytics/devguides/reporting/data/v1/basics?hl=vi This Python code snippet demonstrates how to use the Google Analytics Data API client library to run a report. It specifies dimensions, metrics, and date ranges, and then prints the response. Ensure the google-analytics-data library is installed. ```python from google.analytics.data_v1beta import BetaAnalyticsDataClient from google.analytics.data_v1beta.types import ( DateRange, Dimension, Metric, MetricType, RunReportRequest, ) def run_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) def run_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) def print_run_report_response(response): """Prints results of a runReport call.""" print(f"{response.row_count} rows received") for dimensionHeader in response.dimension_headers: print(f"Dimension header name: {dimensionHeader.name}") for metricHeader in response.metric_headers: metric_type = MetricType(metricHeader.type_).name print(f"Metric header name: {metricHeader.name} ({metric_type})") print("Report result:") for rowIdx, row in enumerate(response.rows): print(f"\nRow {rowIdx}") for i, dimension_value in enumerate(row.dimension_values): dimension_name = response.dimension_headers[i].name print(f"{dimension_name}: {dimension_value.value}") for i, metric_value in enumerate(row.metric_values): metric_name = response.metric_headers[i].name print(f"{metric_name}: {metric_value.value}") run_sample() ``` -------------------------------- ### Run Report with Pagination (Python) Source: https://developers.google.com/analytics/devguides/reporting/data/v1/basics?hl=he Executes a report using the Google Analytics Data API v1 with specified dimensions, metrics, and pagination settings. This example utilizes the Python client library and demonstrates how to set the limit and offset for paginated results. ```python from google.analytics.data_v1beta import BetaAnalyticsDataClient from google.analytics.data_v1beta.types import DateRange, Dimension, Metric, RunReportRequest client = BetaAnalyticsDataClient() request = RunReportRequest( property="properties/YOUR_PROPERTY_ID", dimensions=[ Dimension(name="firstUserSource"), Dimension(name="firstUserMedium"), Dimension(name="firstUserCampaignName"), ], metrics=[ Metric(name="sessions"), Metric(name="keyEvents"), Metric(name="totalRevenue"), ], date_ranges=[ DateRange(start_date="350daysAgo", end_date="yesterday") ], limit=100000, offset=100000, ) response = client.run_report(request) ```