# SkillPatch skill: google-analytics-data-api-basics

This skill provides guidance for interacting with the Google Analytics Data API v1beta, covering API enablement via the Google Cloud CLI, authentication using Application Default Credentials, and creating analytics reports. It supports multiple programming languages (Python, Java, PHP, Node.js, Go, .NET, Ruby) and helps agents query metrics and dimensions from Google Analytics properties.

You (the agent) were given this URL and asked to use this skill. This is a **public** skill — no SkillPatch account, API key, or prior setup is required. Two ways to use it:

**1. Use it right now** — the skill's complete file tree (SKILL.md + all reference files) is inlined below; read `SKILL.md` first, then follow it, consulting the other files as it directs.

**2. Install the exact package onto disk** (recommended if you can run a shell — this reproduces the skill byte-for-byte, including any binary assets that can't be inlined):

```bash
mkdir -p .claude/skills/google-analytics-data-api-basics
curl -sSL https://skillpatch.dev/install_skill/google-analytics-data-api-basics | tar -xz -C .claude/skills/
```

(`.claude/skills/` is Claude Code's convention; use whatever directory your agent loads skills from.)


---

## Skill files (8)

- `SKILL.md`
- `references/dotnet.md`
- `references/go.md`
- `references/java.md`
- `references/nodejs.md`
- `references/php.md`
- `references/python.md`
- `references/ruby.md`


### `SKILL.md`

````markdown
---
name: google-analytics-data-api-basics
metadata:
  category: GoogleAnalytics
description: >-
  Manages Google Analytics reporting data, enables the Analytics Data API via the Cloud CLI, and creates reports using the Google Analytics Data API (v1beta). Use when you need to interact with Google Analytics properties, run customized analytics reports, query metrics (like activeUsers, screenPageViews) and dimensions (like city, date), check metrics and dimensions compatibility, or verify API enablement.
---

# Getting Started with Google Analytics Data API

The Google Analytics Data API v1beta provides programmatic access to Google
Analytics report data. It allows you to build customized dashboards,
automate reporting workflows, and integrate Google Analytics data into your enterprise
applications.

## Enabling the API via Cloud CLI

Before making API calls, ensure the Google Analytics Data API is enabled in your
Google Cloud project.

If `gcloud` is not found, prompt the user to install the Google Cloud CLI before
running these commands.

1.  **Enable the API:** Use the Cloud CLI (`gcloud`) to enable
    `analyticsdata.googleapis.com`.

    ```bash
    gcloud services enable analyticsdata.googleapis.com --quiet
    ```

    *Why: Enabling the API ensures your Cloud project has the necessary quota
    and permissions allocated for running Google Analytics reports.*

2.  **Verify API Enablement:**

    ```bash
    gcloud services list --enabled --filter="analyticsdata.googleapis.com"
    ```

## Authentication

To authenticate your API requests, you must generate Application Default
Credentials (ADC) and give your account the necessary scopes. Run the following
command in your terminal:

```bash
gcloud auth application-default login --scopes="https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/analytics.readonly"
```

*Why: This configures ADC in your local environment with the required Cloud
Platform and Google Analytics read-only scopes, allowing the client library to
automatically authenticate your requests.*

## Creating a Data API Report (v1beta)

To create a report, use the official Google Analytics Data client library.
Always prefer the `v1beta` version of the API for stability and access to
current Google Analytics reporting capabilities.

> [!IMPORTANT] **Mandatory Agent Directive:** When the user selects or requires
> a specific programming language, read the corresponding client library setup
> reference guide in `references/` listed below.

### Supported Client Libraries

#### Python

If you need to install or set up the Google Analytics Data API client library
for Python, read the setup guide:

*   [Python Installation Reference](references/python.md) *(Package:
    `google-analytics-data`)*

#### Java

If you need to install or set up the Google Analytics Data API client library
for Java, read the setup guide:

*   [Java Installation Reference](references/java.md) *(Artifact:
    `com.google.cloud:google-cloud-analytics-data`)*

#### PHP

If you need to install or set up the Google Analytics Data API client library
for PHP, read the setup guide:

*   [PHP Installation Reference](references/php.md) *(Package:
    `google/analytics-data`)*

#### Node.js

If you need to install or set up the Google Analytics Data API client library
for Node.js, read the setup guide:

*   [Node.js Installation Reference](references/nodejs.md) *(Package:
    `@google-analytics/data`)*

#### Go

If you need to install or set up the Google Analytics Data API client library
for Go, read the setup guide:

*   [Go Installation Reference](references/go.md) *(Package:
    `cloud.google.com/go/analytics/data/apiv1beta`)*

#### .NET

If you need to install or set up the Google Analytics Data API client library
for .NET / C#, read the setup guide:

*   [.NET Installation Reference](references/dotnet.md) *(Package:
    `Google.Analytics.Data.V1Beta`)*

#### Ruby

If you need to install or set up the Google Analytics Data API client library
for Ruby, read the setup guide:

*   [Ruby Installation Reference](references/ruby.md) *(Gem:
    `google-analytics-data-v1beta`)*

> [!NOTE] **Additional Resources**: For further examples of calling the Data API
> with Java, PHP, Node.js, .NET, Python and REST, as well as hints on
> authentication with a service account, refer to the official
> [Data API Quickstart](https://developers.google.com/analytics/devguides/reporting/data/v1/quickstart).

### Python Quick Start

1.  **Install the Client Library:**

    ```bash
    pip install google-analytics-data
    ```

    If `pip` is not available, prompt the user to install `pip` before
    installing the client library.

2.  **Run a Report Request:** Below is a complete example demonstrating how to
    query a Google Analytics property for active users and sessions grouped by city and date.
    Replace `YOUR-PROPERTY-ID` with your actual Google Analytics property ID (e.g.,
    `1234567`).

    ```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: str):
        # Initialize the client.
        # Assumes Application Default Credentials (ADC) are configured in your environment.
        client = BetaAnalyticsDataClient()

        request = RunReportRequest(
            property=f"properties/{property_id}",
            dimensions=[
                Dimension(name="city"),
                Dimension(name="date")
            ],
            metrics=[
                Metric(name="activeUsers"),
                Metric(name="sessions")
            ],
            date_ranges=[
                DateRange(start_date="2026-05-01", end_date="today")
            ],
        )

        response = client.run_report(request)

        print(f"Report result for property {property_id}:")
        for row in response.rows:
            print(
                f"City: {row.dimension_values[0].value}, "
                f"Date: {row.dimension_values[1].value}, "
                f"Active Users: {row.metric_values[0].value}, "
                f"Sessions: {row.metric_values[1].value}"
            )

    if __name__ == "__main__":
        sample_run_report("YOUR-PROPERTY-ID")
    ```

    *Why: Using `BetaAnalyticsDataClient` and `RunReportRequest` ensures
    compatibility with the v1beta endpoint and strongly typed request
    validation.*

## Metrics and Dimensions Schema

When constructing your `RunReportRequest`, you must use valid API names for
dimensions and metrics. Refer to the official
[Data API Schema documentation](https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema)
for the complete, authoritative list of available fields.

### Commonly Used Dimensions

Dimensions represent categorical attributes of your data.

*   `city`: The town or city of the user.
*   `country`: The country of the user.
*   `date`: The date of the event, formatted as YYYYMMDD.
*   `deviceCategory`: The category of mobile device (e.g., desktop, mobile,
    tablet).
*   `eventName`: The name of the triggered event.
*   `pageTitle`: The title of the web page.

### Commonly Used Metrics

Metrics represent quantitative measurements.

*   `activeUsers`: The number of active users.
*   `eventCount`: The total count of events.
*   `sessions`: The total number of sessions.
*   `screenPageViews`: The number of app screens or web pages viewed.
*   `totalRevenue`: The total revenue from purchases, subscriptions, and
    advertising.

### Metrics and Dimensions Compatibility Check

Some dimensions and metrics cannot be queried together in the same report
request. If you encounter an `INVALID_ARGUMENT` error regarding incompatible
fields, verify your field combinations For programmatic access to the Data API
schema, use `getMetadata()`. To programmatically check the compatibility of
specific dimension and metric combinations before running a report, use the
`checkCompatibility()` method.

```python
from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import CheckCompatibilityRequest, Compatibility, Dimension, Metric

def sample_check_compatibility(property_id: str):
    client = BetaAnalyticsDataClient()

    # Define the dimensions and metrics you want to query together.
    # For example, checking if 'itemDescription' (an e-commerce dimension)
    # is compatible with 'activeUsers' and 'totalRevenue'.
    request = CheckCompatibilityRequest(
        property=f"properties/{property_id}",
        dimensions=[
            Dimension(name="itemDescription"),
            Dimension(name="date")
        ],
        metrics=[
            Metric(name="activeUsers"),
            Metric(name="totalRevenue")
        ],
    )
    response = client.check_compatibility(request)

    print(f"Compatibility check for property {property_id}:")
    for dim in response.dimension_compatibilities:
        is_compatible = dim.compatibility == Compatibility.COMPATIBLE
        print(f"Dimension '{dim.dimension_metadata.api_name}' is compatible: {is_compatible}")

    for metric in response.metric_compatibilities:
        is_compatible = metric.compatibility == Compatibility.COMPATIBLE
        print(f"Metric '{metric.metric_metadata.api_name}' is compatible: {is_compatible}")

if __name__ == "__main__":
    sample_check_compatibility("YOUR-PROPERTY-ID")
```

````


### `references/dotnet.md`

````markdown
# Google Analytics Data API .NET Client Library Installation

This guide provides specific instructions for installing and setting up the
Google Analytics Data API (v1beta) client library for .NET / C#.

## Prerequisites

*   **.NET SDK:** .NET Core 3.1, .NET Standard 2.0, or .NET 6.0+.
*   **Package Manager:** NuGet / `dotnet` CLI.
*   **Authentication:** Application Default Credentials (ADC) configured via
    `gcloud auth application-default login`.

## Installation

Install the official NuGet package.

> [!NOTE] For package management options, see the
> [NuGet Google.Analytics.Data.V1Beta Page](https://www.nuget.org/packages/Google.Analytics.Data.V1Beta#package-manager).

Run the following command using the .NET CLI:

```bash
dotnet add package Google.Analytics.Data.V1Beta
```

If `dotnet` is not available, prompt the user to install the `.NET CLI` before
installing the package.

Or via Package Manager Console in Visual Studio:

```powershell
Install-Package Google.Analytics.Data.V1Beta
```

*Why: The NuGet package provides asynchronous service client wrappers and
protobuf types for calling the Data API.*

## Quickstart / Usage

```csharp
using System;
using System.Threading.Tasks;
using Google.Analytics.Data.V1Beta;

class Program
{
    static async Task Main()
    {
        // Initialize client. Uses Application Default Credentials.
        BetaAnalyticsDataClient client = await BetaAnalyticsDataClient.CreateAsync();

        RunReportRequest request = new RunReportRequest
        {
            Property = "properties/1234567",
            Dimensions = { new Dimension { Name = "city" } },
            Metrics = { new Metric { Name = "activeUsers" } },
            DateRanges = { new DateRange { StartDate = "2026-05-01", EndDate = "today" } }
        };

        RunReportResponse response = await client.RunReportAsync(request);
        foreach (Row row in response.Rows)
        {
            Console.WriteLine($"{row.DimensionValues[0].Value}, {row.MetricValues[0].Value}");
        }
    }
}
```

````


### `references/go.md`

````markdown
# Google Analytics Data API Go Client Library Installation

This guide provides specific instructions for installing and setting up the
Google Analytics Data API (v1beta) client library for Go.

## Prerequisites

*   **Go:** Version 1.19 or higher.
*   **Modules:** Go modules enabled.
*   **Authentication:** Application Default Credentials (ADC) configured via
    `gcloud auth application-default login`.

## Installation

Install the official Go client library using `go get`.

Run the following command in your module directory:

```bash
go get cloud.google.com/go/analytics/data/apiv1beta
```

If `go` is not available, prompt the user to install `Go` before installing the
package.

*Why: This command adds the Google Analytics Data API package and its gRPC
transport layers to your Go project.*

## Quickstart / Usage

```go
package main

import (
    "context"
    "fmt"
    "log"

    data "cloud.google.com/go/analytics/data/apiv1beta"
    "cloud.google.com/go/analytics/data/apiv1beta/datapb"
)

func main() {
    ctx := context.Background()

    // Initialize client. Uses ADC from environment.
    client, err := data.NewBetaAnalyticsDataClient(ctx)
    if err != nil {
        log.Fatalf("Failed to create client: %v", err)
    }
    defer client.Close()

    req := &datapb.RunReportRequest{
        Property:   "properties/1234567",
        Dimensions: []*datapb.Dimension{{Name: "city"}},
        Metrics:    []*datapb.Metric{{Name: "activeUsers"}},
        DateRanges: []*datapb.DateRange{{StartDate: "2026-05-01", EndDate: "today"}},
    }

    resp, err := client.RunReport(ctx, req)
    if err != nil {
        log.Fatalf("RunReport failed: %v", err)
    }

    for _, row := range resp.Rows {
        fmt.Printf("%s, %s\n", row.DimensionValues[0].Value, row.MetricValues[0].Value)
    }
}
```

````


### `references/java.md`

````markdown
# Google Analytics Data API Java Client Library Installation

This guide provides specific instructions for installing and setting up the
Google Analytics Data API (v1beta) client library for Java.

## Prerequisites

*   **Java Development Kit (JDK):** Java 8 or higher (Java 11+ recommended).
*   **Build Tool:** Maven or Gradle.
*   **Authentication:** Application Default Credentials (ADC) configured via
    `gcloud auth application-default login`.

## Installation

Add the official Google Analytics Data client library dependency to your build
file.

> [!NOTE] For complete reference documentation, see the
> [Google Cloud Java Analytics Data Repository](https://github.com/googleapis/google-cloud-java/blob/main/java-analytics-data/README.md).

> [!TIP]
> Always replace `LATEST_LIBRARY_VERSION` with the latest stable version of the
> dependency available on Maven Central.

### Option A: Maven (`pom.xml`)

Add the following dependency inside your `<dependencies>` tag in `pom.xml`:

```xml
<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-analytics-data</artifactId>
  <version>LATEST_LIBRARY_VERSION</version>
</dependency>
```

*Why: Using Maven ensures all required gRPC and protobuf message classes are
added to your runtime classpath.*

### Option B: Gradle (`build.gradle`)

Add the following to your `dependencies` block:

```groovy
implementation 'com.google.cloud:google-cloud-analytics-data:LATEST_LIBRARY_VERSION'
```

## Quickstart / Usage

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

public class DataApiDemo {
  public static void main(String[] args) throws Exception {
    // Initialize BetaAnalyticsDataClient within try-with-resources.
    try (BetaAnalyticsDataClient client = BetaAnalyticsDataClient.create()) {
      RunReportRequest request = RunReportRequest.newBuilder()
          .setProperty("properties/1234567")
          .addDimensions(Dimension.newBuilder().setName("city"))
          .addMetrics(Metric.newBuilder().setName("activeUsers"))
          .addDateRanges(DateRange.newBuilder().setStartDate("2026-05-01").setEndDate("today"))
          .build();

      RunReportResponse response = client.runReport(request);
      response.getRowsList().forEach(row -> {
        System.out.printf("%s, %s%n", row.getDimensionValues(0).getValue(), row.getMetricValues(0).getValue());
      });
    }
  }
}
```

````


### `references/nodejs.md`

````markdown
# Google Analytics Data API Node.js Client Library Installation

This guide provides specific instructions for installing and setting up the
Google Analytics Data API (v1beta) client library for Node.js.

## Prerequisites

*   **Node.js:** v14.x or higher (v16+ recommended).
*   **Package Manager:** `npm` or `yarn`.
*   **Authentication:** Application Default Credentials (ADC) configured via
    `gcloud auth application-default login`.

## Installation

Install the official npm package.

> [!NOTE] For complete reference documentation, see the
> [Node.js Analytics Data Reference](https://googleapis.dev/nodejs/analytics-data/latest/index.html#installing-the-client-library).

Run the following command in your project root:

```bash
npm install @google-analytics/data
```

*Why: Installing `@google-analytics/data` provides TypeScript definitions and
JavaScript wrappers for the BetaAnalyticsDataClient.*

## Quickstart / Usage

```javascript
const {BetaAnalyticsDataClient} = require('@google-analytics/data');

async function runReport() {
  // Initialize client. Automatically authenticates using ADC.
  const analyticsDataClient = new BetaAnalyticsDataClient();

  const [response] = await analyticsDataClient.runReport({
    property: 'properties/1234567',
    dateRanges: [{startDate: '2026-05-01', endDate: 'today'}],
    dimensions: [{name: 'city'}],
    metrics: [{name: 'activeUsers'}],
  });

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

runReport().catch(console.error);
```

````


### `references/php.md`

````markdown
# Google Analytics Data API PHP Client Library Installation

This guide provides specific instructions for installing and setting up the
Google Analytics Data API (v1beta) client library for PHP.

## Prerequisites

*   **PHP:** Version 8.0 or higher.
*   **Package Manager:** Composer.
*   **Authentication:** Application Default Credentials (ADC) configured via
    `gcloud auth application-default login`.

## Installation

Install the library using Composer.

> [!NOTE] For complete instructions, see the
> [PHP Analytics Data Repository](https://github.com/googleapis/php-analytics-data#installation).

Run the following command in your project root:

```bash
composer require google/analytics-data
```

If `composer` is not available, prompt the user to install `Composer` before
installing the package.

*Why: Composer downloads `google/analytics-data`, its dependencies, and sets up
autoloading.*

## Quickstart / Usage

```php
require_once __DIR__ . '/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;

$client = new BetaAnalyticsDataClient();

$request = (new RunReportRequest())
    ->setProperty('properties/1234567')
    ->setDimensions([new Dimension(['name' => 'city'])])
    ->setMetrics([new Metric(['name' => 'activeUsers'])])
    ->setDateRanges([new DateRange(['start_date' => '2026-05-01', 'end_date' => 'today'])]);

$response = $client->runReport($request);

foreach ($response->getRows() as $row) {
    printf("%s, %s\n", $row->getDimensionValues()[0]->getValue(), $row->getMetricValues()[0]->getValue());
}
```

````


### `references/python.md`

````markdown
# Google Analytics Data API Python Client Library Installation

This guide provides specific instructions for installing and setting up the
Google Analytics Data API (v1beta) client library for Python.

## Prerequisites

*   **Python:** Version 3.8 or higher.
*   **Package Manager:** `pip`
*   **Authentication:** Application Default Credentials (ADC) configured via
    `gcloud auth application-default login`.

## Installation

Install the official Google Analytics Data client library within a virtual
environment.

> [!NOTE] For complete documentation, see the
> [Python Analytics Data README](https://github.com/googleapis/google-cloud-python/blob/main/packages/google-analytics-data/README.rst#installation).

### 1. Create and Activate a Virtual Environment

```bash
python3 -m venv .venv
source .venv/bin/activate
```

### 2. Install the Client Library

```bash
pip install google-analytics-data
```

If `pip` is not available, prompt the user to install Python and `pip` before
installing the client library.

*Why: Installing `google-analytics-data` in a clean virtual environment ensures
repeatable builds and prevents dependency conflicts.*

## Quickstart / Usage

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

def run_report(property_id: str):
    # Initialize the client. Uses ADC from environment.
    client = BetaAnalyticsDataClient()

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

    for row in response.rows:
        print(f"City: {row.dimension_values[0].value}, Users: {row.metric_values[0].value}")

if __name__ == "__main__":
    run_report("1234567")
```

````


### `references/ruby.md`

````markdown
# Google Analytics Data API Ruby Client Library Installation

This guide provides specific instructions for installing and setting up the
Google Analytics Data API (v1beta) client library for Ruby.

## Prerequisites

*   **Ruby:** Version 3.0 or higher.
*   **Package Manager:** RubyGems / Bundler.
*   **Authentication:** Application Default Credentials (ADC) configured via
    `gcloud auth application-default login`.

## Installation

Install the official Google Cloud Ruby client gem.

> [!NOTE] For full installation instructions, refer to the
> [Ruby Analytics Data Repository](https://github.com/googleapis/google-cloud-ruby/tree/main/google-analytics-data-v1beta#installation).

Using RubyGems:

```bash
gem install google-analytics-data-v1beta
```

If `gem` is not available, prompt the user to install `Ruby` (and `RubyGems`)
before installing the gem.

Or add to your `Gemfile`:

```ruby
gem "google-analytics-data-v1beta"
```

And run `bundle install`.

## Quickstart / Usage

```ruby
require "google/analytics/data/v1beta"

# Initialize client. Automatically authenticates using ADC.
client = Google::Analytics::Data::V1beta::AnalyticsData::Client.new

request = Google::Analytics::Data::V1beta::RunReportRequest.new(
  property: "properties/1234567",
  dimensions: [Google::Analytics::Data::V1beta::Dimension.new(name: "city")],
  metrics: [Google::Analytics::Data::V1beta::Metric.new(name: "activeUsers")],
  date_ranges: [Google::Analytics::Data::V1beta::DateRange.new(start_date: "2026-05-01", end_date: "today")]
)

response = client.run_report request
response.rows.each do |row|
  puts "#{row.dimension_values.first.value}, #{row.metric_values.first.value}"
end
```

````
