Take our developer survey. We want your feedback so we can learn how to improve Google Analytics, and make it an even better tool for you.

API Quickstart

This page shows you how to get started with the Google Analytics Data API V1 in your favorite programming language using the client Libraries.

Step 1. Enable the API

Click this button to create a new Cloud Platform project, automatically enable the Google Analytics Data API V1 and create the service account needed for this tutorial:

Enable the Google Analytics Data API V1

In resulting dialog click DOWNLOAD CLIENT CONFIGURATION and save the file credentials.json to your working directory.

Step 2. Add service account to the Google Analytics 4 property

Using a text editor, open the credentials.json file downloaded in the previous step and search for client_email field to obtain the service account email address that looks similar to:

quickstart@PROJECT-ID.iam.gserviceaccount.com

Use this email address to add a user to the Google Analytics 4 property you want to access via the Google Analytics Data API V1. For this tutorial only Read & Analyze permissions are needed.

Step 3. Configure authentication

This application demonstrates the usage of the Google Analytics Data API V1 using service account credentials.

Read more for instructions on creating and setting service account credentials for your application.

An easy way to provide service account credentials is by setting the GOOGLE_APPLICATION_CREDENTIALS environment variable, the API client will use the value of this variable to find the service account key JSON file.

To set the application credentials in this example, run the following command and use the path to the service account JSON file downloaded at Step 1:

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

For example:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/credentials.json"

Step 4. Install the client library

Java

If you are using Maven, add this to your pom.xml file:

<dependency>
  <groupId>com.google.analytics</groupId>
  <artifactId>google-analytics-data</artifactId>
  <version>0.1.0</version>
</dependency>

If you are using Gradle, add this to your dependencies
compile 'com.google.analytics:google-analytics-data:0.1.0'

Python

Install this library in a virtualenv using pip. virtualenv is a tool to create isolated Python environments. The basic problem it addresses is one of dependencies and versions, and indirectly permissions.

With virtualenv, it’s possible to install this library without needing system install permissions, and without clashing with the installed system dependencies.

pip install virtualenv
virtualenv 
source <your-env>/bin/activate
<your-env>/bin/pip install google-analytics-data

Node.js

npm install @google-analytics/data

Ruby

gem install google-analytics-data-v1alpha

Go

go get -u cloud.google.com/go/analytics/data/apiv1alpha

.NET

If you are using Package Manager, execute this command:

Install-Package Google.Analytics.Data.V1Alpha -Version 1.0.0-alpha01
If you are using .NET CLI, execute this command in your project's folder:
dotnet add package Google.Analytics.Data.V1Alpha --version 1.0.0-alpha01
You can directly include the library dependency to your project by adding this to your .NET project file:

<PackageReference Include="Google.Analytics.Data.V1Alpha" Version="1.0.0-alpha01" />

Make an API call

Now you can use the Google Analytics Data API to query a Google Analytics 4 property. Run the following code to perform your first call to the API:

Java


import com.google.analytics.data.v1alpha.AlphaAnalyticsDataClient;
import com.google.analytics.data.v1alpha.DateRange;
import com.google.analytics.data.v1alpha.Dimension;
import com.google.analytics.data.v1alpha.Entity;
import com.google.analytics.data.v1alpha.Metric;
import com.google.analytics.data.v1alpha.Row;
import com.google.analytics.data.v1alpha.RunReportRequest;
import com.google.analytics.data.v1alpha.RunReportResponse;

public class QuickstartSample {

  // 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 ga4PropertyId) throws Exception {
    // Instantiates a client using default credentials.
    // See https://cloud.google.com/docs/authentication/production for more information
    // about managing credentials.
    try (AlphaAnalyticsDataClient analyticsData = AlphaAnalyticsDataClient.create()) {
      RunReportRequest request = RunReportRequest.newBuilder()
          .setEntity(Entity.newBuilder().setPropertyId(ga4PropertyId))
          .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:");
      for (Row row : response.getRowsList()) {
        System.out.printf("%s, %s%n", row.getDimensionValues(0).getValue(),
            row.getMetricValues(0).getValue());
      }
    }
  }

  public static void main(String... args) throws Exception {
    // TODO(developer): Replace this variable with your GA4 property ID before running the sample.
    String ga4PropertyId = "GA4 PROPERTY ID";
    sampleRunReport(ga4PropertyId);
  }
}

Python

from google.analytics.data_v1alpha import AlphaAnalyticsDataClient
from google.analytics.data_v1alpha.types import DateRange
from google.analytics.data_v1alpha.types import Dimension
from google.analytics.data_v1alpha.types import Entity
from google.analytics.data_v1alpha.types import Metric
from google.analytics.data_v1alpha.types import RunReportRequest


def sample_run_report(property_id):
    """Runs a simple report on a Google Analytics App+Web property."""

    # Using a default constructor instructs the client to use the credentials
    # specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.
    client = AlphaAnalyticsDataClient()
    request = RunReportRequest(entity=Entity(property_id=property_id),
                               dimensions=[Dimension(name='city')],
                               metrics=[Metric(name='activeUsers')],
                               date_ranges=[DateRange(start_date='2020-03-31',
                                                      end_date='today')])
    response = client.run_report(request)

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


Node.js

  /**
   * 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 {AlphaAnalyticsDataClient} = require('@google-analytics/data');

  // Creates a client.
  const analyticsDataClient = new AlphaAnalyticsDataClient();

  // Runs a simple report.
  async function runReport() {
    const [response] = await analyticsDataClient.runReport({
      entity: {
        propertyId: 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();

.NET

using Google.Analytics.Data.V1Beta;
using Google.Api.Gax;
using System;

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

            /**
             * TODO(developer): Uncomment this variable and replace with a valid path to
             *  the credentials.json file for your service account downloaded from the
             *  Cloud Console.
             *  Otherwise, default service account credentials will be derived from
             *  the GOOGLE_APPLICATION_CREDENTIALS environment variable.
             */
            // credentialsJsonPath = "/path/to/credentials.json";

            BetaAnalyticsDataClient client;
            if(String.IsNullOrEmpty(credentialsJsonPath))
            {
              // Using a default constructor instructs the client to use the credentials
              // specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.
              client = BetaAnalyticsDataClient.Create();
            }
            else
            {
              // Explicitly use service account credentials by specifying
              // the private key file.
              client = new BetaAnalyticsDataClientBuilder
              {
                CredentialsPath = credentialsJsonPath
              }.Build();
            }

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

            // Make the request
            PagedEnumerable<RunReportResponse, DimensionHeader> response = client.RunReport(request);

            Console.WriteLine("Report result:");
            foreach(RunReportResponse page in response.AsRawResponses())
            {
              foreach(Row row in page.Rows)
              {
                  Console.WriteLine("{0}, {1}", row.DimensionValues[0].Value, row.MetricValues[0].Value);
              }
            }
        }
        static int Main(string[] args)
        {
            SampleRunReport();
            return 0;
        }
    }
}

Congratulations! You've sent your first request to the Google Analytics Data API.