Démarrage rapide: gérer les associations de comptes Google Analytics à l'aide de l'API Google Marketing Platform Admin

Dans ce guide de démarrage rapide, vous allez créer des requêtes à l'API Google Marketing Platform Admin et afficher les réponses contenant la liste des comptes Google Analytics associés à l'organisation Google Marketing Platform spécifiée.

Vous pouvez suivre ce guide de démarrage rapide à l'aide d'un SDK de langage de programmation dans votre environnement local ou de l'API REST.

Prérequis

Pour suivre ce guide de démarrage rapide, vous devez:

  • Configurer un projet Google Cloud et activer l'API Google Marketing Platform Admin
  • Sur votre machine locale :
    • Installer, initialiser et s'authentifier auprès de Google Cloud
    • Installer le SDK pour votre langue

Configurer un projet Google Cloud

Configurez votre projet Google Cloud et activez l'API Google Marketing Platform Admin.

Cliquez sur ce bouton pour sélectionner ou créer un projet Google Cloud et activer automatiquement l'API Admin de Google Marketing Platform:

Activer l'API Google Marketing Platform Admin

Configurer Google Cloud

Sur votre ordinateur local, configurez et authentifiez-vous auprès de Google Cloud.

  1. Installez et initialisez Google Cloud.

  2. Si vous avez déjà installé Google Cloud, assurez-vous que vos composants gcloud sont à jour en exécutant cette commande.

    gcloud components update
  3. Pour vous authentifier auprès de Google Cloud, générez un fichier local d'identifiants par défaut de l'application (ADC) en exécutant cette commande. Le flux Web lancé par la commande permet de fournir vos identifiants utilisateur.

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

    Notez que les champs d'application requis par l'API Google Marketing Platform Admin sont spécifiés dans la commande.

    Pour en savoir plus, consultez la page Configurer les identifiants par défaut de l'application.

L'API Google Marketing Platform Admin nécessite un projet de quota, qui n'est pas défini par défaut. Pour savoir comment définir votre projet de quota, consultez le guide des identifiants utilisateur.

Identifiez l'ID de votre organisation Google Marketing Platform

Pour utiliser l'API Google Marketing Platform Admin, vous devez identifier l'ID de votre organisation Google Marketing Platform. Connectez-vous à Google Marketing Platform, accédez à la boîte de dialogue Administration, sélectionnez votre organisation, puis notez l'ID de l'organisation sous Détails de l'organisation.

Toutes les requêtes envoyées à l'API Google Marketing Platform Admin doivent inclure l'ID de l'organisation au format organizations/ORGANIZATION_ID.

Configurer le SDK pour votre langage de programmation

Sur votre ordinateur local, cliquez sur l'un des onglets suivants pour installer le SDK pour votre langage de programmation.

Java

Guide d'installation de la bibliothèque cliente Java

PHP

Guide d'installation de la bibliothèque cliente PHP

Python

Guide d'installation de la bibliothèque cliente Python

Node.js

Guide d'installation de la bibliothèque cliente Node.js

.NET

Guide d'installation de la bibliothèque cliente.NET

Ruby

Guide d'installation de la bibliothèque cliente Ruby

REST

Configurez vos variables d'environnement en saisissant les informations suivantes.

  1. Remplacez ORGANIZATION_ID par l'ID de votre organisation Google Marketing Platform.
  2. Remplacez PROJECT_ID par l'ID de votre projet Google Cloud.

Effectuer un appel d'API

Vous pouvez désormais utiliser l'API Google Marketing Platform pour lister les comptes Google Analytics associés à l'entreprise Google Marketing Platform spécifiée. Exécutez le code suivant pour effectuer votre premier appel à l'API:

Java

Supprimez les appels à .setPageSize et .setPageToken lorsque vous exécutez le guide de démarrage rapide.

import com.google.ads.marketingplatform.admin.v1alpha.AnalyticsAccountLink;
import com.google.ads.marketingplatform.admin.v1alpha.ListAnalyticsAccountLinksRequest;
import com.google.ads.marketingplatform.admin.v1alpha.MarketingplatformAdminServiceClient;
import com.google.ads.marketingplatform.admin.v1alpha.OrganizationName;

public class SyncListAnalyticsAccountLinks {

  public static void main(String[] args) throws Exception {
    syncListAnalyticsAccountLinks();
  }

  public static void syncListAnalyticsAccountLinks() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (MarketingplatformAdminServiceClient marketingplatformAdminServiceClient =
        MarketingplatformAdminServiceClient.create()) {
      ListAnalyticsAccountLinksRequest request =
          ListAnalyticsAccountLinksRequest.newBuilder()
              .setParent(OrganizationName.of("[ORGANIZATION]").toString())
              .setPageSize(883849137)
              .setPageToken("pageToken873572522")
              .build();
      for (AnalyticsAccountLink element :
          marketingplatformAdminServiceClient.listAnalyticsAccountLinks(request).iterateAll()) {
        // doThingsWith(element);
      }
    }
  }
}

PHP

use Google\Ads\MarketingPlatform\Admin\V1alpha\AnalyticsAccountLink;
use Google\Ads\MarketingPlatform\Admin\V1alpha\Client\MarketingplatformAdminServiceClient;
use Google\Ads\MarketingPlatform\Admin\V1alpha\ListAnalyticsAccountLinksRequest;
use Google\ApiCore\ApiException;
use Google\ApiCore\PagedListResponse;

/**
 * Lists the Google Analytics accounts link to the specified Google Marketing
 * Platform organization.
 *
 * @param string $formattedParent The parent organization, which owns this collection of Analytics
 *                                account links. Format: organizations/{org_id}
 *                                Please see {@see MarketingplatformAdminServiceClient::organizationName()} for help formatting this field.
 */
function list_analytics_account_links_sample(string $formattedParent): void
{
    // Create a client.
    $marketingplatformAdminServiceClient = new MarketingplatformAdminServiceClient();

    // Prepare the request message.
    $request = (new ListAnalyticsAccountLinksRequest())
        ->setParent($formattedParent);

    // Call the API and handle any network failures.
    try {
        /** @var PagedListResponse $response */
        $response = $marketingplatformAdminServiceClient->listAnalyticsAccountLinks($request);

        /** @var AnalyticsAccountLink $element */
        foreach ($response as $element) {
            printf('Element data: %s' . PHP_EOL, $element->serializeToJsonString());
        }
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedParent = MarketingplatformAdminServiceClient::organizationName('[ORGANIZATION]');

    list_analytics_account_links_sample($formattedParent);
}

Python

# This snippet has been automatically generated and should be regarded as a
# code template only.
# It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
#   client as shown in:
#   https://googleapis.dev/python/google-api-core/latest/client_options.html
from google.ads import marketingplatform_admin_v1alpha


def sample_list_analytics_account_links():
    # Create a client
    client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient()

    # Initialize request argument(s)
    request = marketingplatform_admin_v1alpha.ListAnalyticsAccountLinksRequest(
        parent="parent_value",
    )

    # Make the request
    page_result = client.list_analytics_account_links(request=request)

    # Handle the response
    for response in page_result:
        print(response)

Node.js

Utilisation: node packages/google-marketingplatform-admin/samples/quickstart.js organizations/ORGANISATION_ID.

  /**
   * This snippet has been automatically generated and should be regarded as a code template only.
   * It will require modifications to work.
   * It may require correct/in-range values for request initialization.
   * TODO(developer): Uncomment these variables before running the sample.
   */
  /**
   *  Required. The parent organization, which owns this collection of Analytics
   *  account links. Format: organizations/{org_id}
   */
  // const parent = 'abc123'
  /**
   *  Optional. The maximum number of Analytics account links to return in one
   *  call. The service may return fewer than this value.
   *  If unspecified, at most 50 Analytics account links will be returned. The
   *  maximum value is 1000; values above 1000 will be coerced to 1000.
   */
  // const pageSize = 1234
  /**
   *  Optional. A page token, received from a previous ListAnalyticsAccountLinks
   *  call. Provide this to retrieve the subsequent page.
   *  When paginating, all other parameters provided to
   *  `ListAnalyticsAccountLinks` must match the call that provided the page
   *  token.
   */
  // const pageToken = 'abc123'

  // Imports the Admin library
  const {MarketingplatformAdminServiceClient} =
    require('@google-ads/marketing-platform-admin').v1alpha;

  // Instantiates a client
  const adminClient = new MarketingplatformAdminServiceClient({fallback: true});

  async function callListAnalyticsAccountLinks() {
    // Construct request
    const request = {
      parent,
    };

    // Run request
    const iterable = adminClient.listAnalyticsAccountLinksAsync(request);
    for await (const response of iterable) {
      console.log(response);
    }
  }

  callListAnalyticsAccountLinks();

.NET

    using Google.Ads.MarketingPlatform.Admin.V1Alpha;
    using Google.Api.Gax;
    using System;

    public sealed partial class GeneratedMarketingplatformAdminServiceClientSnippets
    {
        /// <summary>Snippet for ListAnalyticsAccountLinks</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public void ListAnalyticsAccountLinks()
        {
            // Create client
            MarketingplatformAdminServiceClient marketingplatformAdminServiceClient = MarketingplatformAdminServiceClient.Create();
            // Initialize request argument(s)
            string parent = "organizations/[ORGANIZATION]";
            // Make the request
            PagedEnumerable<ListAnalyticsAccountLinksResponse, AnalyticsAccountLink> response = marketingplatformAdminServiceClient.ListAnalyticsAccountLinks(parent);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (AnalyticsAccountLink item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (ListAnalyticsAccountLinksResponse page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (AnalyticsAccountLink item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page<AnalyticsAccountLink> singlePage = response.ReadPage(pageSize);
            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (AnalyticsAccountLink item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
        }
    }

REST

Pour envoyer cette requête, exécutez la commande curl à partir de la ligne de commande ou incluez l'appel REST dans votre application.

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

L'exemple de code affiche une réponse avec une liste des comptes Google Analytics associés à l'entreprise Google Marketing Platform spécifiée:

{
  "analyticsAccountLinks": [
    {
      "name": "organizations/0a123456789-wxyz/analyticsAccountLinks/1234567890",
      "analyticsAccount": "analyticsadmin.googleapis.com/accounts/1234567890",
      "displayName": "Demo Account",
      "linkVerificationState": "LINK_VERIFICATION_STATE_VERIFIED"
    }
  ]
}

Félicitations ! Vous avez envoyé votre première requête à l'API Google Marketing Platform.