Create a Realtime Report (original) (raw)

Skip to main content

Create a Realtime Report

This is an overview of the capabilities Realtime Reporting API Methodof the Google Analytics Data API v1. For a detailed reference of the API, see theAPI Reference.

Events appear in realtime reports seconds after they have been sent to the Google Analytics. Realtime reports show events and usage data for the periods of time ranging from the present moment to 30 minutes ago (up to 60 minutes for Google Analytics 360 properties) and can be used for applications such as live counters of visitors on your website.

Realtime reports support a limited subset of dimensions and metricscompared to the Core Reporting functionality of the Data API v1.

Realtime report requests have the same semantics with Core report requests for many shared features. For example pagination, Dimension Filtersand User Properties, behave the same in Realtime Reports as Core Reports. Please familiarize yourself with theoverview of the Core Reporting functionality of the Data API v1, as the remainder of this document will focus on the features specific to the Realtime report requests.

Report Request

To request realtime reports, you can construct aRunRealtimeReportRequestobject. We recommend starting with these request parameters:

Here is a sample request with the recommended fields.

HTTP

POST https://analyticsdata.googleapis.com/v1beta/properties/GA_PROPERTY_ID:runRealtimeReport
{
  "dimensions": [{ "name": "country" }],
  "metrics": [{ "name": "activeUsers" }]
}

Java

import com.google.analytics.data.v1beta.BetaAnalyticsDataClient; 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.RunRealtimeReportRequest; import com.google.analytics.data.v1beta.RunRealtimeReportResponse;

/**

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());
}

} }

PHP

use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient; use Google\Analytics\Data\V1beta\Dimension; use Google\Analytics\Data\V1beta\Metric; use Google\Analytics\Data\V1beta\MetricType; use Google\Analytics\Data\V1beta\RunRealtimeReportRequest; use Google\Analytics\Data\V1beta\RunRealtimeReportResponse;

/**

}

/**

}

Python

from google.analytics.data_v1beta import BetaAnalyticsDataClient from google.analytics.data_v1beta.types import ( Dimension, Metric, RunRealtimeReportRequest, )

from run_report import print_run_report_response

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_realtime_report(property_id)

def run_realtime_report(property_id="YOUR-GA4-PROPERTY-ID"): """Runs a realtime report on a Google Analytics 4 property.""" client = BetaAnalyticsDataClient()

request = RunRealtimeReportRequest(
    property=f"properties/{property_id}",
    dimensions=[Dimension(name="country")],
    metrics=[Metric(name="activeUsers")],
)
response = client.run_realtime_report(request)
print_run_report_response(response)

Node.js

/**

// 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: <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mrow><mi>m</mi><mi>e</mi><mi>t</mi><mi>r</mi><mi>i</mi><mi>c</mi><mi>H</mi><mi>e</mi><mi>a</mi><mi>d</mi><mi>e</mi><mi>r</mi><mi mathvariant="normal">.</mi><mi>n</mi><mi>a</mi><mi>m</mi><mi>e</mi></mrow><mo stretchy="false">(</mo></mrow><annotation encoding="application/x-tex">{metricHeader.name} (</annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord"><span class="mord mathnormal">m</span><span class="mord mathnormal">e</span><span class="mord mathnormal">t</span><span class="mord mathnormal" style="margin-right:0.02778em;">r</span><span class="mord mathnormal">i</span><span class="mord mathnormal">cHe</span><span class="mord mathnormal">a</span><span class="mord mathnormal">d</span><span class="mord mathnormal" style="margin-right:0.02778em;">er</span><span class="mord">.</span><span class="mord mathnormal">nam</span><span class="mord mathnormal">e</span></span><span class="mopen">(</span></span></span></span>{metricHeader.type}) ); });

console.log('Report result:');
response.rows.forEach(row => {
  console.log(
    `${row.dimensionValues[0].value}, ${row.metricValues[0].value}`
  );
});

}

Report Response

The Realtime Report Responseof the API request is primarily a header and rows. The header consists ofDimensionHeaders and MetricHeaderswhich list the columns in the Report. Each row consists of DimensionValuesand MetricValues for the columns in the report. The ordering of columns is consistent in the request, the header, and every row.

Here is a sample response for the sample request above:

{
  "dimensionHeaders": [
    {
      "name": "country"
    }
  ],
  "metricHeaders": [
    {
      "name": "activeUsers",
      "type": "TYPE_INTEGER"
    }
  ],
  "rows": [
    {
      "dimensionValues": [
        {
          "value": "Japan"
        }
      ],
      "metricValues": [
        {
          "value": "2541"
        }
      ]
    },
    {
      "dimensionValues": [
        {
          "value": "France"
        }
      ],
      "metricValues": [
        {
          "value": "12"
        }
      ]
    }
  ],
  "rowCount": 2
}

Dimensions

Dimensions describe and group event data for your website or app. The city dimension, for example, indicates the city ("Paris" or "New York") from which each event originated. In a report request, you can specify zero or more dimensions. See the Realtime Dimensionsfor a full list of API Dimension names available in realtime requests.

For example, this request groups Active Users in two dimension columns:

HTTP

POST https://analyticsdata.googleapis.com/v1beta/property/GA_PROPERTY_ID:runRealtimeReport
  {
    "dimensions": [
      {
        "name": "country"
      },
      {
        "name": "city"
      }
    ],
    "metrics": [{ "name": "activeUsers" }]
  }

Java

import com.google.analytics.data.v1beta.BetaAnalyticsDataClient; import com.google.analytics.data.v1beta.Dimension; import com.google.analytics.data.v1beta.Metric; import com.google.analytics.data.v1beta.RunRealtimeReportRequest; import com.google.analytics.data.v1beta.RunRealtimeReportResponse;

/**

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"; sampleRunRealtimeReportWithMultipleDimensions(propertyId); }

// Runs a realtime report on a Google Analytics 4 property. static void sampleRunRealtimeReportWithMultipleDimensions(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")) .addDimensions(Dimension.newBuilder().setName(("city"))) .addMetrics(Metric.newBuilder().setName("activeUsers")) .build();

  // Make the request.
  RunRealtimeReportResponse response = analyticsData.runRealtimeReport(request);
  // Prints the response using a method in RunRealtimeReportSample.java
  RunRealtimeReportSample.printRunRealtimeReportResponse(response);
}

} }

PHP

use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient; use Google\Analytics\Data\V1beta\Dimension; use Google\Analytics\Data\V1beta\Metric; use Google\Analytics\Data\V1beta\MetricType; use Google\Analytics\Data\V1beta\RunRealtimeReportRequest; use Google\Analytics\Data\V1beta\RunRealtimeReportResponse;

/**

}

/**

}

Python

from google.analytics.data_v1beta import BetaAnalyticsDataClient from google.analytics.data_v1beta.types import ( Dimension, Metric, RunRealtimeReportRequest, )

from run_report import print_run_report_response

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_realtime_report_with_multiple_dimensions(property_id)

def run_realtime_report_with_multiple_dimensions(property_id="YOUR-GA4-PROPERTY-ID"): """Runs a realtime report on a Google Analytics 4 property.""" client = BetaAnalyticsDataClient()

request = RunRealtimeReportRequest(
    property=f"properties/{property_id}",
    dimensions=[Dimension(name="country"), Dimension(name="city")],
    metrics=[Metric(name="activeUsers")],
)
response = client.run_realtime_report(request)
print_run_report_response(response)

Node.js

/**

// 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. const analyticsDataClient = new BetaAnalyticsDataClient();

// Runs a realtime report on a Google Analytics 4 property. async function runRealtimeReportWithMultipleDimensions() { const [response] = await analyticsDataClient.runRealtimeReport({ property: properties/${propertyId}, dimensions: [ { name: 'country', }, { name: 'city', }, ], metrics: [ { name: 'activeUsers', }, ], }); printRunReportResponse(response); }

runRealtimeReportWithMultipleDimensions();

// 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: <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mrow><mi>m</mi><mi>e</mi><mi>t</mi><mi>r</mi><mi>i</mi><mi>c</mi><mi>H</mi><mi>e</mi><mi>a</mi><mi>d</mi><mi>e</mi><mi>r</mi><mi mathvariant="normal">.</mi><mi>n</mi><mi>a</mi><mi>m</mi><mi>e</mi></mrow><mo stretchy="false">(</mo></mrow><annotation encoding="application/x-tex">{metricHeader.name} (</annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord"><span class="mord mathnormal">m</span><span class="mord mathnormal">e</span><span class="mord mathnormal">t</span><span class="mord mathnormal" style="margin-right:0.02778em;">r</span><span class="mord mathnormal">i</span><span class="mord mathnormal">cHe</span><span class="mord mathnormal">a</span><span class="mord mathnormal">d</span><span class="mord mathnormal" style="margin-right:0.02778em;">er</span><span class="mord">.</span><span class="mord mathnormal">nam</span><span class="mord mathnormal">e</span></span><span class="mopen">(</span></span></span></span>{metricHeader.type}) ); });

console.log('Report result:');
response.rows.forEach(row => {
  console.log(
    `${row.dimensionValues[0].value}, ${row.metricValues[0].value}`
  );
});

}

As a sample, a row in the report response could contain the following. This row means there are 47 Active Users for your website or app with events from Cape Town, South Africa in the last 30 minutes.

"rows": [
...
{
  "dimensionValues": [
    {
      "value": "South Africa"
    },
    {
      "value": "Cape Town"
    }
  ],
  "metricValues": [
    {
      "value": "47"
    }
  ]
},
...
],

Metrics

Metrics are quantitative measurements of event data for your website or app. In a report request, you can specify one or more metrics. See the Realtime Metrics for a full list of API Metric names available in requests.

For example, this request will show the two metrics grouped by the dimensionunifiedScreenName:

HTTP

POST https://analyticsdata.googleapis.com/v1beta/property/GA_PROPERTY_ID:runRealtimeReport
  {
    "dimensions": [{ "name": "unifiedScreenName" }],
    "metrics": [
      {
        "name": "screenPageViews"
      },
      {
        "name": "keyEvents"
      }
    ],
  }

Java

import com.google.analytics.data.v1beta.BetaAnalyticsDataClient; import com.google.analytics.data.v1beta.Dimension; import com.google.analytics.data.v1beta.Metric; import com.google.analytics.data.v1beta.RunRealtimeReportRequest; import com.google.analytics.data.v1beta.RunRealtimeReportResponse;

/**

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"; sampleRunRealtimeReportWithMultipleMetrics(propertyId); }

// Runs a realtime report on a Google Analytics 4 property. static void sampleRunRealtimeReportWithMultipleMetrics(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("unifiedScreenName")) .addMetrics(Metric.newBuilder().setName(("screenPageViews"))) .addMetrics(Metric.newBuilder().setName("keyEvents")) .build();

  // Make the request.
  RunRealtimeReportResponse response = analyticsData.runRealtimeReport(request);
  // Prints the response using a method in RunRealtimeReportSample.java
  RunRealtimeReportSample.printRunRealtimeReportResponse(response);
}

} }

PHP

use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient; use Google\Analytics\Data\V1beta\Dimension; use Google\Analytics\Data\V1beta\Metric; use Google\Analytics\Data\V1beta\MetricType; use Google\Analytics\Data\V1beta\RunRealtimeReportRequest; use Google\Analytics\Data\V1beta\RunRealtimeReportResponse;

/**

}

/**

}

Python

from google.analytics.data_v1beta import BetaAnalyticsDataClient from google.analytics.data_v1beta.types import ( Dimension, Metric, RunRealtimeReportRequest, )

from run_report import print_run_report_response

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_realtime_report_with_multiple_metrics(property_id)

def run_realtime_report_with_multiple_metrics(property_id="YOUR-GA4-PROPERTY-ID"): """Runs a realtime report on a Google Analytics 4 property.""" client = BetaAnalyticsDataClient()

request = RunRealtimeReportRequest(
    property=f"properties/{property_id}",
    dimensions=[Dimension(name="unifiedScreenName")],
    metrics=[Metric(name="screenPageViews"), Metric(name="keyEvents")],
)
response = client.run_realtime_report(request)
print_run_report_response(response)

Node.js

/**

// 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 runRealtimeReportWithMultipleMetrics() { const [response] = await analyticsDataClient.runRealtimeReport({ // The property parameter value must be in the form properties/1234 // where 1234 is a GA4 property Id. property: properties/${propertyId}, dimensions: [ { name: 'unifiedScreenName', }, ], metrics: [ { name: 'screenPageViews', }, { name: 'keyEvents', }, ], }); printRunReportResponse(response); }

runRealtimeReportWithMultipleMetrics();

// 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: <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mrow><mi>m</mi><mi>e</mi><mi>t</mi><mi>r</mi><mi>i</mi><mi>c</mi><mi>H</mi><mi>e</mi><mi>a</mi><mi>d</mi><mi>e</mi><mi>r</mi><mi mathvariant="normal">.</mi><mi>n</mi><mi>a</mi><mi>m</mi><mi>e</mi></mrow><mo stretchy="false">(</mo></mrow><annotation encoding="application/x-tex">{metricHeader.name} (</annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord"><span class="mord mathnormal">m</span><span class="mord mathnormal">e</span><span class="mord mathnormal">t</span><span class="mord mathnormal" style="margin-right:0.02778em;">r</span><span class="mord mathnormal">i</span><span class="mord mathnormal">cHe</span><span class="mord mathnormal">a</span><span class="mord mathnormal">d</span><span class="mord mathnormal" style="margin-right:0.02778em;">er</span><span class="mord">.</span><span class="mord mathnormal">nam</span><span class="mord mathnormal">e</span></span><span class="mopen">(</span></span></span></span>{metricHeader.type}) ); });

console.log('Report result:');
response.rows.forEach(row => {
  console.log(
    `${row.dimensionValues[0].value}, ${row.metricValues[0].value}`
  );
});

}

As a sample, a row in report response could contain the following. This row means that for the page title (web) or screen name (app) of main_menu, there were 257 views and 72 key events in last 30 minutes.

"rows": [
...
{
  "dimensionValues": [
    {
      "value": "main_menu"
    }
  ],
  "metricValues": [
    {
      "value": "257"
    },
    {
      "value": "72"
    }
  ]
},
...
],

Minute Ranges

In a realtime report request, you can use the minuteRangesfield to specify Minute Rangesof event data to read. Up to two separate minute ranges can be used in a query. If a minute range specification is not present in a query, a single minute range for the last 30 minutes will be used.

For example, the request below will show the Active Users count for two separate minute ranges:

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,
      }
    ],
  }

Java

import com.google.analytics.data.v1beta.BetaAnalyticsDataClient; import com.google.analytics.data.v1beta.Metric; import com.google.analytics.data.v1beta.MinuteRange; import com.google.analytics.data.v1beta.RunRealtimeReportRequest; import com.google.analytics.data.v1beta.RunRealtimeReportResponse;

/**

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"; sampleRunRealtimeReportWithMinuteRanges(propertyId); }

// Runs a realtime report on a Google Analytics 4 property. static void sampleRunRealtimeReportWithMinuteRanges(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) .addMetrics(Metric.newBuilder().setName(("activeUsers"))) .addMinuteRanges( MinuteRange.newBuilder().setName("0-4 minutes ago").setStartMinutesAgo(4)) .addMinuteRanges( MinuteRange.newBuilder() .setName("25-29 minutes ago") .setEndMinutesAgo(29) .setEndMinutesAgo(25)) .build();

  // Make the request.
  RunRealtimeReportResponse response = analyticsData.runRealtimeReport(request);
  // Prints the response using a method in RunRealtimeReportSample.java
  RunRealtimeReportSample.printRunRealtimeReportResponse(response);
}

} }

PHP

use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient; use Google\Analytics\Data\V1beta\Metric; use Google\Analytics\Data\V1beta\MetricType; use Google\Analytics\Data\V1beta\MinuteRange; use Google\Analytics\Data\V1beta\RunRealtimeReportRequest; use Google\Analytics\Data\V1beta\RunRealtimeReportResponse;

/**

}

/**

}

Python

from google.analytics.data_v1beta import BetaAnalyticsDataClient from google.analytics.data_v1beta.types import ( Metric, MinuteRange, RunRealtimeReportRequest, )

from run_report import print_run_report_response

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_realtime_report_with_minute_ranges(property_id)

def run_realtime_report_with_minute_ranges(property_id="YOUR-GA4-PROPERTY-ID"): """Runs a realtime report on a Google Analytics 4 property. Dimensions field is omitted in the query, which results in total values of active users returned for each minute range in the report.

Note the `dateRange` dimension added to the report response automatically
as a result of querying multiple minute ranges.
"""
client = BetaAnalyticsDataClient()

request = RunRealtimeReportRequest(
    property=f"properties/{property_id}",
    metrics=[Metric(name="activeUsers")],
    minute_ranges=[
        MinuteRange(name="0-4 minutes ago", start_minutes_ago=4),
        MinuteRange(
            name="25-29 minutes ago", start_minutes_ago=29, end_minutes_ago=25
        ),
    ],
)
response = client.run_realtime_report(request)
print_run_report_response(response)

Node.js

// TODO(developer): Uncomment this variable and replace with your // Google Analytics 4 property ID before running the sample. // propertyId = 'YOUR-GA4-PROPERTY-ID';

// Imports the Google Analytics Data API client library. const {BetaAnalyticsDataClient} = require('@google-analytics/data');

// Initialize client that will be used to send requests. This client only // needs to be created once, and can be reused for multiple requests. const analyticsDataClient = new BetaAnalyticsDataClient();

// Runs a report using two date ranges. async function runRealtimeReportWithMinuteRanges() { const [response] = await analyticsDataClient.runRealtimeReport({ property: properties/${propertyId}, minuteRanges: [ { name: '0-4 minutes ago', startMinutesAgo: 4, endMinutesAgo: 0, }, { name: '25-29 minutes ago', startMinutesAgo: 29, endMinutesAgo: 25, }, ], metrics: [ { name: 'activeUsers', }, ], }); printRunReportResponse(response); }

runRealtimeReportWithMinuteRanges();

// 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: <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mrow><mi>m</mi><mi>e</mi><mi>t</mi><mi>r</mi><mi>i</mi><mi>c</mi><mi>H</mi><mi>e</mi><mi>a</mi><mi>d</mi><mi>e</mi><mi>r</mi><mi mathvariant="normal">.</mi><mi>n</mi><mi>a</mi><mi>m</mi><mi>e</mi></mrow><mo stretchy="false">(</mo></mrow><annotation encoding="application/x-tex">{metricHeader.name} (</annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord"><span class="mord mathnormal">m</span><span class="mord mathnormal">e</span><span class="mord mathnormal">t</span><span class="mord mathnormal" style="margin-right:0.02778em;">r</span><span class="mord mathnormal">i</span><span class="mord mathnormal">cHe</span><span class="mord mathnormal">a</span><span class="mord mathnormal">d</span><span class="mord mathnormal" style="margin-right:0.02778em;">er</span><span class="mord">.</span><span class="mord mathnormal">nam</span><span class="mord mathnormal">e</span></span><span class="mopen">(</span></span></span></span>{metricHeader.type}) ); });

console.log('Report result:');
response.rows.forEach(row => {
  console.log(
    `${row.dimensionValues[0].value}, ${row.metricValues[0].value}`
  );
});

}

The following is a complete sample response for the query. Note thedateRange dimension added to the report response automatically as a result of querying multiple minute ranges.

  {
    "dimensionHeaders": [
      {
        "name": "dateRange"
      }
    ],
    "metricHeaders": [
      {
        "name": "activeUsers",
        "type": "TYPE_INTEGER"
      }
    ],
    "rows": [
      {
        "dimensionValues": [
          {
            "value": "0-4 minutes ago"
          }
        ],
        "metricValues": [
          {
            "value": "16"
          }
        ]
      },
      {
        "dimensionValues": [
          {
            "value": "25-29 minutes ago"
          }
        ],
        "metricValues": [
          {
            "value": "14"
          }
        ]
      }
    ],
    "rowCount": 2,
    "kind": "analyticsData#runRealtimeReport"
  }

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-05-15 UTC.