### RunReportRequest Example Source: https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/Row This example shows the dimensions and metrics that can be included in a RunReportRequest. ```json { "dimensions": [ { "name": "eventName" }, { "name": "countryId" } ], "metrics": [ { "name": "eventCount" } ] } ``` -------------------------------- ### Retrieve Account Summaries - GET Request Example Source: https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1beta/accountSummaries/list Example of a GET request to retrieve account summaries. Supports optional pageSize and pageToken for pagination. Requires specific OAuth scopes. ```http GET https://analyticsadmin.googleapis.com/v1beta/accountSummaries?pageSize=200 ``` -------------------------------- ### gtag.js Example: select_promotion Event with Item Parameters Source: https://developers.google.com/analytics/devguides/collection/ga4/reference/events This example demonstrates how to send a 'select_promotion' event using gtag.js, including detailed item parameters for a selected product. ```javascript gtag("event", "select_promotion", { currency: "USD", creative_name: "Summer Banner", creative_slot: "featured_app_1", promotion_id: "P_12345", promotion_name: "Summer Sale", items: [ { item_id: "SKU_12345", item_name: "Stan and Friends Tee", affiliation: "Google Merchandise Store", coupon: "SUMMER_FUN", creative_name: "summer_banner2", creative_slot: "featured_app_1", discount: 2.22, index: 0, item_brand: "Google", item_category: "Apparel", item_category2: "Adult", item_category3: "Shirts", item_category4: "Crew", item_category5: "Short sleeve", item_list_id: "related_products", item_list_name: "Related Products", item_variant: "green", location_id: "ChIJIQBpAG2ahYAR_6128GcTUEo", price: 10.01, promotion_id: "P_12345", promotion_name: "Summer Sale", google_business_vertical: "retail", quantity: 3 } ], }); ``` -------------------------------- ### Run Pivot Report in PHP Source: https://developers.google.com/analytics/devguides/reporting/data/v1/pivots Use the PHP client library to run a pivot report. This example builds a report of session counts by country, pivoted by the browser dimension. Ensure the client library is installed and configured. ```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\OrderBy; use Google\Analytics\Data\V1beta\OrderBy\DimensionOrderBy; use Google\Analytics\Data\V1beta\OrderBy\MetricOrderBy; use Google\Analytics\Data\V1beta\Pivot; use Google\Analytics\Data\V1beta\RunPivotReportRequest; use Google\Analytics\Data\V1beta\RunPivotReportResponse; /** * Runs a pivot query to build a report of session counts by country, * pivoted by the browser dimension. * @param string $propertyId Your GA-4 Property ID */ function run_pivot_report(string $propertyId) { // Create an instance of the Google Analytics Data API client library. $client = new BetaAnalyticsDataClient(); // Make an API call. $request = (new RunPivotReportRequest()) ->setProperty('properties/' . $propertyId) ->setDateRanges([new DateRange([ 'start_date' => '2021-01-01', 'end_date' => '2021-01-30', ]), ]) ->setPivots([ new Pivot([ 'field_names' => ['country'], 'limit' => 250, 'order_bys' => [new OrderBy([ 'dimension' => new DimensionOrderBy([ 'dimension_name' => 'country', ]), ])], ]), new Pivot([ 'field_names' => ['browser'], 'offset' => 3, 'limit' => 3, 'order_bys' => [new OrderBy([ 'metric' => new MetricOrderBy([ 'metric_name' => 'sessions', ]), 'desc' => true, ])], ]), ]) ->setMetrics([new Metric(['name' => 'sessions'])]) ->setDimensions([ new Dimension(['name' => 'country']), new Dimension(['name' => 'browser']), ]); $response = $client->runPivotReport($request); printPivotReportResponse($response); } /** * Print results of a runPivotReport call. * @param RunPivotReportResponse $response */ function printPivotReportResponse(RunPivotReportResponse $response) { print 'Report result: ' . PHP_EOL; foreach ($response->getRows() as $row) { printf( '%s %s' . PHP_EOL, $row->getDimensionValues()[0]->getValue(), $row->getMetricValues()[0]->getValue() ); } } run_pivot_report.php ``` -------------------------------- ### Example Event with Parameters Source: https://developers.google.com/analytics/devguides/collection/ga4/event-parameters An example of sending a 'screen_view' event with 'app_name' and 'screen_name' parameters. Ensure custom parameters like these are registered in Google Analytics for reporting. ```javascript gtag('event', 'screen_view', { 'app_name': 'myAppName', 'screen_name': 'Home' }); ``` -------------------------------- ### PivotHeaders Example Source: https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/RunPivotReportResponse This example demonstrates how pivotHeaders are structured in the response based on the provided pivot request. It shows dimension values for each pivot. ```json "pivotHeaders" : [{ "dimensionHeaders": [{ "dimensionValues": [ { "value": "United Kingdom" }, { "value": "London" } ] }, { "dimensionValues": [ { "value": "Japan" }, { "value": "Osaka" } ] }] },{ "dimensionHeaders": [{ "dimensionValues": [{ "value": "session_start" }] }, { "dimensionValues": [{ "value": "scroll" }] }] }] ``` -------------------------------- ### Filter Examples for properties.list Source: https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1beta/properties/list Examples of filter expressions used to narrow down the properties returned by the API. ```text | Filter | Description | |-----------------------------|-------------------------------------------| | parent:accounts/123 | The account with account id: 123. | | parent:properties/123 | The property with property id: 123. | | ancestor:accounts/123 | The account with account id: 123. | | firebase_project:project-id | The firebase project with id: project-id. | | firebase_project:123 | The firebase project with number: 123. | ``` -------------------------------- ### Log tutorial_begin Event Source: https://developers.google.com/analytics/devguides/collection/ga4/reference/events Log the tutorial_begin event to signify the start of an on-boarding process. This event has no parameters. ```javascript gtag("event", "tutorial_begin"); ``` -------------------------------- ### Status Details Example Source: https://developers.google.com/analytics/devguides/reporting/data/v1/rest/Shared.Types/Operation An example of the details field within the Status type, showing an object with arbitrary fields and a '@type' URI. ```json { "id": 1234, "@type": "types.example.com/standard/id" } ``` -------------------------------- ### Measurement Protocol JSON Payload Example Source: https://developers.google.com/analytics/devguides/collection/protocol/ga4/sending-events This is an example of the JSON payload required for the Measurement Protocol request body. It includes the `app_instance_id` to identify a unique app installation and an `events` array with event details like name and parameters. ```json { "app_instance_id": "APP_INSTANCE_ID", "events": [ { "name": "login", "params": { "method": "Google", "session_id": "SESSION_ID", "engagement_time_msec": 100 } } ] } ``` -------------------------------- ### Run a report using the PHP client library Source: https://developers.google.com/analytics/devguides/reporting/data/v1/basics Demonstrates initializing the client and executing a report request in PHP. ```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', ]), ``` -------------------------------- ### List Google Analytics Accounts in Node.js Source: https://developers.google.com/analytics/devguides/config/admin/v1/quickstart-client-libraries Fetches and displays all Google Analytics accounts for the authenticated user. This example utilizes auto-pagination for handling multiple pages of results. Ensure the '@google-analytics/admin' package is installed and GOOGLE_APPLICATION_CREDENTIALS is set. ```javascript // Imports the Google Analytics Admin API client library. const analyticsAdmin = require('@google-analytics/admin'); // Using a default constructor instructs the client to use the credentials // specified in GOOGLE_APPLICATION_CREDENTIALS environment variable. const analyticsAdminClient = new analyticsAdmin.AnalyticsAdminServiceClient(); // Lists all Google Analytics accounts available to the authenticated user. async function listAccounts() { // Uses listAccounts() with no arguments to fetch all pages. For more // information on pagination in the Node.js library, see: // https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#auto-pagination const [response] = await analyticsAdminClient.listAccounts(); console.log('Accounts:'); for (const account of response) { console.log('Account name:', account.name); console.log('Display name:', account.displayName); console.log('Region code:', account.regionCode); console.log('Create time:', account.createTime.seconds); console.log('Update time:', account.updateTime.seconds); } } listAccounts(); ``` -------------------------------- ### Pivot Configuration with Sorting and Pagination Source: https://developers.google.com/analytics/devguides/reporting/data/v1/pivots Demonstrates configuring pivots with sorting using orderBys and implementing pagination with offset and limit. ```json "pivots": [ { "fieldNames": [ "country" ], "limit": 250, "orderBys": [ { "dimension": { "dimensionName": "country" } } ] }, { "fieldNames": [ "browser" ], "offset": 3, "limit": 3, "orderBys": [ { "metric": { "metricName": "sessions" }, "desc": true } ] } ], ... ``` -------------------------------- ### Run a report using the Java client library Source: https://developers.google.com/analytics/devguides/reporting/data/v1/basics Demonstrates creating a report request and printing the response using the BetaAnalyticsDataClient. ```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.DimensionHeader; import com.google.analytics.data.v1beta.Metric; import com.google.analytics.data.v1beta.MetricHeader; import com.google.analytics.data.v1beta.Row; import com.google.analytics.data.v1beta.RunReportRequest; import com.google.analytics.data.v1beta.RunReportResponse; /** * Google Analytics Data API sample application demonstrating the creation of a basic report. * *
See * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport * for more information. * *
Before you start the application, please review the comments starting with "TODO(developer)" * and update the code to use correct values. * *
To run this sample using Maven: * *
{@code
* cd google-analytics-data
* mvn compile exec:java -Dexec.mainClass="com.google.analytics.data.samples.RunReportSample"
* }
*/
public class RunReportSample {
public static void main(String... args) throws Exception {
/**
* TODO(developer): Replace this variable with your Google Analytics 4 property ID before
* running the sample.
*/
String propertyId = "YOUR-GA4-PROPERTY-ID";
sampleRunReport(propertyId);
}
// Runs a report of active users grouped by country.
static void sampleRunReport(String propertyId) throws Exception {
// Using a default constructor instructs the client to use the credentials
// specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.
try (BetaAnalyticsDataClient analyticsData = BetaAnalyticsDataClient.create()) {
RunReportRequest request =
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.
RunReportResponse response = analyticsData.runReport(request);
printRunResponseResponse(response);
}
}
// Prints results of a runReport call.
static void printRunResponseResponse(RunReportResponse response) {
System.out.printf("%s rows received%n", response.getRowsList().size());
for (DimensionHeader header : response.getDimensionHeadersList()) {
System.out.printf("Dimension header name: %s%n", header.getName());
}
for (MetricHeader header : response.getMetricHeadersList()) {
System.out.printf("Metric header name: %s (%s)%n", header.getName(), header.getType());
}
System.out.println("Report result:");
for (Row row : response.getRowsList()) {
System.out.printf(
"%s, %s%n", row.getDimensionValues(0).getValue(), row.getMetricValues(0).getValue());
}
}
}
```
--------------------------------
### Install Go Client Library
Source: https://developers.google.com/analytics/devguides/reporting/data/v1/client-libraries
Use this command to install the Go client library for Google Analytics Data API v1beta. Ensure you have Go installed and configured.
```go
go get google.golang.org/genproto/googleapis/analytics/data/v1beta
```
--------------------------------
### Log tutorial_complete Event
Source: https://developers.google.com/analytics/devguides/collection/ga4/reference/events
Log the tutorial_complete event to signify the completion of an on-boarding process. This event has no parameters.
```javascript
gtag("event", "tutorial_complete");
```
--------------------------------
### Install Go client library for Google Analytics Admin API
Source: https://developers.google.com/analytics/devguides/config/admin/v1/client-libraries
Use this command to install the Go client library for the Google Analytics Admin API. Ensure you have Go installed and configured.
```go
go get google.golang.org/genproto/googleapis/analytics/admin/v1beta
```
--------------------------------
### Pivot Configuration with Dimensions and Metrics
Source: https://developers.google.com/analytics/devguides/reporting/data/v1/pivots
Shows how to configure pivots using dimensions and metrics, including sorting by metric in descending order.
```json
"pivots": [
{
"fieldNames": [
"browser"
],
"limit": 5,
"orderBys": [
{
"metric": {
"metricName": "sessions"
},
"desc": true
}
]
},
{
"fieldNames": [
"country"
],
"limit": 250,
"orderBys": [
{
"dimension": {
"dimensionName": "country"
}
}
]
},
{
"fieldNames": [
"language"
],
"limit": 10
}
],
```
--------------------------------
### Run Pivot Report
Source: https://developers.google.com/analytics/devguides/reporting/data/v1/pivots
This example demonstrates how to construct a request to run a pivot report with specified date ranges, dimensions, metrics, and pivot configurations.
```APIDOC
## POST https://analyticsdata.googleapis.com/v1beta/properties/GA_PROPERTY_ID:runPivotReport
### Description
Runs a pivot report for the given property. This report is configured by specifying the dimensions, metrics, and pivot criteria.
### Method
POST
### Endpoint
https://analyticsdata.googleapis.com/v1beta/properties/GA_PROPERTY_ID:runPivotReport
### Parameters
#### Request Body
- **dateRanges** (array) - Required - A non-empty list of date ranges for the report. Each date range must have a `startDate` and `endDate`.
- **dimensions** (array) - Required - A non-empty list of dimensions to include in the report. Each dimension must have a `name`.
- **metrics** (array) - Required - A non-empty list of metrics to include in the report. Each metric must have a `name`.
- **pivots** (array) - Required - A non-empty list of pivot configurations. Each pivot must have `fieldNames` and can optionally include `limit`, `offset`, and `orderBys`.
### Request Example
```json
{
"dateRanges": [{ "startDate": "2020-09-01", "endDate": "2020-09-15" }],
"dimensions": [
{ "name": "browser" },
{ "name": "country" },
{ "name": "language" }
],
"metrics": [{ "name": "sessions" }],
"pivots": [
{
"fieldNames": [
"browser"
],
"limit": 5
},
{
"fieldNames": [
"country"
],
"limit": 250
},
{
"fieldNames": [
"language"
],
"limit": 15
}
]
}
```
### Response
#### Success Response (200)
- **pivotHeaders** (array) - Headers for the pivot tables.
- **dimensionHeaders** (array) - Headers for the dimension columns.
- **metricHeaders** (array) - Headers for the metric columns.
- **rows** (array) - Rows of data for the pivot report.
- **rowCount** (integer) - The total number of rows in the response.
- **metadata** (object) - Metadata about the report.
- **propertyQuota** (object) - Quotas for the property.
#### Response Example
```json
{
"pivotHeaders": [
{
"pivotRow": {
"dimensionValues": [
{ "value": "Chrome" },
{ "value": "United States" },
{ "value": "en-US" }
]
}
}
],
"dimensionHeaders": [
{ "name": "browser" },
{ "name": "country" },
{ "name": "language" }
],
"metricHeaders": [
{ "name": "sessions" }
],
"rows": [
{
"dimensionValues": [
{ "value": "Chrome" },
{ "value": "United States" },
{ "value": "en-US" }
],
"metricValues": [
{ "value": "1000" }
]
}
],
"rowCount": 1,
"metadata": {
"currencyCode": "USD",
"timeZone": "America/Los_Angeles"
},
"propertyQuota": {
"tokensPerDay": { "remainingTokenCount": 10000, "numerator": 1000, "denominator": 10000 },
"tokensPerHour": { "remainingTokenCount": 1000, "numerator": 100, "denominator": 1000 }
}
}
```
```
--------------------------------
### Row Data Example
Source: https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/Row
An example of a single row of report data, including dimension and metric values.
```json
"dimensionValues": [
{
"value": "in_app_purchase"
},
{
"value": "JP"
}
],
"metricValues": [
{
"value": "15"
}
]
```
--------------------------------
### get
Source: https://developers.google.com/analytics/devguides/reporting/data/v1/rest
Gets report metadata about a specific report task. Use this to retrieve details and status of an existing report task.
```APIDOC
## GET /v1alpha/{name=properties/*/reportTasks/*}
### Description
Gets report metadata about a specific report task.
### Method
GET
### Endpoint
/v1alpha/{name=properties/*/reportTasks/*}
```
--------------------------------
### Send tutorial_complete Event
Source: https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference/events
Signify the completion of the on-boarding process using this event. No parameters are suggested for this event.
```javascript
const measurementId = 'G-XXXXXXXXXX';
const apiSecret = 'See * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runRealtimeReport * for more information. * *
Before you start the application, please review the comments starting with "TODO(developer)" * and update the code to use correct values. * *
To run this sample using Maven: * *
{@code
* cd google-analytics-data
* mvn compile exec:java -Dexec.mainClass="com.google.analytics.data.samples.RunRealtimeReportSample"
* }
*/
public class RunRealtimeReportSample {
public static void main(String... args) throws Exception {
// TODO(developer): Replace with your Google Analytics 4 property ID before running the sample.
String propertyId = "YOUR-GA4-PROPERTY-ID";
sampleRunRealtimeReport(propertyId);
}
// Runs a realtime report on a Google Analytics 4 property.
static void sampleRunRealtimeReport(String propertyId) throws Exception {
// 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 (BetaAnalyticsDataClient analyticsData = BetaAnalyticsDataClient.create()) {
RunRealtimeReportRequest request =
RunRealtimeReportRequest.newBuilder()
.setProperty("properties/" + propertyId)
.addDimensions(Dimension.newBuilder().setName("country"))
.addMetrics(Metric.newBuilder().setName("activeUsers"))
.build();
// Make the request.
RunRealtimeReportResponse response = analyticsData.runRealtimeReport(request);
printRunRealtimeReportResponse(response);
}
}
// Prints results of a runRealReport call.
static void printRunRealtimeReportResponse(RunRealtimeReportResponse response) {
System.out.printf("%s rows received%n", response.getRowsList().size());
for (DimensionHeader header : response.getDimensionHeadersList()) {
System.out.printf("Dimension header name: %s%n", header.getName());
}
for (MetricHeader header : response.getMetricHeadersList()) {
System.out.printf("Metric header name: %s (%s)%n", header.getName(), header.getType());
}
System.out.println("Report result:");
for (Row row : response.getRowsList()) {
System.out.printf(
"%s, %s%n", row.getDimensionValues(0).getValue(), row.getMetricValues(0).getValue());
}
}
}
```
--------------------------------
### Example of a Refund Event with a Missing Comma
Source: https://developers.google.com/analytics/devguides/collection/ga4/validate-ecommerce
This example demonstrates a refund event where a trailing comma is missing after the 'transaction_id' parameter, which will cause Analytics to ignore the event.
```javascript
gtag("event", "refund", {
currency: "USD",
transaction_id: "T_12345" // Missing a trailing comma
value: 30.03,
coupon: "SUMMER_FUN",
shipping: 3.33,
tax: 1.11
});
```
--------------------------------
### sign_up
Source: https://developers.google.com/analytics/devguides/collection/ga4/reference/events
This event indicates that a user has signed up for an account. Use this event to understand the different behaviors of logged in and logged out users.
```APIDOC
## sign_up
### Description
This event indicates that a user has signed up for an account. Use this event to understand the different behaviors of logged in and logged out users.
### Parameters
#### Query Parameters
- **method** (string) - Optional - The method used for sign up.
### Request Example
```javascript
gtag("event", "sign_up", {
method: "Google"
});
```
```
--------------------------------
### Example Pivot Report Response Rows
Source: https://developers.google.com/analytics/devguides/reporting/data/v1/pivots
Each row in a pivot report response represents a single cell in the pivot table. This example shows dimension and metric values for two cells.
```json
"rows": [
{
"dimensionValues": [
{
"value": "Chrome"
},
{
"value": "United States"
},
{
"value": "English"
}
],
"metricValues": [
{
"value": "1"
}
]
},
{
"dimensionValues": [
{
"value": "Firefox"
},
{
"value": "Canada"
},
{
"value": "French"
}
],
"metricValues": [
{
"value": "3"
}
]
},
...
]
```
--------------------------------
### Run Realtime Report with Minute Ranges (HTTP)
Source: https://developers.google.com/analytics/devguides/reporting/data/v1/realtime-basics
This example shows how to make an HTTP POST request to the runRealtimeReport method, specifying two distinct minute ranges for active users.
```HTTP
POST https://analyticsdata.googleapis.com/v1beta/property/GA_PROPERTY_ID:runRealtimeReport
{
"metrics": [
{
"name": "activeUsers"
}
],
"minuteRanges": [
{
"name": "0-4 minutes ago",
"startMinutesAgo": 4,
},
{
"name": "25-29 minutes ago",
"startMinutesAgo": 29,
"endMinutesAgo": 25,
}
],
}
```
--------------------------------
### Automated Google Analytics setup process opt-out
Source: https://developers.google.com/analytics/devguides/config/admin
Manages the opt-out status for the automated Google Analytics setup process for a UA property. Supports setting and fetching the opt-out status.
```APIDOC
## Automated Google Analytics setup process opt-out (Alpha)
### Description
Manages the opt-out status for the automated Google Analytics setup process for a UA property. Supports setting and fetching the opt-out status.
### Methods
- `properties.setAutomatedGa4ConfigurationOptOut`
- `properties.fetchAutomatedGa4ConfigurationOptOut`
```
--------------------------------
### Run Pivot Report Request Example
Source: https://developers.google.com/analytics/devguides/reporting/data/v1/pivots
A sample request body for the runPivotReport method, including date ranges, dimensions, metrics, and pivot configurations.
```json
POST https://analyticsdata.googleapis.com/v1beta/properties/GA_PROPERTY_ID:runPivotReport
{
"dateRanges": [{ "startDate": "2020-09-01", "endDate": "2020-09-15" }],
"dimensions": [
{ "name": "browser" },
{ "name": "country" },
{ "name": "language" }
],
"metrics": [{ "name": "sessions" }],
"pivots": [
{
"fieldNames": [
"browser"
],
"limit": 5
},
{
"fieldNames": [
"country"
],
"limit": 250
},
{
"fieldNames": [
"language"
],
"limit": 15
}
]
}
```
--------------------------------
### Get Report Task Status Request
Source: https://developers.google.com/analytics/devguides/reporting/data/v1/report-tasks
Send a GET request to the `reportTasks.get` endpoint using the Report Task name to check its readiness state. The state changes from `CREATING` to `ACTIVE` upon completion.
```HTTP
GET https://analyticsdata.googleapis.com/v1alpha/properties/1234567/reportTasks/123
```
--------------------------------
### Run Realtime Report in JavaScript
Source: https://developers.google.com/analytics/devguides/reporting/data/v1/realtime-basics
Utilize the BetaAnalyticsDataClient to request realtime data. Ensure the property ID is correctly set and the necessary imports are included. This example fetches active users by country.
```javascript
/**
* TODO(developer): Uncomment this variable and replace with your GA4
* 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');
// Creates a client.
const analyticsDataClient = new BetaAnalyticsDataClient();
// Runs a realtime report on a Google Analytics 4 property.
async function runRealtimeReport() {
const [response] = await analyticsDataClient.runRealtimeReport({
property: `properties/${propertyId}`,
dimensions: [
{
name: 'country',
},
],
metrics: [
{
name: 'activeUsers',
},
],
});
printRunReportResponse(response);
}
runRealtimeReport();
// Prints results of a runReport call.
function printRunReportResponse(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}`,
);
});
}
```
--------------------------------
### HTTP Request to Get Data Sharing Settings
Source: https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1beta/accounts/getDataSharingSettings
Use this GET request to retrieve the data sharing settings for a specific Google Analytics account. The account name must be provided in the URL path.
```http
GET https://analyticsadmin.googleapis.com/v1beta/{name=accounts/*/dataSharingSettings}
```
--------------------------------
### Initiate Checkout Event
Source: https://developers.google.com/analytics/devguides/collection/ga4/ecommerce
Send a 'begin_checkout' event to track the start of the checkout process. This includes item details and an optional coupon.
```javascript
gtag("event", "begin_checkout", {
currency: "USD",
value: 30.03,
coupon: "SUMMER_FUN",
items: [
{
item_id: "SKU_12345",
item_name: "Stan and Friends Tee",
affiliation: "Google Merchandise Store",
coupon: "SUMMER_FUN",
discount: 2.22,
index: 0,
item_brand: "Google",
item_category: "Apparel",
item_category2: "Adult",
item_category3: "Shirts",
item_category4: "Crew",
item_category5: "Short sleeve",
item_list_id: "related_products",
item_list_name: "Related Products",
item_variant: "green",
location_id: "ChIJIQBpAG2ahYAR_6128GcTUEo",
price: 10.01,
google_business_vertical: "retail",
quantity: 3
}
]
});
```
--------------------------------
### Example Cohort Report Response
Source: https://developers.google.com/analytics/devguides/reporting/data/v1/advanced
This is an example response from the cohort report request. It includes dimension and metric headers, rows with cohort and retention data, and metadata. Use this structure to parse and visualize retention metrics.
```json
{
"dimensionHeaders": [{ "name": "cohort" },{ "name": "cohortNthDay" }],
"metricHeaders": [
{
"name": "cohortRetentionFraction",
"type": "TYPE_FLOAT"
}
]
,
"rows": [
{
"dimensionValues": [{ "value": "cohort_0" },{ "value": "0000" }],
"metricValues": [{ "value": "1" }]
},
{
"dimensionValues": [{ "value": "cohort_1" },{ "value": "0000" }],
"metricValues": [{ "value": "1" }]
},
{
"dimensionValues": [{ "value": "cohort_2" },{ "value": "0000" }],
"metricValues": [{ "value": "1" }]
},
{
"dimensionValues": [{ "value": "cohort_2" },{ "value": "0001" }],
"metricValues": [{ "value": "0.308" }]
},
{
"dimensionValues": [{ "value": "cohort_1" },{ "value": "0001" }],
"metricValues": [{ "value": "0.272" }]
},
{
"dimensionValues": [{ "value": "cohort_2" },{ "value": "0002" }],
"metricValues": [{ "value": "0.257" }]
},
{
"dimensionValues": [{ "value": "cohort_0" },{ "value": "0001" }],
"metricValues": [{ "value": "0.248" }]
},
{
"dimensionValues": [{ "value": "cohort_2" },{ "value": "0003" }],
"metricValues": [{ "value": "0.235" }]
},
{
"dimensionValues": [{ "value": "cohort_2" },{ "value": "0004" }],
"metricValues": [{ "value": "0.211" }]
},
{
"dimensionValues": [{ "value": "cohort_1" },{ "value": "0002" }],
"metricValues": [{ "value": "0.198" }]
},
{
"dimensionValues": [{ "value": "cohort_0" },{ "value": "0002" }],
"metricValues": [{ "value": "0.172" }]
},
{
"dimensionValues": [{ "value": "cohort_1" },{ "value": "0003" }],
"metricValues": [{ "value": "0.167" }]
},
{
"dimensionValues": [{ "value": "cohort_1" },{ "value": "0004" }],
"metricValues": [{ "value": "0.155" }]
},
{
"dimensionValues": [{ "value": "cohort_0" },{ "value": "0003" }],
"metricValues": [{ "value": "0.141" }]
},
{
"dimensionValues": [{ "value": "cohort_0" },{ "value": "0004" }],
"metricValues": [{ "value": "0.118" }]
}
],
"metadata": {},
"rowCount": 15
}
```
--------------------------------
### Example Weekly Cohort Report Response
Source: https://developers.google.com/analytics/devguides/reporting/data/v1/advanced
This is an example response for the weekly cohort report request, showing active users per cohort week for Russia and Mexico. It includes dimension and metric headers, rows of data, and metadata.
```json
{
"dimensionHeaders": [
{ "name": "cohort" },
{ "name": "cohortNthWeek" },
{ "name": "country" }
],
"metricHeaders": [
{ "name": "cohortActiveUsers", "type": "TYPE_INTEGER" }
],
"rows": [
{
"dimensionValues": [
{ "value": "cohort_0" },{ "value": "0000" },{ "value": "Russia" }
],
"metricValues": [{ "value": "105" }]
},
{
"dimensionValues": [
{ "value": "cohort_0" },{ "value": "0000" },{ "value": "Mexico" }
],
"metricValues": [{ "value": "98" }]
},
{
"dimensionValues": [
{ "value": "cohort_0" },{ "value": "0001" },{ "value": "Mexico" }
],
"metricValues": [{ "value": "35" }]
},
{
"dimensionValues": [
{ "value": "cohort_0" },{ "value": "0002" },{ "value": "Mexico" }
],
"metricValues": [{ "value": "24" }]
},
{
"dimensionValues": [
{ "value": "cohort_0" },{ "value": "0001" },{ "value": "Russia" }
],
"metricValues": [{ "value": "23" }]
},
{
"dimensionValues": [
{ "value": "cohort_0" },{ "value": "0004" },{ "value": "Mexico" }
],
"metricValues": [{ "value": "17" }]
},
{
"dimensionValues": [
{ "value": "cohort_0" },{ "value": "0003" },{ "value": "Mexico" }
],
"metricValues": [{ "value": "15" }]
},
{
"dimensionValues": [
{ "value": "cohort_0" },{ "value": "0005" },{ "value": "Mexico" }
],
"metricValues": [{ "value": "15" }]
},
{
"dimensionValues": [
{ "value": "cohort_0" },{ "value": "0002" },{ "value": "Russia" }
],
"metricValues": [{ "value": "3" }]
},
{
"dimensionValues": [
{ "value": "cohort_0" },{ "value": "0003" },{ "value": "Russia" }
],
"metricValues": [{ "value": "1" }]
},
{
"dimensionValues": [
{ "value": "cohort_0" },{ "value": "0004" },{ "value": "Russia" }
],
"metricValues": [{ "value": "1" }]
}
],
"metadata": {},
"rowCount": 11
}
```
--------------------------------
### get
Source: https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1beta/properties.dataStreams.measurementProtocolSecrets
Retrieves a specific measurement protocol secret.
```APIDOC
## GET properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets/{measurementProtocolSecret}
### Description
Lookup for a single MeasurementProtocolSecret.
### Method
GET
### Endpoint
`properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets/{measurementProtocolSecret}`
### Parameters
#### Path Parameters
* **property** (string) - Required - The name of the property.
* **dataStream** (string) - Required - The data stream the secret belongs to.
* **measurementProtocolSecret** (string) - Required - The ID of the measurement protocol secret to retrieve.
```
--------------------------------
### New Users by First User Default Channel Group Over Time
Source: https://developers.google.com/analytics/devguides/reporting/data/v1/predefined-reports
Query for new users broken down by their first user default channel group over a 28-day period. Useful for understanding initial acquisition channels.
```json
{
"pivots": [
{
"fieldNames": [
"date"
],
"orderBys": [
{
"dimension": {
"dimensionName": "date"
}
}
],
"limit": 28
},
{
"fieldNames": [
"firstUserDefaultChannelGroup"
],
"limit": 5
}
],
"dateRanges": [
{
"startDate": "28daysAgo",
"endDate": "yesterday"
}
],
"dimensions": [
{
"name": "date"
},
{
"name": "firstUserDefaultChannelGroup"
}
],
"metrics": [
{
"name": "newUsers"
}
]
}
```