Szybki start dla programistów korzystających z interfejsu Google Analytics Admin API

W tej sekcji krótkiego wprowadzenia utworzysz i wyślesz list żądania do interfejsu Google Analytics Admin API, a potem wyświetlisz odpowiedzi, aby skonfigurować i potwierdzić dostęp do interfejsu API.

Możesz wykonać ten samouczek za pomocą pakietu SDK lub interfejsu REST API w środowisku lokalnym albo instancji maszyny wirtualnej Google Cloud.

Oto podsumowanie kroków:

  • skonfigurować projekt Google Cloud i włączyć interfejs Google Analytics Admin API;
  • Na komputerze lokalnym lub instancji maszyny wirtualnej w chmurze:
    • Instalowanie, inicjowanie i uwierzytelnianie się w Google Cloud.
    • Zainstaluj pakiet SDK dla wybranego języka (opcjonalnie).
  • skonfigurować uwierzytelnianie,
  • Skonfiguruj dostęp do Google Analytics.
  • Skonfiguruj pakiet SDK.
  • Wywołaj interfejs API.

Konfigurowanie projektu Google Cloud

Kliknij przycisk Włącz interfejs Google Analytics Admin API, aby wybrać lub utworzyć nowy projekt Google Cloud i automatycznie włączyć interfejs Google Analytics Admin API.

Włączanie interfejsu Google Analytics Admin API

Konfigurowanie Google Cloud

Na komputerze lokalnym lub instancji maszyny wirtualnej w Google Cloud skonfiguruj Google Cloud i zaloguj się na swoje konto.

  1. Zainstaluj i inicjuj Google Cloud.

  2. Aby mieć pewność, że komponenty gcloud są aktualne, uruchom to polecenie.

    gcloud components update

Aby uniknąć podawania identyfikatora projektu w Google Cloud, możesz użyć polecenia gcloud config set, aby ustawić domyślny projekt i region.

Konfigurowanie uwierzytelniania

W tym krótkim wprowadzeniu użyjemy domyślnych danych logowania aplikacji, aby automatycznie znajdować dane logowania na podstawie środowiska aplikacji. Dzięki temu nie musisz zmieniać kodu klienta, aby uwierzytelnić aplikację.

Interfejs Google Analytics Admin API obsługuje konta użytkowników i konta usługi:

  • Konta użytkowników reprezentują programistę, administratora lub dowolną inną osobę korzystającą z interfejsów API i usług Google.
  • Konta usługi nie reprezentują konkretnego użytkownika. Umożliwiają one zarządzanie uwierzytelnianiem i autoryzacją, gdy nie jest bezpośrednio zaangażowana osoba, np. gdy aplikacja musi uzyskać dostęp do zasobów Google Cloud.

Więcej informacji o uwierzytelnianiu i konfigurowaniu danych logowania do konta w aplikacji znajdziesz w artykule Metody uwierzytelniania w Google.

Wygeneruj lokalny plik domyślnych danych uwierzytelniających aplikacji (ADC), uruchamiając to polecenie. To polecenie uruchamia proces internetowy, w którym podajesz dane logowania użytkownika.

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

Pamiętaj, aby w komendach podać zakresy wymagane przez interfejs Google Analytics Admin API. Więcej informacji znajdziesz w artykule Konfigurowanie domyślnego uwierzytelniania aplikacji.

Aby uwierzytelnić się przy użyciu konta usługi, wykonaj te czynności:

  1. Utwórz konto usługi
  2. Załącz konto usługi do instancji maszyny wirtualnej w chmurze, uruchamiając to polecenie gcloud CLI:
  gcloud compute instances stop YOUR-VM-INSTANCE-ID

  gcloud compute instances set-service-account YOUR-VM-INSTANCE-ID \
    --service-account YOUR-SERVICE-ACCOUNT-EMAIL-ALIAS  \
    --scopes="https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/analytics.readonly"

Pamiętaj, aby w komendach podać zakresy wymagane przez interfejs Google Analytics Admin API. Więcej informacji znajdziesz w artykule Konfigurowanie domyślnego uwierzytelniania aplikacji.

Konfigurowanie dostępu do Google Analytics

Przyznaj Google Analytics dostęp do adresu e-mail powiązanego z kontem użytkownika lub usługi.

Konfigurowanie pakietu SDK pod kątem języka programowania

Zainstaluj na komputerze pakiet SDK dla wybranego języka programowania.

Przewodnik po instalacji biblioteki klienta Java

Przewodnik po instalacji biblioteki klienta PHP

Przewodnik po instalacji biblioteki klienta Pythona

Przewodnik po instalacji biblioteki klienta Node.js

Przewodnik instalacji biblioteki klienta.NET

Przewodnik instalacji biblioteki klienta Ruby

go get google.golang.org/genproto/googleapis/analytics/admin/v1beta

Aby skonfigurować zmienne środowiskowe, wpisz: Zastąp PROJECT_ID identyfikatorem projektu Google Cloud.

  EXPORT PROJECT_ID=PROJECT_ID

Wywoływanie interfejsu API

Aby wykonać pierwsze wywołanie, uruchom ten kod:

import com.google.analytics.admin.v1beta.Account;
import com.google.analytics.admin.v1beta.AnalyticsAdminServiceClient;
import com.google.analytics.admin.v1beta.AnalyticsAdminServiceClient.ListAccountsPage;
import com.google.analytics.admin.v1beta.AnalyticsAdminServiceClient.ListAccountsPagedResponse;
import com.google.analytics.admin.v1beta.ListAccountsRequest;

/**
 * This application demonstrates the usage of the Analytics Admin API using service account
 * credentials. For more information on service accounts, see
 * https://cloud.google.com/iam/docs/understanding-service-accounts.
 *
 * <p>The following document provides instructions on setting service account credentials for your
 * application: https://cloud.google.com/docs/authentication/production
 *
 * <p>In a nutshell, you need to:
 *
 * <ol>
 *   <li>Create a service account and download the key JSON file as described at
 *       https://cloud.google.com/docs/authentication/production#creating_a_service_account.
 *   <li>Provide service account credentials using one of the following options:
 *       <ul>
 *         <li>Set the {@code GOOGLE_APPLICATION_CREDENTIALS} environment variable. The API client
 *             will use the value of this variable to find the service account key JSON file. See
 *             https://cloud.google.com/docs/authentication/production#setting_the_environment_variable
 *             for more information.
 *             <p>OR
 *         <li>Manually pass the path to the service account key JSON file to the API client by
 *             specifying the {@code keyFilename} parameter in the constructor. See
 *             https://cloud.google.com/docs/authentication/production#passing_the_path_to_the_service_account_key_in_code
 *             for more information.
 *       </ul>
 * </ol>
 *
 * <p>To run this sample using Maven:
 *
 * <pre>{@code
 * cd google-analytics-data
 * mvn compile exec:java -Dexec.mainClass="com.google.analytics.admin.samples.QuickstartSample"
 * }</pre>
 */
public class QuickstartSample {

  public static void main(String... args) throws Exception {
    listAccounts();
  }

  // This is an example snippet that calls the Google Analytics Admin API and lists all Google
  // Analytics accounts available to the authenticated user.
  static void listAccounts() throws Exception {
    // Instantiates a client using default credentials.
    // See https://cloud.google.com/docs/authentication/production for more information
    // about managing credentials.
    try (AnalyticsAdminServiceClient analyticsAdmin = AnalyticsAdminServiceClient.create()) {
      // Calls listAccounts() method of the Google Analytics Admin API and prints
      // the response for each account.
      ListAccountsPagedResponse response =
          analyticsAdmin.listAccounts(ListAccountsRequest.newBuilder().build());
      for (ListAccountsPage page : response.iteratePages()) {
        for (Account account : page.iterateAll()) {
          System.out.printf("Account name: %s%n", account.getName());
          System.out.printf("Display name: %s%n", account.getDisplayName());
          System.out.printf("Country code: %s%n", account.getRegionCode());
          System.out.printf("Create time: %s%n", account.getCreateTime().getSeconds());
          System.out.printf("Update time: %s%n", account.getUpdateTime().getSeconds());
          System.out.println();
        }
      }
    }
  }
}

require 'vendor/autoload.php';

use Google\Analytics\Admin\V1beta\Account;
use Google\Analytics\Admin\V1beta\Client\AnalyticsAdminServiceClient;
use Google\Analytics\Admin\V1beta\ListAccountsRequest;

/**
 * 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.
// See https://cloud.google.com/docs/authentication/production for more information
// about managing credentials.
$client = new AnalyticsAdminServiceClient();

// Calls listAccounts() method of the Google Analytics Admin API and prints
// the response for each account.
$request = new ListAccountsRequest();
$response = $client->listAccounts($request);

print 'Result:' . PHP_EOL;
foreach ($response->iterateAllElements() as $account) {
    print 'Account name: ' . $account->getName() . PHP_EOL;
    print 'Display name: ' . $account->getDisplayName() . PHP_EOL;
    print 'Country code: ' . $account->getRegionCode() . PHP_EOL;
    print 'Create time: ' . $account->getCreateTime()->getSeconds() . PHP_EOL;
    print 'Update time: ' . $account->getUpdateTime()->getSeconds() . PHP_EOL;
}

def list_accounts(transport: str = None):
    """
    Lists the available Google Analytics accounts.

    Args:
        transport(str): The transport to use. For example, "grpc"
            or "rest". If set to None, a transport is chosen automatically.
    """
    from google.analytics.admin import AnalyticsAdminServiceClient

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

    results = client.list_accounts()

    # Displays the configuration information for all Google Analytics accounts
    # available to the authenticated user.
    print("Result:")
    for account in results:
        print(account)

  // Imports the Google Analytics Admin API client library.
  const analyticsAdmin = require('@google-analytics/admin');

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

  // Lists all Google Analytics accounts available to the authenticated user.
  async function listAccounts() {
    // Uses listAccounts() with no arguments to fetch all pages. For more
    // information on pagination in the Node.js library, see:
    // https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#auto-pagination
    const [response] = await analyticsAdminClient.listAccounts();

    console.log('Accounts:');
    for (const account of response) {
      console.log('Account name:', account.name);
      console.log('Display name:', account.displayName);
      console.log('Region code:', account.regionCode);
      console.log('Create time:', account.createTime.seconds);
      console.log('Update time:', account.updateTime.seconds);
    }
  }

  listAccounts();

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

namespace AnalyticsSamples
{
    class QuickStart
    {
        static void Main(string[] args)
        {
            AnalyticsAdminServiceClient client = AnalyticsAdminServiceClient.Create();
            PagedEnumerable<ListAccountsResponse, Account> response =
                client.ListAccounts( new ListAccountsRequest() );
            foreach( Account account in response )
            {
                Console.WriteLine("Account name: {0}", account.Name);
                Console.WriteLine("Display name: {0}", account.DisplayName);
                Console.WriteLine("Region code: {0}", account.RegionCode);
                Console.WriteLine("Update time: {0}", account.UpdateTime);
                Console.WriteLine("Create time: {0}", account.CreateTime);
                Console.WriteLine();
            }
        }
    }
}

Aby wysłać to żądanie, uruchom polecenie curl z wiersza poleceń lub dodaj wywołanie REST w aplikacji.

curl -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
  -H "x-goog-user-project: ${PROJECT_ID}" \
  -H "Content-Type: application/json" \
  https://analyticsadmin.googleapis.com/v1beta/accounts

Odpowiedź z próbnego kodu zawiera listę kont Google Analytics, do których użytkownik lub konto usługi ma dostęp:

{
  "accounts": [
    {
      "name": "accounts/123456789",
      "createTime": "2025-01-01T00:12:23.456Z",
      "createTime": "2025-01-01T00:12:23.456Z",
      "displayName": "Demo Account",
      "regionCode": "US",
      "gmpOrganization": "marketingplatformadmin.googleapis.com/organizations/abcdef12345678"
    }
}