옵션
집 Skill 데이터베이스 관리 google-analytics-data-api-basics

google-analytics-data-api-basics

google/skills google/skills

Google Analytics Data API를 활성화하고, gcloud를 통해 인증하며, v1beta 클라이언트 라이브러리를 사용하여 사용자 지정 보고서를 생성합니다.

...모든 것을 확장하십시오
3
업데이트 된 시간 2026년 9월 4일

Google Analytics 데이터 API 시작하기

Google Analytics 데이터 API v1beta는 Google Analytics 보고서 데이터에 프로그래밍 방식으로 접근할 수 있는 기능을 제공합니다. 이를 통해 맞춤형 대시보드를 구축하고, 보고 워크플로우를 자동화하며, Google Analytics 데이터를 기업용 애플리케이션에 통합할 수 있습니다.

Cloud CLI를 통해 API 활성화하기

API 호출을 수행하기 전에 Google Cloud 프로젝트에서 Google Analytics 데이터 API가 활성화되어 있는지 확인하십시오.

gcloud 명령어를 찾을 수 없는 경우, 해당 명령어를 실행하기 전에 사용자에게 Google Cloud CLI를 설치하도록 안내하십시오.

  1. API 활성화: Cloud CLI(gcloud)를 사용하여 analyticsdata.googleapis.com을 활성화합니다.

     gcloud services enable analyticsdata.googleapis.com --quiet
    

    이유: API를 활성화하면 Cloud 프로젝트에 Google Analytics 보고서를 실행하는 데 필요한 할당량과 권한이 할당됩니다.

  2. API 활성화 상태 확인:

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

인증

API 요청을 인증하려면 Application Default Credentials(ADC)를 생성하고 계정에 필요한 범위를 부여해야 합니다. 터미널에서 다음 명령어를 실행하십시오:

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

이유: 이는 로컬 환경에 ADC를 구성하여 필요한 Cloud Platform 및 Google Analytics 읽기 전용 범위를 설정하며, 이를 통해 클라이언트 라이브러리가 요청을 자동으로 인증할 수 있게 합니다.

데이터 API 보고서 생성 (v1beta)

보고서를 생성하려면 공식 Google Analytics 데이터 클라이언트 라이브러리를 사용하십시오. 안정성과 최신 Google Analytics 보고 기능에 대한 접근성을 위해 항상 API의 v1beta 버전을 선호하십시오.

[!IMPORTANT] 필수 에이전트 지침: 사용자가 특정 프로그래밍 언어를 선택하거나 요구하는 경우, 아래에 나열된 references/ 폴더의 해당 클라이언트 라이브러리 설정 참조 가이드를 읽으십시오.

지원되는 클라이언트 라이브러리

Python

Python용 Google Analytics 데이터 API 클라이언트 라이브러리를 설치하거나 설정해야 하는 경우, 설정 가이드를 읽으십시오:

  • Python 설치 참조 (패키지: google-analytics-data)

Java

Java용 Google Analytics 데이터 API 클라이언트 라이브러리를 설치하거나 설정해야 하는 경우, 설정 가이드를 읽으십시오:

  • Java 설치 참조 (아티팩트: com.google.cloud:google-cloud-analytics-data)

PHP

PHP용 Google Analytics 데이터 API 클라이언트 라이브러리를 설치하거나 설정해야 하는 경우, 설정 가이드를 읽으십시오:

  • PHP 설치 참조 (패키지: google/analytics-data)

Node.js

Node.js용 Google Analytics 데이터 API 클라이언트 라이브러리를 설치하거나 설정해야 하는 경우, 설정 가이드를 읽으십시오:

  • Node.js 설치 참조 (패키지: @google-analytics/data)

Go

Go용 Google Analytics 데이터 API 클라이언트 라이브러리를 설치하거나 설정해야 하는 경우, 설정 가이드를 읽으십시오:

  • Go 설치 참조 (패키지: cloud.google.com/go/analytics/data/apiv1beta)

.NET

.NET / C#용 Google Analytics 데이터 API 클라이언트 라이브러리를 설치하거나 설정해야 하는 경우, 설정 가이드를 읽으십시오:

  • .NET 설치 참조 (패키지: Google.Analytics.Data.V1Beta)

Ruby

Ruby용 Google Analytics 데이터 API 클라이언트 라이브러리를 설치하거나 설정해야 하는 경우, 설정 가이드를 읽으십시오:

  • Ruby 설치 참조 (Gem: google-analytics-data-v1beta)

[!NOTE] 추가 자료: Java, PHP, Node.js, .NET, Python 및 REST를 사용하여 데이터 API를 호출하는 추가 예제와 서비스 계정을 사용한 인증에 대한 힌트는 공식 데이터 API 빠른 시작 가이드를 참조하십시오.

Python 빠른 시작

  1. 클라이언트 라이브러리 설치:

     pip install google-analytics-data
    

    pip를 사용할 수 없는 경우, 클라이언트 라이브러리를 설치하기 전에 사용자에게 pip를 설치하도록 안내하십시오.

  2. 보고서 요청 실행: 아래는 Google Analytics 속성에서 도시와 날짜별로 그룹화된 활성 사용자 및 세션에 대해 쿼리하는 방법을 보여주는 전체 예제입니다. YOUR-PROPERTY-ID를 실제 Google Analytics 속성 ID(예: 1234567)로 바꾸십시오.

     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):
         # 클라이언트 초기화.
         # 환경에 Application Default Credentials(ADC)가 구성되어 있다고 가정합니다.
         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")
    

    이유: BetaAnalyticsDataClientRunReportRequest를 사용하면 v1beta 엔드포인트와의 호환성이 보장되며, 강타입 요청 유효성 검사가 수행됩니다.

지표 및 차원 스키마

RunReportRequest를 구성할 때 차원과 지표에 대해 유효한 API 이름을 사용해야 합니다. 사용 가능한 필드의 전체이고 권위 있는 목록은 공식 데이터 API 스키마 문서를 참조하십시오.

일반적으로 사용되는 차원

차원은 데이터의 범주형 속성을 나타냅니다.

  • city: 사용자의 도시 또는 시 지역.
  • country: 사용자의 국가.
  • date: YYYYMMDD 형식으로 포맷된 이벤트 날짜.
  • deviceCategory: 모바일 기기 카테고리(예: 데스크톱, 모바일, 태블릿).
  • eventName: 트리거된 이벤트의 이름.
  • pageTitle: 웹 페이지의 제목.

일반적으로 사용되는 지표

지표는 정량적 측정을 나타냅니다.

  • activeUsers: 활성 사용자의 수.
  • eventCount: 이벤트의 총 횟수.
  • sessions: 세션의 총 수.
  • screenPageViews: 조회된 앱 화면 또는 웹 페이지 수.
  • totalRevenue: 구매, 구독 및 광고에서 발생한 총 수익.

지표 및 차원 호환성 확인

일부 차원과 지표는 동일한 보고서 요청에서 함께 쿼리할 수 없습니다. 호환되지 않는 필드에 대한 INVALID_ARGUMENT 오류가 발생하는 경우 필드 조합을 확인하십시오. 데이터 API 스키마에 프로그래밍 방식으로 접근하려면 getMetadata()를 사용하십시오. 보고서를 실행하기 전에 특정 차원 및 지표 조합의 호환성을 프로그래밍 방식으로 확인하려면 checkCompatibility() 메서드를 사용하십시오.

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

    # 함께 쿼리하려는 차원과 지표를 정의합니다.
    # 예를 들어, 'itemDescription'(전자상거래 차원)이
    # 'activeUsers' 및 '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")
GitHub에서 보기
---
name: google-analytics-data-api-basics
description: Enables the Google Analytics Data API, authenticates via gcloud, and creates customized reports using the v1beta client library.
---

# 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")
```

모든 파일

0개 파일

google-analytics-data-api-basics 설치

스킬 파일을 다운로드하여 .claude/skills/ 디렉토리에 추출하세요.

ZIP 다운로드

저장소를 클론하고 스킬 파일을 프로젝트에 복사하세요.

git clone https://github.com/google/skills/tree/main/skills/analytics/google-analytics-data-api-basics # Copy SKILL.md to your .claude/skills/ directory

복사 복사
빠른 설정: 스킬 폴더를 .claude/skills/에 복사하세요. Claude가 자동으로 감지하고 사용합니다.
저장소 google/skills

관련 스킬

microservices-patterns
업데이트 된 시간 2026년 6월 29일
jpa-patterns
업데이트 된 시간 2026년 6월 30일
fabric-lakehouse
업데이트 된 시간 2026년 6월 30일
PostgreSQL Syntax Reference
업데이트 된 시간 2026년 6월 29일
OR