You can use the [Data API](https://developers.google.com/analytics/devguides/reporting/data/v1.md.txt) or [Admin
API](https://developers.google.com/analytics/devguides/config/admin/v1) for this quickstart


Choose an API: [Data API](https://developers.google.com/analytics/devguides/reporting/data/v1/quickstart.md.txt "View this page for the Data API.") [Admin API](https://developers.google.com/analytics/devguides/config/admin/v1/quickstart.md.txt "View this page for the Admin API.")

<br />

You can authenticate with a [user
account](https://cloud.google.com/docs/authentication#user-accounts) or [service
account](https://cloud.google.com/docs/authentication#service-accounts):
Choose an account type: <button value="user" default="">User account</button> <button value="service">Service account</button>

In this quickstart, you create and send a
[`runReport`](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport.md.txt)
request.

Here's a summary of the steps:

1. Set up tools and access.
2. Enable the API.
3. Install an SDK.
4. Make an API call.

## Before you begin

1. [Install and initialize](https://cloud.google.com/sdk/docs/install) the gcloud
   CLI.

2. To generate [Application Default
   Credentials](https://cloud.google.com/docs/authentication/application-default-credentials)
   and give your account the necessary scopes, run the following:

   ```bash
   gcloud auth application-default login --scopes="https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/analytics.readonly"
   ```
3. In the [Google Analytics UI](https://analytics.google.com), grant your user
   account [access to a Google Analytics
   property](https://support.google.com/analytics/answer/9305788).

## Enable the Data API

To select or create a [Google Cloud
project](https://cloud.google.com/resource-manager/docs/creating-managing-projects),
and enable the API, click **Enable the Google Analytics
Data API v1**.
Enable the Google Analytics API

## Install an SDK

Install the SDK for your programming language.

### Java


[Java client library installation guide](https://github.com/googleapis/google-cloud-java/blob/main/java-analytics-data/README.md)

### PHP


[PHP client library installation guide](https://github.com/googleapis/php-analytics-data#installation)

### Python


[Python client library installation guide](https://github.com/googleapis/google-cloud-python/blob/main/packages/google-analytics-data/README.rst#installation)

### Node.js


[Node.js client library installation guide](https://googleapis.dev/nodejs/analytics-data/latest/index.html#installing-the-client-library)

### .NET


[.NET client library installation guide](https://www.nuget.org/packages/Google.Analytics.Data.V1Beta#package-manager)

### Ruby


[Ruby client library installation guide](https://github.com/googleapis/google-cloud-ruby/tree/main/google-analytics-data-v1beta#installation)

### Go


```
go get google.golang.org/genproto/googleapis/analytics/data/v1beta
```

<br />

### REST


Configure your environment variables by entering the following.

Replace <var translate="no">`PROJECT_ID`</var> with the ID of your project
and <var translate="no">`PROPERTY_ID`</var> with the ID of your Google Analytics property.

```bash
  export PROJECT_ID=`PROJECT_ID`
  export PROPERTY_ID=`PROPERTY_ID`
```

<br />

## Make an API call

To verify your setup and make an API call, run the following sample.

This sample calls the
[`runReport`](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport.md.txt)
method. The response lists active users for your property.

To install all the Analytics API code samples, see our [GitHub](https://github.com/googleanalytics).

### Java


[google-analytics-data/src/main/java/com/google/analytics/data/samples/QuickstartSample.java](https://github.com/googleanalytics/java-docs-samples/blob/main/google-analytics-data/src/main/java/com/google/analytics/data/samples/QuickstartSample.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/QuickstartSample.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/QuickstartSample.java)

```java
import com.google.analytics.data.v1beta.BetaAnalyticsDataClient;
import com.google.analytics.data.v1beta.DateRange;
import com.google.analytics.data.v1beta.Dimension;
import com.google.analytics.data.v1beta.Metric;
import com.google.analytics.data.v1beta.Row;
import com.google.analytics.data.v1beta.RunReportRequest;
import com.google.analytics.data.v1beta.RunReportResponse;

/**
 * Google Analytics Data API sample quickstart application.
 *
 * <p>This application demonstrates the usage of the Analytics Data API using service account
 * credentials.
 *
 * <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.QuickstartSample"
 * }</pre>
 */
public class QuickstartSample {

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

  // This is an example snippet that calls the Google Analytics Data API and runs a simple report
  // on the provided GA4 property id.
  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("city"))
              .addMetrics(Metric.newBuilder().setName("activeUsers"))
              .addDateRanges(DateRange.newBuilder().setStartDate("2020-03-31").setEndDate("today"))
              .build();

      // Make the request.
      RunReportResponse response = analyticsData.runReport(request);

      System.out.println("Report result:");
      // Iterate through every row of the API response.
      for (Row row : response.getRowsList()) {
        System.out.printf(
            "%s, %s%n", row.getDimensionValues(0).getValue(), row.getMetricValues(0).getValue());
      }
    }
  }
}
```

<br />

### PHP


[google-analytics-data/quickstart.php](https://github.com/googleanalytics/php-docs-samples/blob/main/google-analytics-data/quickstart.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/quickstart.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/quickstart.php)

```php
require 'vendor/autoload.php';

use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient;
use Google\Analytics\Data\V1beta\DateRange;
use Google\Analytics\Data\V1beta\Dimension;
use Google\Analytics\Data\V1beta\Metric;
use Google\Analytics\Data\V1beta\RunReportRequest;

/**
 * TODO(developer): Replace this variable with your Google Analytics 4
 *   property ID before running the sample.
 */
$property_id = 'YOUR-GA4-PROPERTY-ID';

// Using a default constructor instructs the client to use the credentials
// specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.
$client = new BetaAnalyticsDataClient();

// Make an API call.
$request = (new RunReportRequest())
    ->setProperty('properties/' . $property_id)
    ->setDateRanges([
        new DateRange([
            'start_date' => '2020-03-31',
            'end_date' => 'today',
        ]),
    ])
    ->setDimensions([new Dimension([
            'name' => 'city',
        ]),
    ])
    ->setMetrics([new Metric([
            'name' => 'activeUsers',
        ])
    ]);
$response = $client->runReport($request);

// Print results of an API call.
print 'Report result: ' . PHP_EOL;

foreach ($response->getRows() as $row) {
    print $row->getDimensionValues()[0]->getValue()
        . ' ' . $row->getMetricValues()[0]->getValue() . PHP_EOL;
}
```

<br />

### Python


[google-analytics-data/quickstart.py](https://github.com/googleanalytics/python-docs-samples/blob/main/google-analytics-data/quickstart.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/quickstart.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/quickstart.py)

```python
from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import (
    DateRange,
    Dimension,
    Metric,
    RunReportRequest,
)


def sample_run_report(property_id="YOUR-GA4-PROPERTY-ID"):
    """Runs a simple report on a Google Analytics 4 property."""
    # TODO(developer): Uncomment this variable and replace with your
    #  Google Analytics 4 property ID before running the sample.
    # property_id = "YOUR-GA4-PROPERTY-ID"

    # Using a default constructor instructs the client to use the credentials
    # specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.
    client = BetaAnalyticsDataClient()

    request = RunReportRequest(
        property=f"properties/{property_id}",
        dimensions=[Dimension(name="city")],
        metrics=[Metric(name="activeUsers")],
        date_ranges=[DateRange(start_date="2020-03-31", end_date="today")],
    )
    response = client.run_report(request)

    print("Report result:")
    for row in response.rows:
        print(row.dimension_values[0].value, row.metric_values[0].value)

```

<br />

### Node.js


[google-analytics-data/quickstart.js](https://github.com/googleanalytics/nodejs-docs-samples/blob/main/google-analytics-data/quickstart.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/quickstart.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/quickstart.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');

  // Using a default constructor instructs the client to use the credentials
  // specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.
  const analyticsDataClient = new BetaAnalyticsDataClient();

  // Runs a simple report.
  async function runReport() {
    const [response] = await analyticsDataClient.runReport({
      property: `properties/${propertyId}`,
      dateRanges: [
        {
          startDate: '2020-03-31',
          endDate: 'today',
        },
      ],
      dimensions: [
        {
          name: 'city',
        },
      ],
      metrics: [
        {
          name: 'activeUsers',
        },
      ],
    });

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

  runReport();
```

<br />

### .NET


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

```
using System;
using Google.Analytics.Data.V1Beta;

namespace AnalyticsSamples
{
    class QuickStart
    {
        static void SampleRunReport(string propertyId = "YOUR-GA4-PROPERTY-ID")
        {
            /**
             * TODO(developer): Uncomment this variable and replace with your
             *  Google Analytics 4 property ID before running the sample.
             */
            // propertyId = "YOUR-GA4-PROPERTY-ID";

            // Using a default constructor instructs the client to use the credentials
            // specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.
            BetaAnalyticsDataClient client = BetaAnalyticsDataClient.Create();

            // Initialize request argument(s)
            RunReportRequest request = new RunReportRequest
            {
                Property = "properties/" + propertyId,
                Dimensions = { new Dimension { Name = "city" } },
                Metrics = { new Metric { Name = "activeUsers" } },
                DateRanges =
                {
                    new DateRange { StartDate = "2020-03-31", EndDate = "today" },
                },
            };

            // Make the request
            RunReportResponse response = client.RunReport(request);

            Console.WriteLine("Report result:");
            foreach (Row row in response.Rows)
            {
                Console.WriteLine(
                    "{0}, {1}",
                    row.DimensionValues[0].Value,
                    row.MetricValues[0].Value
                );
            }
        }

        static int Main(string[] args)
        {
            if (args.Length > 0)
            {
                SampleRunReport(args[0]);
            }
            else
            {
                SampleRunReport();
            }
            return 0;
        }
    }
}
```

<br />

### REST


To send this request, run the curl command from the command line or
include the REST call in your application.

```bash
curl -X POST \
  -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
  -H "x-goog-user-project: ${PROJECT_ID}" \
  -H "Content-Type: application/json" \
  -d '
  {
    "dateRanges": [
      {
        "startDate": "2025-01-01",
        "endDate": "2025-02-01"
      }
    ],
    "dimensions": [
      {
        "name": "country"
      }
    ],
    "metrics": [
      {
        "name": "activeUsers"
      }
    ]
  }'  https://analyticsdata.googleapis.com/v1beta/properties/${PROPERTY_ID}:runReport
```

<br />

Here's a sample response in JSON:

```json
{
  "dimensionHeaders": [
    {
      "name": "country"
    }
  ],
  "metricHeaders": [
    {
      "name": "activeUsers",
      "type": "TYPE_INTEGER"
    }
  ],
  "rows": [
    {
      "dimensionValues": [
        {
          "value": "United States"
        }
      ],
      "metricValues": [
        {
          "value": "3242"
        }
      ]
    },
    {
      "dimensionValues": [
        {
          "value": "(not set)"
        }
      ],
      "metricValues": [
        {
          "value": "3015"
        }
      ]
    },
    {
      "dimensionValues": [
        {
          "value": "India"
        }
      ],
      "metricValues": [
        {
          "value": "805"
        }
      ]
    }
  ],
  "rowCount": 3,
  "metadata": {
    "currencyCode": "USD",
    "timeZone": "America/Los_Angeles"
  },
  "kind": "analyticsData#runReport"
}
```

## Next steps

- [Use Google Analytics AI agent skills](https://developers.google.com/analytics/devguides/agent-skills.md.txt) to install the `google-analytics-data-api-basics` skill for `runReport` workflows and dimension and metric compatibility checks.
- [Try the Google Analytics MCP server](https://developers.google.com/analytics/devguides/MCP.md.txt) to query live Google Analytics reports and property metadata in natural language.
- Explore the [Google Analytics Data API dimensions and metrics
  schema](https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema).