This is an overview of the capabilities [Realtime Reporting API Method](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runRealtimeReport.md.txt) of the Google Analytics Data
API v1. See the [API Reference](https://developers.google.com/analytics/devguides/reporting/data/v1/rest.md.txt).

**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
metrics](https://developers.google.com/analytics/devguides/reporting/data/v1/realtime-api-schema) compared to the [Core Reporting](https://developers.google.com/analytics/devguides/reporting/data/v1/basics.md.txt)
functionality of the Data API v1.

## Shared features with core reports

Realtime report requests have the same semantics with Core report requests for
many shared features. For example [pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics.md.txt#pagination), [Dimension
Filters](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#filter) and [User
Properties](https://developers.google.com/analytics/devguides/reporting/data/v1/advanced#user-scoped_custom_dimensions), behave the same in Realtime
reports as Core reports. Familiarize yourself with the [overview of the
Core Reporting functionality of the Data API v1](https://developers.google.com/analytics/devguides/reporting/data/v1/basics), 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 a [RunRealtimeReportRequest](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runRealtimeReport.md.txt#request-body) object. We recommend
starting with these request parameters:

- At least one valid entry in the [dimensions](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/Dimension.md.txt) field.
- At least one valid entry in the [metrics](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/Metric.md.txt) field.

Here is a sample request with the recommended fields.

### HTTP

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

### Java

[google-analytics-data/src/main/java/com/google/analytics/data/samples/RunRealtimeReportSample.java](https://github.com/googleanalytics/java-docs-samples/blob/main/google-analytics-data/src/main/java/com/google/analytics/data/samples/RunRealtimeReportSample.java) [Open in Cloud Shell](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleanalytics/java-docs-samples&page=editor&open_in_editor=google-analytics-data/src/main/java/com/google/analytics/data/samples/RunRealtimeReportSample.java "Open this sample or repository in the Google Cloud Shell Editor") [View on GitHub](https://github.com/googleanalytics/java-docs-samples/blob/main/google-analytics-data/src/main/java/com/google/analytics/data/samples/RunRealtimeReportSample.java)

```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;

/**
 * Google Analytics Data API sample application demonstrating the creation of a realtime report.
 *
 * <p>See
 * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runRealtimeReport
 * for more information.
 *
 * <p>Before you start the application, please review the comments starting with "TODO(developer)"
 * and update the code to use correct values.
 *
 * <p>To run this sample using Maven:
 *
 * <pre>{@code
 * cd google-analytics-data
 * mvn compile exec:java -Dexec.mainClass="com.google.analytics.data.samples.RunRealtimeReportSample"
 * }</pre>
 */
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());
    }
  }
}
```

### PHP

[google-analytics-data/src/run_realtime_report.php](https://github.com/googleanalytics/php-docs-samples/blob/main/google-analytics-data/src/run_realtime_report.php) [Open in Cloud Shell](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleanalytics/php-docs-samples&page=editor&open_in_editor=google-analytics-data/src/run_realtime_report.php "Open this sample or repository in the Google Cloud Shell Editor") [View on GitHub](https://github.com/googleanalytics/php-docs-samples/blob/main/google-analytics-data/src/run_realtime_report.php)

```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;

/**
 * Runs a realtime report on a Google Analytics 4 property.
 * @param string $propertyId Your GA-4 Property ID
 */
function run_realtime_report(string $propertyId)
{
    // Create an instance of the Google Analytics Data API client library.
    $client = new BetaAnalyticsDataClient();

    // Make an API call.
    $request = (new RunRealtimeReportRequest())
        ->setProperty('properties/' . $propertyId)
        ->setDimensions([new Dimension(['name' => 'country'])])
        ->setMetrics([new Metric(['name' => 'activeUsers'])]);
    $response = $client->runRealtimeReport($request);

    printRunRealtimeReportResponse($response);
}

/**
 * Print results of a runRealtimeReport call.
 * @param RunRealtimeReportResponse $response
 */
function printRunRealtimeReportResponse(RunRealtimeReportResponse $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) {
        printf(
            '%s %s' . PHP_EOL,
            $row->getDimensionValues()[0]->getValue(),
            $row->getMetricValues()[0]->getValue()
        );
    }
}
```

### Python

[google-analytics-data/run_realtime_report.py](https://github.com/googleanalytics/python-docs-samples/blob/main/google-analytics-data/run_realtime_report.py) [Open in Cloud Shell](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleanalytics/python-docs-samples&page=editor&open_in_editor=google-analytics-data/run_realtime_report.py "Open this sample or repository in the Google Cloud Shell Editor") [View on GitHub](https://github.com/googleanalytics/python-docs-samples/blob/main/google-analytics-data/run_realtime_report.py)

```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

[google-analytics-data/run_realtime_report.js](https://github.com/googleanalytics/nodejs-docs-samples/blob/main/google-analytics-data/run_realtime_report.js) [Open in Cloud Shell](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleanalytics/nodejs-docs-samples&page=editor&open_in_editor=google-analytics-data/run_realtime_report.js "Open this sample or repository in the Google Cloud Shell Editor") [View on GitHub](https://github.com/googleanalytics/nodejs-docs-samples/blob/main/google-analytics-data/run_realtime_report.js)

```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}`,
      );
    });
  }
```

> [!NOTE]
> **Note:** Dimensions are not required in API requests.

## Report response

The [Realtime Report
Response](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runRealtimeReport#response-body) of the
API request is primarily a header and rows. The header consists of
[DimensionHeaders](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DimensionHeader.md.txt) and [MetricHeaders](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/MetricHeader.md.txt) which list the columns in the Report. Each row
consists of [DimensionValues](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/Row.md.txt#FIELDS.dimension_values) and
[MetricValues](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/Row.md.txt#FIELDS.metric_values) 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 preceding sample request:

```json
    {
      "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](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/Dimension.md.txt) 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 [Realtime
Dimensions](https://developers.google.com/analytics/devguides/reporting/data/v1/realtime-api-schema#dimensions) for a full list of API Dimension
names available in realtime requests.

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

### HTTP

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

### Java

[google-analytics-data/src/main/java/com/google/analytics/data/samples/RunRealtimeReportWithMultipleDimensionsSample.java](https://github.com/googleanalytics/java-docs-samples/blob/main/google-analytics-data/src/main/java/com/google/analytics/data/samples/RunRealtimeReportWithMultipleDimensionsSample.java) [Open in Cloud Shell](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleanalytics/java-docs-samples&page=editor&open_in_editor=google-analytics-data/src/main/java/com/google/analytics/data/samples/RunRealtimeReportWithMultipleDimensionsSample.java "Open this sample or repository in the Google Cloud Shell Editor") [View on GitHub](https://github.com/googleanalytics/java-docs-samples/blob/main/google-analytics-data/src/main/java/com/google/analytics/data/samples/RunRealtimeReportWithMultipleDimensionsSample.java)

```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;

/**
 * Google Analytics Data API sample application demonstrating the creation of a realtime report.
 *
 * <p>See
 * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runRealtimeReport
 * for more information.
 *
 * <p>Before you start the application, please review the comments starting with "TODO(developer)"
 * and update the code to use correct values.
 *
 * <p>To run this sample using Maven:
 *
 * <pre>{@code
 * cd google-analytics-data
 * mvn compile exec:java -Dexec.mainClass="com.google.analytics.data.samples.RunRealtimeReportWithMultipleDimensionsSample"
 * }</pre>
 */
public class RunRealtimeReportWithMultipleDimensionsSample {

  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

[google-analytics-data/src/run_realtime_report_with_multiple_dimensions.php](https://github.com/googleanalytics/php-docs-samples/blob/main/google-analytics-data/src/run_realtime_report_with_multiple_dimensions.php) [Open in Cloud Shell](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleanalytics/php-docs-samples&page=editor&open_in_editor=google-analytics-data/src/run_realtime_report_with_multiple_dimensions.php "Open this sample or repository in the Google Cloud Shell Editor") [View on GitHub](https://github.com/googleanalytics/php-docs-samples/blob/main/google-analytics-data/src/run_realtime_report_with_multiple_dimensions.php)

```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;

/**
 * Runs a realtime report on a Google Analytics 4 property.
 * @param string $propertyId Your GA-4 Property ID
 */
function run_realtime_report_with_multiple_dimensions(string $propertyId)
{
    // Create an instance of the Google Analytics Data API client library.
    $client = new BetaAnalyticsDataClient();

    // Make an API call.
    $request = (new RunRealtimeReportRequest())
        ->setProperty('properties/' . $propertyId)
        ->setDimensions([
            new Dimension(['name' => 'country']),
            new Dimension(['name' => 'city']),
        ])
        ->setMetrics([new Metric(['name' => 'activeUsers'])]);
    $response = $client->runRealtimeReport($request);

    printRunRealtimeReportWithMultipleDimensionsResponse($response);
}

/**
 * Print results of a runRealtimeReport call.
 * @param RunRealtimeReportResponse $response
 */
function printRunRealtimeReportWithMultipleDimensionsResponse(RunRealtimeReportResponse $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) {
        printf(
            '%s %s' . PHP_EOL,
            $row->getDimensionValues()[0]->getValue(),
            $row->getMetricValues()[0]->getValue()
        );
    }
}
```

### Python

[google-analytics-data/run_realtime_report_with_multiple_dimensions.py](https://github.com/googleanalytics/python-docs-samples/blob/main/google-analytics-data/run_realtime_report_with_multiple_dimensions.py) [Open in Cloud Shell](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleanalytics/python-docs-samples&page=editor&open_in_editor=google-analytics-data/run_realtime_report_with_multiple_dimensions.py "Open this sample or repository in the Google Cloud Shell Editor") [View on GitHub](https://github.com/googleanalytics/python-docs-samples/blob/main/google-analytics-data/run_realtime_report_with_multiple_dimensions.py)

```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

[google-analytics-data/run_realtime_report_with_multiple_dimensions.js](https://github.com/googleanalytics/nodejs-docs-samples/blob/main/google-analytics-data/run_realtime_report_with_multiple_dimensions.js) [Open in Cloud Shell](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleanalytics/nodejs-docs-samples&page=editor&open_in_editor=google-analytics-data/run_realtime_report_with_multiple_dimensions.js "Open this sample or repository in the Google Cloud Shell Editor") [View on GitHub](https://github.com/googleanalytics/nodejs-docs-samples/blob/main/google-analytics-data/run_realtime_report_with_multiple_dimensions.js)

```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');

  // 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: ${metricHeader.name} (${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.

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

## Metrics

[Metrics](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/Metric.md.txt) are quantitative measurements of
event data for your website or app. In a report request, you can specify one
or more metrics. See [Realtime Metrics](https://developers.google.com/analytics/devguides/reporting/data/v1/realtime-api-schema.md.txt#metrics) for a
full list of API Metric names available in requests.

For example, this request will show the two metrics grouped by the dimension
`unifiedScreenName`:

### HTTP

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

### Java

[google-analytics-data/src/main/java/com/google/analytics/data/samples/RunRealtimeReportWithMultipleMetricsSample.java](https://github.com/googleanalytics/java-docs-samples/blob/main/google-analytics-data/src/main/java/com/google/analytics/data/samples/RunRealtimeReportWithMultipleMetricsSample.java) [Open in Cloud Shell](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleanalytics/java-docs-samples&page=editor&open_in_editor=google-analytics-data/src/main/java/com/google/analytics/data/samples/RunRealtimeReportWithMultipleMetricsSample.java "Open this sample or repository in the Google Cloud Shell Editor") [View on GitHub](https://github.com/googleanalytics/java-docs-samples/blob/main/google-analytics-data/src/main/java/com/google/analytics/data/samples/RunRealtimeReportWithMultipleMetricsSample.java)

```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;

/**
 * Google Analytics Data API sample application demonstrating the creation of a realtime report.
 *
 * <p>See
 * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runRealtimeReport
 * for more information.
 *
 * <p>Before you start the application, please review the comments starting with "TODO(developer)"
 * and update the code to use correct values.
 *
 * <p>To run this sample using Maven:
 *
 * <pre>{@code
 * cd google-analytics-data
 * mvn compile exec:java -Dexec.mainClass="com.google.analytics.data.samples.RunRealtimeReportWithMultipleMetricsSample"
 * }</pre>
 */
public class RunRealtimeReportWithMultipleMetricsSample {

  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

[google-analytics-data/src/run_realtime_report_with_multiple_metrics.php](https://github.com/googleanalytics/php-docs-samples/blob/main/google-analytics-data/src/run_realtime_report_with_multiple_metrics.php) [Open in Cloud Shell](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleanalytics/php-docs-samples&page=editor&open_in_editor=google-analytics-data/src/run_realtime_report_with_multiple_metrics.php "Open this sample or repository in the Google Cloud Shell Editor") [View on GitHub](https://github.com/googleanalytics/php-docs-samples/blob/main/google-analytics-data/src/run_realtime_report_with_multiple_metrics.php)

```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;

/**
 * Runs a realtime report on a Google Analytics 4 property.
 * @param string $propertyId Your GA-4 Property ID
 */
function run_realtime_report_with_multiple_metrics(string $propertyId)
{
    // Create an instance of the Google Analytics Data API client library.
    $client = new BetaAnalyticsDataClient();

    // Make an API call.
    $request = (new RunRealtimeReportRequest())
        ->setProperty('properties/' . $propertyId)
        ->setDimensions([new Dimension(['name' => 'unifiedScreenName'])])
        ->setMetrics([
            new Metric(['name' => 'screenPageViews']),
            new Metric(['name' => 'keyEvents']),
        ]);
    $response = $client->runRealtimeReport($request);

    printRunRealtimeReportWithMultipleMetricsResponse($response);
}

/**
 * Print results of a runRealtimeReport call.
 * @param RunRealtimeReportResponse $response
 */
function printRunRealtimeReportWithMultipleMetricsResponse(RunRealtimeReportResponse $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) {
        printf(
            '%s %s' . PHP_EOL,
            $row->getDimensionValues()[0]->getValue(),
            $row->getMetricValues()[0]->getValue()
        );
    }
}
```

### Python

[google-analytics-data/run_realtime_report_with_multiple_metrics.py](https://github.com/googleanalytics/python-docs-samples/blob/main/google-analytics-data/run_realtime_report_with_multiple_metrics.py) [Open in Cloud Shell](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleanalytics/python-docs-samples&page=editor&open_in_editor=google-analytics-data/run_realtime_report_with_multiple_metrics.py "Open this sample or repository in the Google Cloud Shell Editor") [View on GitHub](https://github.com/googleanalytics/python-docs-samples/blob/main/google-analytics-data/run_realtime_report_with_multiple_metrics.py)

```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

[google-analytics-data/run_realtime_report_with_multiple_metrics.js](https://github.com/googleanalytics/nodejs-docs-samples/blob/main/google-analytics-data/run_realtime_report_with_multiple_metrics.js) [Open in Cloud Shell](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleanalytics/nodejs-docs-samples&page=editor&open_in_editor=google-analytics-data/run_realtime_report_with_multiple_metrics.js "Open this sample or repository in the Google Cloud Shell Editor") [View on GitHub](https://github.com/googleanalytics/nodejs-docs-samples/blob/main/google-analytics-data/run_realtime_report_with_multiple_metrics.js)

```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 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: ${metricHeader.name} (${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.

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

## Minute ranges

In a realtime report request, you can use the
[minuteRanges](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runRealtimeReport.md.txt#body.request_body.FIELDS.minute_ranges)
field to specify [Minute
Ranges](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runRealtimeReport#MinuteRange) of 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.

> [!NOTE]
> **Note:** Standard and 360 Analytics properties have different limits on the maximum minute range that can be used in a realtime query. See [Minute Ranges](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runRealtimeReport.md.txt#MinuteRange) for the current limits.

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

- Range #1: starting 4 minutes ago until the present moment.
- Range #2: starting 29 minutes ago until 25 minutes ago (inclusively).

### HTTP

```console
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

[google-analytics-data/src/main/java/com/google/analytics/data/samples/RunRealtimeReportWithMinuteRangesSample.java](https://github.com/googleanalytics/java-docs-samples/blob/main/google-analytics-data/src/main/java/com/google/analytics/data/samples/RunRealtimeReportWithMinuteRangesSample.java) [Open in Cloud Shell](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleanalytics/java-docs-samples&page=editor&open_in_editor=google-analytics-data/src/main/java/com/google/analytics/data/samples/RunRealtimeReportWithMinuteRangesSample.java "Open this sample or repository in the Google Cloud Shell Editor") [View on GitHub](https://github.com/googleanalytics/java-docs-samples/blob/main/google-analytics-data/src/main/java/com/google/analytics/data/samples/RunRealtimeReportWithMinuteRangesSample.java)

```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;

/**
 * Google Analytics Data API sample application demonstrating the creation of a realtime report.
 *
 * <p>See
 * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runRealtimeReport
 * for more information.
 *
 * <p>Before you start the application, please review the comments starting with "TODO(developer)"
 * and update the code to use correct values.
 *
 * <p>To run this sample using Maven:
 *
 * <pre>{@code
 * cd google-analytics-data
 * mvn compile exec:java -Dexec.mainClass="com.google.analytics.data.samples.RunRealtimeReportWithMinuteRangesSample"
 * }</pre>
 */
public class RunRealtimeReportWithMinuteRangesSample {

  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

[google-analytics-data/src/run_realtime_report_with_minute_ranges.php](https://github.com/googleanalytics/php-docs-samples/blob/main/google-analytics-data/src/run_realtime_report_with_minute_ranges.php) [Open in Cloud Shell](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleanalytics/php-docs-samples&page=editor&open_in_editor=google-analytics-data/src/run_realtime_report_with_minute_ranges.php "Open this sample or repository in the Google Cloud Shell Editor") [View on GitHub](https://github.com/googleanalytics/php-docs-samples/blob/main/google-analytics-data/src/run_realtime_report_with_minute_ranges.php)

```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;

/**
 * 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.
 * @param string $propertyId Your GA-4 Property ID
 */
function run_realtime_report_with_minute_ranges(string $propertyId)
{
    // Create an instance of the Google Analytics Data API client library.
    $client = new BetaAnalyticsDataClient();

    // Make an API call.
    $request = (new RunRealtimeReportRequest())
        ->setProperty('properties/' . $propertyId)
        ->setMetrics([
            new Metric(['name' => 'activeUsers']),
        ])
        ->setMinuteRanges([
            new MinuteRange(['name' => '0-4 minutes ago', 'start_minutes_ago' => 4]),
            new MinuteRange(['name' => '25-29 minutes ago', 'start_minutes_ago' => 29, 'end_minutes_ago' => 25]),
        ]);
    $response = $client->runRealtimeReport($request);

    printRunRealtimeReportWithMinuteRangesResponse($response);
}

/**
 * Print results of a runRealtimeReport call.
 * @param RunRealtimeReportResponse $response
 */
function printRunRealtimeReportWithMinuteRangesResponse(RunRealtimeReportResponse $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) {
        printf(
            '%s %s' . PHP_EOL,
            $row->getDimensionValues()[0]->getValue(),
            $row->getMetricValues()[0]->getValue()
        );
    }
}
```

### Python

[google-analytics-data/run_realtime_report_with_minute_ranges.py](https://github.com/googleanalytics/python-docs-samples/blob/main/google-analytics-data/run_realtime_report_with_minute_ranges.py) [Open in Cloud Shell](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleanalytics/python-docs-samples&page=editor&open_in_editor=google-analytics-data/run_realtime_report_with_minute_ranges.py "Open this sample or repository in the Google Cloud Shell Editor") [View on GitHub](https://github.com/googleanalytics/python-docs-samples/blob/main/google-analytics-data/run_realtime_report_with_minute_ranges.py)

```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

[google-analytics-data/run_realtime_report_with_minute_ranges.js](https://github.com/googleanalytics/nodejs-docs-samples/blob/main/google-analytics-data/run_realtime_report_with_minute_ranges.js) [Open in Cloud Shell](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleanalytics/nodejs-docs-samples&page=editor&open_in_editor=google-analytics-data/run_realtime_report_with_minute_ranges.js "Open this sample or repository in the Google Cloud Shell Editor") [View on GitHub](https://github.com/googleanalytics/nodejs-docs-samples/blob/main/google-analytics-data/run_realtime_report_with_minute_ranges.js)

```javascript
  // 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: ${metricHeader.name} (${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 the `dateRange`
dimension added to the report response automatically as a result of querying
multiple minute ranges.

```json
  {
    "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"
  }
```