Google Tag Manager API - Geliştirici Kılavuzu

Bu geliştirici kılavuzu, Tag Manager API v2 aracılığıyla bir Google Etiket Yöneticisi hesabındaki öğelere erişmek, bunları oluşturmak ve yönetmek için gereken adımları açıklar.

Giriş

Bu kılavuzda, Google Etiket Yöneticisi hesabına erişme ve hesabı yapılandırmayla ilgili çeşitli adımlar açıklanmaktadır. Bu laboratuvarı tamamladığınızda, aşağıdaki görevleri nasıl yapacağınızla ilgili temel bilgilere sahip olacaksınız:

  • Etiket Yöneticisi hizmet nesnesi oluşturun.
  • Kullanıcının kimliğini doğrulama ve kullanıcıyı yetkilendirme
  • Kaynaklara erişmek ve kaynakları yönetmek için Etiket Yöneticisi API ile çalışma

Başlamadan önce

Kılavuzu kullanmaya başlamadan önce Google Etiket Yöneticisi Yardım Merkezi'ni ziyaret ederek Google Etiket Yöneticisi hakkında bilgi edinmenizi öneririz.

Test hesabı kullanma

Varlıkları oluşturmak, yapılandırmak veya silmek için Etiket Yöneticisi API'sini kullanmayı planlıyorsanız kodunuzu bir test hesabıyla uygulamanızı ve doğrulamanızı öneririz. Test hesabı kullanmak, etkin bir hesapta yanlışlıkla değişiklik yapmanızı önlemeye yardımcı olur. Test hesabını kullanarak kodunuzu test edip beklendiği gibi çalıştığını onayladıktan sonra uygulamayı gerçek hesaplarınızla kullanmaya başlayabilirsiniz.

Dil seçin

Örnekleri takip etmek istediğiniz programlama dilini seçin:

Python


Bu kılavuzdaki tüm kod snippet'leri için Python seçilmiştir.

JavaScript


Bu kılavuzdaki tüm kod snippet'leri için JavaScript seçilmiştir.

Programa genel bakış

Bu kılavuzda yer alan örnek program, bir komut satırı uygulamasıdır. Uygulama, hesap kimliği verildiğinde Greetings adlı bir kapsayıcı bulur ve bu kapsayıcıda sayfa görüntüleme tetiklenen bir Google etiketi oluşturur.

Bu uygulamayı geliştirmek için aşağıdaki adımları uygulamanız gerekir:

  1. Google API Konsolu'nda geliştirme ortamınızı ve projenizi oluşturun.
  2. Etiket Yöneticisi hizmet nesnesi oluşturun.
    1. Etiket Yöneticisi hesabına erişim yetkisi verme
    2. Etiket Yöneticisi hizmet nesnesi oluşturun.
  3. API'yi sorgulama, yanıtı işleme ve sonuçları çıkarma
    1. Başlatılmış bir Etiket Yöneticisi hizmet nesnesi alın.
    2. Aşağıdaki görevleri gerçekleştirmek üzere Etiket Yöneticisi API'sini sorgulamak için Etiket Yöneticisi hizmet nesnesini kullanın:
      1. Kimliği doğrulanmış Google Etiket Yöneticisi hesabı için Greetings kapsayıcısını alın.
      2. Yeni çalışma alanı oluşturun.
      3. Google etiketini oluşturun.
      4. Etiketi tetikleyecek tetikleyiciyi oluşturun.
      5. Etiketi, tetikleyiciyle etkinleşecek şekilde güncelleyin.

Geliştirme ortamınızı ve projenizi ayarlama

Greetings kapsayıcısını oluşturma

Bu kılavuzda, Greetings adlı bir kapsayıcıya sahip bir Google Etiket Yöneticisi hesabınız olduğu varsayılmaktadır. Kurulum ve İş Akışı (Web) talimatlarını uygulayarak bir Hesap ve Greetings adında bir Kapsayıcı oluşturun.

İstemci kitaplığı yükleme

Başlamadan önce bir Google API'leri istemci kitaplığı yükleyip yapılandırın.

Google API Konsolu'nda proje oluşturma ve yapılandırma

Etiket Yöneticisi API'sini kullanmaya başlamak için önce kurulum aracını kullanmanız gerekir. Bu araç, Google API Konsolu'nda proje oluşturma ve API'yi etkinleştirme konusunda size yol gösterir.

Bu kılavuzda Yüklü Uygulama kimlik doğrulama akışı kullanılmaktadır. Proje kimlik bilgilerinizi oluşturmak için aşağıdaki talimatları uygulayın. İstendiğinde APPLICATION TYPE (UYGULAMA TÜRÜ) için Installed Application, INSTALLED APPLICATION TYPE (YÜKLÜ UYGULAMA TÜRÜ) için Other değerini seçin.

  1. Kimlik Bilgileri sayfasında, OAuth 2.0 kimlik bilgilerinizi oluşturmak için Kimlik bilgileri oluştur > OAuth istemci kimliği'ni veya bir hizmet hesabı oluşturmak için Kimlik bilgileri oluştur > Hizmet hesabı anahtarı'nı tıklayın.
  2. OAuth istemci kimliği oluşturduysanız uygulama türünüzü seçin.
  3. Formu doldurun ve Oluştur'u tıklayın.

Uygulamanızın istemci kimlikleri ve hizmet hesabı anahtarları artık Kimlik Bilgileri sayfasında listelenir. Ayrıntılar için bir istemci kimliğini tıklayın. Parametreler, kimlik türüne göre değişir ancak e-posta adresi, istemci gizli anahtarı, JavaScript kaynakları veya yönlendirme URI'lerini içerebilir.

Download JSON (JSON'u indir) düğmesini tıklayarak istemci ayrıntılarını indirin. Bu dosyayı client_secrets.json olarak yeniden adlandırın. Bu dosya daha sonra kimlik doğrulama amacıyla kullanılacaktır.

Etiket Yöneticisi hizmet nesnesi oluşturma

API istekleri göndermek için Etiket Yöneticisi service nesnesini kullanırsınız.

Etiket Yöneticisi hizmet nesnesi oluşturmak için gereken adımlar şunlardır:

  1. Google Etiket Yöneticisi hesabına erişim yetkisi verme
  2. Etiket Yöneticisi hizmet nesnesini örneklendirin.

Google Etiket Yöneticisi hesabına erişim yetkisi verme

Kullanıcı, Google Etiket Yöneticisi API'si ile oluşturulmuş bir uygulamayı başlattığında, uygulamaya Google Etiket Yöneticisi hesabına erişim izni vermesi gerekir. Bu işleme yetkilendirme denir. Kullanıcıları yetkilendirmek için önerilen yöntem OAuth 2.0'dır. Daha fazla bilgi edinmek isterseniz Etiket Yöneticisi API'si Yetkilendirmesi başlıklı makaleyi okuyun.

Aşağıdaki kod, uygulamanın kullanıcısının kimliğini doğrulamak için yukarıda oluşturulan proje ve istemci ayrıntılarını kullanır ve kullanıcıdan Google Etiket Yöneticisi'ne onun adına erişmek için izin ister.

Uygulama, varsayılan tarayıcıyı açmaya ve kullanıcıyı google.com'da barındırılan bir URL'ye yönlendirmeye çalışır. Kullanıcıdan oturum açması ve uygulamaya Etiket Yöneticisi hesabına erişim izni vermesi istenir. İzin verildikten sonra uygulama, tarayıcı penceresindeki kodu okumaya çalışır ve ardından pencereyi kapatır.

Not: Bir hata oluşursa uygulama, kullanıcıdan komut satırına yetkilendirme kodunu girmesini ister.

Python

"""Access and manage a Google Tag Manager account."""

import argparse
import sys

import httplib2

from apiclient.discovery import build
from oauth2client import client
from oauth2client import file
from oauth2client import tools


def GetService(api_name, api_version, scope, client_secrets_path):
  """Get a service that communicates to a Google API.

  Args:
    api_name: string The name of the api to connect to.
    api_version: string The api version to connect to.
    scope: A list of strings representing the auth scopes to authorize for the
      connection.
    client_secrets_path: string A path to a valid client secrets file.

  Returns:
    A service that is connected to the specified API.
  """
  # Parse command-line arguments.
  parser = argparse.ArgumentParser(
      formatter_class=argparse.RawDescriptionHelpFormatter,
      parents=[tools.argparser])
  flags = parser.parse_args([])

  # Set up a Flow object to be used if we need to authenticate.
  flow = client.flow_from_clientsecrets(
      client_secrets_path, scope=scope,
      message=tools.message_if_missing(client_secrets_path))

  # Prepare credentials, and authorize HTTP object with them.
  # If the credentials don't exist or are invalid run through the native client
  # flow. The Storage object will ensure that if successful the good
  # credentials will get written back to a file.
  storage = file.Storage(api_name + '.dat')
  credentials = storage.get()
  if credentials is None or credentials.invalid:
    credentials = tools.run_flow(flow, storage, flags)
  http = credentials.authorize(http=httplib2.Http())

  # Build the service object.
  service = build(api_name, api_version, http=http)

  return service

def main(argv):
  # Define the auth scopes to request.
  scope = ['https://www.googleapis.com/auth/tagmanager.edit.containers']

  # Authenticate and construct service.
  service = GetService('tagmanager', 'v2', scope, 'client_secrets.json')


if __name__ == '__main__':
  main(sys.argv)
    

JavaScript

<html>
  <head>
    <script type="text/javascript">

    // Your Client ID can be retrieved from your project in the Google
    // Developer Console, https://console.developers.google.com
    var CLIENT_ID = TODO;
    var SCOPES = [
      'https://www.googleapis.com/auth/tagmanager.manage.accounts',
      'https://www.googleapis.com/auth/tagmanager.edit.containers',
      'https://www.googleapis.com/auth/tagmanager.delete.containers',
      'https://www.googleapis.com/auth/tagmanager.edit.containerversions',
      'https://www.googleapis.com/auth/tagmanager.manage.users',
      'https://www.googleapis.com/auth/tagmanager.publish'
    ];

    // Parameter values used by the script
    ACCOUNT_PATH = TODO; // such as: 'accounts/555555';
    CONTAINER_NAME = 'Greetings';
    WORKSPACE_NAME = 'Example workspace';

    /**
     * Check if current user has authorization for this application.
     *
     * @param {bool} immediate Whether login should use the "immediate mode", which
     *     causes the security token to be refreshed behind the scenes with no UI.
     */
    function checkAuth(immediate) {
      var authorizeCheckPromise = new Promise((resolve) => {
        gapi.auth.authorize(
          { client_id: CLIENT_ID, scope: SCOPES.join(' '), immediate: immediate },
          resolve);
      });
      authorizeCheckPromise
          .then(handleAuthResult)
          .then(loadTagManagerApi)
          .then(runTagManagerExample)
          .catch(() => {
            console.log('You must authorize any access to the api.');
          });
    }

    /**
     * Check if current user has authorization for this application.
     */
    function checkAuth() {
      checkAuth(true);
    }

    /**
     * Initiate auth flow in response to user clicking authorize button.
     *
     * @param {Event} event Button click event.
     * @return {boolean} Returns false.
     */
    function handleAuthClick(event) {
      checkAuth();
      return false;
    }

    /**
     * Handle response from authorization server.
     *
     * @param {Object} authResult Authorization result.
     * @return {Promise} A promise to call resolve if authorize or redirect to a
     *   login flow.
     */
    function handleAuthResult(authResult) {
      return new Promise((resolve, reject) => {
        var authorizeDiv = document.getElementById('authorize-div');
        if (authResult && !authResult.error) {
          // Hide auth UI, then load client library.
          authorizeDiv.style.display = 'none';
          resolve();
        } else {
          // Show auth UI, allowing the user to initiate authorization by
          // clicking authorize button.
          authorizeDiv.style.display = 'inline';
          reject();
        }
      });
    }

    /**
     * Load Tag Manager API client library.
     *
     * @return {Promise} A promise the load the Tag Manager API library.
     */
    function loadTagManagerApi() {
      return new Promise((resolve, reject) => {
        console.log('Load Tag Manager api');
        gapi.client.load('tagmanager', 'v2', resolve);
      });
    }

    /**
     * Interacts with the tagmanager api v2 to create a container, workspace,
     * trigger, and tag.
     *
     * @return {Promise} A promise to run the Tag Manager example.
     */
    function runTagManagerExample() {
      return new Promise((resolve, reject) => {
        console.log('Running Tag Manager Example.');
        resolve();
      });
    }

    /**
     * Logs an error message to the console.
     *
     * @param {string|Object} error The error to log to the console.
     */
    function handleError(error) {
      console.log('Error when interacting with GTM API');
      console.log(error);
    }

    /**
     * Wraps an API request into a promise.
     *
     * @param {Object} a request to the API.
     * @return {Promise} A promise to execute the API request.
     */
    function requestPromise(request) {
      return new Promise((resolve, reject) => {
        request.execute((response) => {
          if (response.code) {
            reject(response);
          }
          resolve(response);
        });
      });
    }
    </script>

    <script src="https://apis.google.com/js/client.js?onload=checkAuth">
    </script>
  </head>
  <body>
    <div id="authorize-div" style="display: none">
      <span>Authorize access to Tag Manager API</span>
      <!--Button for the user to click to initiate auth sequence -->
      <button id="authorize-button" onclick="handleAuthClick(event)">
        Authorize
      </button>
    </div>
    <pre id="output"></pre>
  </body>
</html>

    

Etiket Yöneticisi API'yi sorgulama

Etiket Yöneticisi hizmet nesnesi, Etiket Yöneticisi API'sini sorgulamak için kullanılabilir. Örnek programı uygulamak için aşağıdaki adımlar gereklidir:

  1. Greetings kapsayıcısını alma
  2. Google etiketini oluşturma
  3. Etiketi etkinleştirecek tetikleyiciyi oluşturma
  4. Etiketi, tetikleyiciyle tetiklenecek şekilde güncelleyin.

1. Greetings kapsayıcısını alma

Aşağıdaki işlev, bir hesabın tüm kapsayıcılarını listelemek ve Greetings adlı kapsayıcıyı almak için Tag Manager API'yi sorgulamak üzere bir Etiket Yöneticisi hizmet nesnesinin nasıl kullanılabileceğini gösterir.

Python

def FindGreetingsContainer(service, account_path):
  """Find the greetings container.

  Args:
    service: the Tag Manager service object.
    account_path: the path of the Tag Manager account from which to retrieve the
      Greetings container.

  Returns:
    The greetings container if it exists, or None if it does not.
  """
  # Query the Tag Manager API to list all containers for the given account.
  container_wrapper = service.accounts().containers().list(
      parent=account_path).execute()

  # Find and return the Greetings container if it exists.
  for container in container_wrapper['container']:
    if container['name'] == 'Greetings':
      return container
  return None
    

JavaScript

/**
 * Returns the greetings container if it exists.
 *
 * @param {string} accountPath The account which contains the Greetings
 * container.
 * @return {Promise} A promise to find the greetings container.
 */
function findContainer(accountPath, containerName) {
  console.log('Finding container in account:' + accountPath);
  var request = gapi.client.tagmanager.accounts.containers.list({
    'parent': accountPath
  });
  return requestPromise(request)
      .then((response) => {
        var containers = response.container || [];
        var container =
            containers.find((container) => container.name === containerName);
        return container ||
            Promise.reject('Unable to find ' + containerName +' container.');
      });
}
    

Ardından, programın ana yürütme dalını, bir Etiket Yöneticisi accountId verildiğinde findGreetingsContainer işlevini çağıracak şekilde güncelleyin. Örneğin:

Python

def main(argv):
  # Get tag manager account ID from command line.
  assert len(argv) == 2 and 'usage: gtm-api-hello-world.py <account_id>'
  account_id = str(argv[1])
  account_path = 'accounts/%s' % account_id

  # Define the auth scopes to request.
  scope = ['https://www.googleapis.com/auth/tagmanager.edit.containers']

  # Authenticate and construct service.
  service = GetService('tagmanager', 'v2', scope, 'client_secrets.json')

  # Find the greetings container.
  container = FindGreetingsContainer(service, account_path)

if __name__ == '__main__':
  main(sys.argv)
    

JavaScript

/**
 * Interacts with the tagmanager api v2 to create a container, workspace,
 * trigger, and tag.
 *
 * @return {Promise} A promise to run the tag manager example.
 */
function runTagManagerExample() {
  return new Promise((resolve, reject) => {
    console.log('Running Tag Manager Example.');
    var trigger = null;
    var workspace = null;
    findContainer(ACCOUNT_PATH, CONTAINER_NAME)
        .catch(handleError);
    resolve();
  });
}
    

2. Yeni çalışma alanı oluşturma

Aşağıdaki kod snippet'i, tetikleyiciler ve etiketlerde yaptığımız değişiklikleri yönetmek için kullandığımız yeni bir çalışma alanı oluşturmak üzere Etiket Yöneticisi API'sini kullanır. Çalışma alanı oluştururken ayarlanabilen zorunlu ve isteğe bağlı özelliklerin listesi için Workspace create yöntemi referansını inceleyebilirsiniz.

Python

def CreateWorkspace(service, container):
    """Creates a workspace named 'my workspace'.

    Args:
      service: the Tag Manager service object.
      container: the container to insert the workspace within.

    Returns:
      The created workspace.
    """
    return service.accounts().containers().workspaces().create(
        parent=container['path'],
        body={
            'name': 'my workspace',
        }).execute()
    

JavaScript

/**
 * Creates a workspace in the Greetings container.
 *
 * @param {Object} container The container to create a new workspace.
 * @return {Promise} A promise to create a workspace.
 */
function createWorkspace(container) {
  console.log('Creating workspace in container:' + container.path);
  var request = gapi.client.tagmanager.accounts.containers.workspaces.create(
    { 'parent': container.path },
    { name: WORKSPACE_NAME, description: 'my workspace created via api' });
  return requestPromise(request);
}

    

3. Google etiketini oluşturma

Aşağıdaki kod snippet'i, Google etiketi oluşturmak için Etiket Yöneticisi API'sini kullanır. Etiket oluştururken ayarlanabilecek zorunlu ve isteğe bağlı özelliklerin listesi için Etiket oluşturma yöntemi referansını, her etiket türünün özelliklerinin listesi için ise Etiket Sözlüğü Referansı'nı inceleyebilirsiniz.

Python

def CreateHelloWorldTag(service, workspace, tag_id):
  """Create the Google Tag Hello World tag.

  Args:
    service: the Tag Manager service object.
    workspace: the workspace to create a tag within.
    tag_id: the Google tag ID or Google Analytics 4 measurement ID to use.

  Returns:
    The created tag.
  """

  hello_world_tag = {
      'name': 'Google Tag Hello World',
      'type': 'googtag',
      'parameter': [{
          'key': 'tagId',
          'type': 'template',
          'value': str(tag_id),
      }],
  }

  return service.accounts().containers().workspaces().tags().create(
      parent=workspace['path'],
      body=hello_world_tag).execute()

    

JavaScript

/**
 * Creates a Google tag.
 *
 * @param {Object} workspace The workspace to create the tag
 * @return {Promise} A promise to create a hello world tag.
 */
function createHelloWorldTag(workspace) {
  console.log('Creating hello world tag');
  var helloWorldTag = {
    'name': 'Google Tag Hello World',
    'type': 'googtag',
    'parameter':
    [{ 'key': 'tagId', 'type': 'template', 'value': 'G-XXXXXXXXXX' }],
  };
  var request =
    gapi.client.tagmanager.accounts.containers.workspaces.tags.create(
      { 'parent': workspace.path }, helloWorldTag);
  return requestPromise(request);
}

    

4. Etiketi etkinleştirecek tetikleyiciyi oluşturma

Etiket oluşturulduktan sonraki adım, herhangi bir sayfada etkinleşecek bir tetikleyici oluşturmaktır.

Tetikleyici, Hello World Tetikleyicisi olarak adlandırılır ve herhangi bir sayfa görüntüleme için tetiklenir. Örneğin:

Python

def CreateHelloWorldTrigger(service, workspace):
  """Create the Hello World Trigger.

  Args:
    service: the Tag Manager service object.
    workspace: the workspace to create the trigger within.

  Returns:
    The created trigger.
  """

  hello_world_trigger = {
      'name': 'Hello World Rule',
      'type': 'PAGEVIEW'
  }

  return service.accounts().containers().workspaces().triggers().create(
      parent=workspace['path'],
      body=hello_world_trigger).execute()
    

JavaScript

/**
 * Creates a page view trigger.
 *
 * @param {Object} workspace The workspace to create the trigger in.
 * @return {Promise} A promise to create a page view trigger.
 */
function createHelloWorldTrigger(workspace) {
  console.log('Creating hello world trigger in workspace');
  var helloWorldTrigger = { 'name': 'Hello World Trigger', 'type': 'PAGEVIEW' };
  var request =
    gapi.client.tagmanager.accounts.containers.workspaces.triggers.create(
      { 'parent': workspace.path }, helloWorldTrigger);
  return requestPromise(request);
}

    

5. Etiketi, tetikleyiciyle tetiklenecek şekilde güncelleyin.

Etiket ve tetikleyici oluşturulduktan sonra bunların birbiriyle ilişkilendirilmesi gerekir. Bunu yapmak için triggerId öğesini, etiketle ilişkili firingTriggerIds listesine ekleyin. Örneğin:

Python

def UpdateHelloWorldTagWithTrigger(service, tag, trigger):
  """Update a Tag with a Trigger.

  Args:
    service: the Tag Manager service object.
    tag: the tag to associate with the trigger.
    trigger: the trigger to associate with the tag.
  """
  # Get the tag to update.
  tag = service.accounts().containers().workspaces().tags().get(
      path=tag['path']).execute()

  # Update the Firing Trigger for the Tag.
  tag['firingTriggerId'] = [trigger['triggerId']]

  # Update the Tag.
  response = service.accounts().containers().workspaces().tags().update(
      path=tag['path'],
      body=tag).execute()
    

JavaScript

/**
 * Updates a tag to fire on a particular trigger.
 *
 * @param {Object} tag The tag to update.
 * @param {Object} trigger The trigger which causes the tag to fire.
 * @return {Promise} A promise to update a tag to fire on a particular trigger.
 */
function updateHelloWorldTagWithTrigger(tag, trigger) {
  console.log('Update hello world tag with trigger');
  tag['firingTriggerId'] = [trigger.triggerId];
  var request =
    gapi.client.tagmanager.accounts.containers.workspaces.tags.update(
      { 'path': tag.path }, tag);
  return requestPromise(request);
}
    

Ardından, programın ana yürütme dalını, oluşturma ve güncelleme işlevlerini çağıracak şekilde güncelleyin. Örneğin:

Python

def main(argv):
  # Get tag manager account ID from command line.
  assert len(argv) == 2 and 'usage: gtm-api-hello-world.py <account_id>'
  account_id = str(argv[1])
  account_path = 'accounts/%s' % account_id

  # Define the auth scopes to request.
  scope = ['https://www.googleapis.com/auth/tagmanager.edit.containers']

  # Authenticate and construct service.
  service = GetService('tagmanager', 'v2', scope, 'client_secrets.json')

  # Find the greetings container.
  container = FindGreetingsContainer(service, account_path)

  # Create a new workspace.
  workspace = CreateWorkspace(service, container)

  # Create the hello world tag.
  tag = CreateHelloWorldTag(
      service, workspace, 'G-XXXXXXXXXX')

  # Create the hello world Trigger.
  trigger = CreateHelloWorldTrigger(
      service, workspace)

  # Update the hello world tag to fire based on the hello world tag.
  UpdateHelloWorldTagWithTrigger(service, tag, trigger)
if __name__ == '__main__':
  main(sys.argv)
    

JavaScript

/**
 * Interacts with the tagmanager api v2 to create a container, workspace,
 * trigger, and tag.
 *
 * @return {Promise} A promise to run the tag manager example.
 */
function runTagManagerExample() {
  return new Promise((resolve, reject) => {
    console.log('Running Tag Manager Example.');
    var trigger = null;
    var workspace = null;
    findContainer(ACCOUNT_PATH, CONTAINER_NAME)
        .then(createWorkspace)
        .then((createdWorkspace) => {
          workspace = createdWorkspace;
          return createHelloWorldTrigger(workspace);
        })
        .then((createdTrigger) => {
          trigger = createdTrigger;
          return createHelloWorldTag(workspace);
        })
        .then((createdTag) => {
          return updateHelloWorldTagWithTrigger(createdTag, trigger);
        })
        .catch(handleError);
    resolve();
  });
}

    

Eksiksiz Örnek

Kılavuzdaki tüm adımların tam kod örneğini görmek için bu bölümü genişletin.

Python

"""Access and manage a Google Tag Manager account."""

import argparse
import sys

import httplib2

from apiclient.discovery import build
from oauth2client import client
from oauth2client import file
from oauth2client import tools


def GetService(api_name, api_version, scope, client_secrets_path):
  """Get a service that communicates to a Google API.

  Args:
    api_name: string The name of the api to connect to.
    api_version: string The api version to connect to.
    scope: A list of strings representing the auth scopes to authorize for the
      connection.
    client_secrets_path: string A path to a valid client secrets file.

  Returns:
    A service that is connected to the specified API.
  """
  # Parse command-line arguments.
  parser = argparse.ArgumentParser(
      formatter_class=argparse.RawDescriptionHelpFormatter,
      parents=[tools.argparser])
  flags = parser.parse_args([])

  # Set up a Flow object to be used if we need to authenticate.
  flow = client.flow_from_clientsecrets(
      client_secrets_path, scope=scope,
      message=tools.message_if_missing(client_secrets_path))

  # Prepare credentials, and authorize HTTP object with them.
  # If the credentials don't exist or are invalid run through the native client
  # flow. The Storage object will ensure that if successful the good
  # credentials will get written back to a file.
  storage = file.Storage(api_name + '.dat')
  credentials = storage.get()
  if credentials is None or credentials.invalid:
    credentials = tools.run_flow(flow, storage, flags)
  http = credentials.authorize(http=httplib2.Http())

  # Build the service object.
  service = build(api_name, api_version, http=http)

  return service

def FindGreetingsContainer(service, account_path):
  """Find the greetings container.

  Args:
    service: the Tag Manager service object.
    account_path: the path of the Tag Manager account from which to retrieve the
      Greetings container.

  Returns:
    The greetings container if it exists, or None if it does not.
  """
  # Query the Tag Manager API to list all containers for the given account.
  container_wrapper = service.accounts().containers().list(
      parent=account_path).execute()

  # Find and return the Greetings container if it exists.
  for container in container_wrapper['container']:
    if container['name'] == 'Greetings':
      return container
  return None

def CreateWorkspace(service, container):
    """Creates a workspace named 'my workspace'.

    Args:
      service: the Tag Manager service object.
      container: the container to insert the workspace within.

    Returns:
      The created workspace.
    """
    return service.accounts().containers().workspaces().create(
        parent=container['path'],
        body={
            'name': 'my workspace',
        }).execute()

def CreateHelloWorldTag(service, workspace, tag_id):
  """Create the Google Tag Hello World tag.

  Args:
    service: the Tag Manager service object.
    workspace: the workspace to create a tag within.
    tag_id: the Google tag ID or Google Analytics 4 measurement ID to use.

  Returns:
    The created tag.
  """

  hello_world_tag = {
      'name': 'Google Tag Hello World',
      'type': 'googtag',
      'parameter': [{
          'key': 'tagId',
          'type': 'template',
          'value': str(tag_id),
      }],
  }

  return service.accounts().containers().workspaces().tags().create(
      parent=workspace['path'],
      body=hello_world_tag).execute()


def CreateHelloWorldTrigger(service, workspace):
  """Create the Hello World Trigger.

  Args:
    service: the Tag Manager service object.
    workspace: the workspace to create the trigger within.

  Returns:
    The created trigger.
  """

  hello_world_trigger = {
      'name': 'Hello World Rule',
      'type': 'PAGEVIEW'
  }

  return service.accounts().containers().workspaces().triggers().create(
      parent=workspace['path'],
      body=hello_world_trigger).execute()

def UpdateHelloWorldTagWithTrigger(service, tag, trigger):
  """Update a Tag with a Trigger.

  Args:
    service: the Tag Manager service object.
    tag: the tag to associate with the trigger.
    trigger: the trigger to associate with the tag.
  """
  # Get the tag to update.
  tag = service.accounts().containers().workspaces().tags().get(
      path=tag['path']).execute()

  # Update the Firing Trigger for the Tag.
  tag['firingTriggerId'] = [trigger['triggerId']]

  # Update the Tag.
  response = service.accounts().containers().workspaces().tags().update(
      path=tag['path'],
      body=tag).execute()

def main(argv):
  # Get tag manager account ID from command line.
  assert len(argv) == 2 and 'usage: gtm-api-hello-world.py <account_id>'
  account_id = str(argv[1])
  account_path = 'accounts/%s' % account_id

  # Define the auth scopes to request.
  scope = ['https://www.googleapis.com/auth/tagmanager.edit.containers']

  # Authenticate and construct service.
  service = GetService('tagmanager', 'v2', scope, 'client_secrets.json')

  # Find the greetings container.
  container = FindGreetingsContainer(service, account_path)

  # Create a new workspace.
  workspace = CreateWorkspace(service, container)

  # Create the hello world tag.
  tag = CreateHelloWorldTag(
      service, workspace, 'G-XXXXXXXXXX')

  # Create the hello world Trigger.
  trigger = CreateHelloWorldTrigger(
      service, workspace)

  # Update the hello world tag to fire based on the hello world tag.
  UpdateHelloWorldTagWithTrigger(service, tag, trigger)
  
if __name__ == '__main__':
  main(sys.argv)

    

JavaScript

<html>
  <head>
    <script type="text/javascript">

    // Your Client ID can be retrieved from your project in the Google
    // Developer Console, https://console.developers.google.com
    var CLIENT_ID = TODO;
    var SCOPES = [
      'https://www.googleapis.com/auth/tagmanager.manage.accounts',
      'https://www.googleapis.com/auth/tagmanager.edit.containers',
      'https://www.googleapis.com/auth/tagmanager.delete.containers',
      'https://www.googleapis.com/auth/tagmanager.edit.containerversions',
      'https://www.googleapis.com/auth/tagmanager.manage.users',
      'https://www.googleapis.com/auth/tagmanager.publish'
    ];

    // Parameter values used by the script
    ACCOUNT_PATH = TODO; // such as: 'accounts/555555';
    CONTAINER_NAME = 'Greetings';
    WORKSPACE_NAME = 'Example workspace';

    /**
     * Check if current user has authorization for this application.
     *
     * @param {bool} immediate Whether login should use the "immediate mode",
     *     which causes the security token to be refreshed behind the scenes
     *     with no UI.
     */
    function checkAuth(immediate) {
      var authorizeCheckPromise = new Promise((resolve) => {
        gapi.auth.authorize(
          { client_id: CLIENT_ID, scope: SCOPES.join(' '), immediate: immediate },
          resolve);
      });
      authorizeCheckPromise
          .then(handleAuthResult)
          .then(loadTagManagerApi)
          .then(runTagManagerExample)
          .catch(() => {
            console.log('You must authorize any access to the api.');
          });
    }

    /**
     * Check if current user has authorization for this application.
     */
    function checkAuth() {
      checkAuth(true);
    }

    /**
     * Initiate auth flow in response to user clicking authorize button.
     *
     * @param {Event} event Button click event.
     * @return {boolean} Returns false.
     */
    function handleAuthClick(event) {
      checkAuth();
      return false;
    }

    /**
     * Handle response from authorization server.
     *
     * @param {Object} authResult Authorization result.
     * @return {Promise} A promise to call resolve if authorize or redirect to a
     *   login flow.
     */
    function handleAuthResult(authResult) {
      return new Promise((resolve, reject) => {
        var authorizeDiv = document.getElementById('authorize-div');
        if (authResult && !authResult.error) {
          // Hide auth UI, then load client library.
          authorizeDiv.style.display = 'none';
          resolve();
        } else {
          // Show auth UI, allowing the user to initiate authorization by
          // clicking authorize button.
          authorizeDiv.style.display = 'inline';
          reject();
        }
      });
    }

    /**
     * Load Tag Manager API client library.

     * @return {Promise} A promise to load the tag manager api library.
     */
    function loadTagManagerApi() {
      return new Promise((resolve, reject) => {
        console.log('Load Tag Manager api');
        gapi.client.load('tagmanager', 'v2', resolve);
      });
    }

    /**
     * Interacts with the tagmanager api v2 to create a container,
     * workspace, trigger, and tag.
     *
     * @return {Promise} A promise to run the tag manager example.
     */
    function runTagManagerExample() {
      return new Promise((resolve, reject) => {
        console.log('Running Tag Manager Example.');
        var trigger = null;
        var workspace = null;
        findContainer(ACCOUNT_PATH, CONTAINER_NAME)
            .then(createWorkspace)
            .then((createdWorkspace) => {
              workspace = createdWorkspace;
              return createHelloWorldTrigger(workspace);
            })
            .then((createdTrigger) => {
              trigger = createdTrigger;
              return createHelloWorldTag(workspace);
            })
            .then((createdTag) => {
              return updateHelloWorldTagWithTrigger(createdTag, trigger);
            })
            .catch(handleError);
        resolve();
      });
    }

    /**
     * Returns the greetings container if it exists.
     *
     * @param {string} accountPath The account which contains the Greetings
     *     container.
     * @param {string} containerName The name of the container to find.
     * @return {Promise} A promise to find the greetings container.
     */
    function findContainer(accountPath, containerName) {
      console.log('Finding container in account:' + accountPath);
      var request = gapi.client.tagmanager.accounts.containers.list({
        'parent': accountPath
      });
      return requestPromise(request)
          .then((response) => {
            var containers = response.container || [];
            var container = containers.find(
                (container) => container.name === containerName);
            return container || Promise.reject(
                'Unable to find ' + containerName +' container.');
          });
    }

    /**
     * Creates a workspace in the Greetings container.
     *
     * @param {Object} container The container to create a new workspace.
     * @return {Promise} A promise to create a workspace.
     */
    function createWorkspace(container) {
      console.log('Creating workspace in container:' + container.path);
      var request = gapi.client.tagmanager.accounts.containers.workspaces.create(
        { 'parent': container.path },
        { name: WORKSPACE_NAME, description: 'my workspace created via api' });
      return requestPromise(request);
    }

    /**
     * Creates a page view trigger.
     *
     * @param {Object} workspace The workspace to create the trigger in.
     * @return {Promise} A promise to create a page view trigger.
     */
    function createHelloWorldTrigger(workspace) {
      console.log('Creating hello world trigger in workspace');
      var helloWorldTrigger =
          { 'name': 'Hello World Trigger', 'type': 'PAGEVIEW' };
      var request =
        gapi.client.tagmanager.accounts.containers.workspaces.triggers.create(
          { 'parent': workspace.path }, helloWorldTrigger);
      return requestPromise(request);
    }

    /**
    * Creates a Google tag.
    *
    * @param {Object} workspace The workspace to create the tag
    * @return {Promise} A promise to create a hello world tag.
    */
    function createHelloWorldTag(workspace) {
      console.log('Creating hello world tag');
      var helloWorldTag = {
        'name': 'Google Tag Hello World',
        'type': 'googtag',
        'parameter':
        [{ 'key': 'tagId', 'type': 'template', 'value': 'G-XXXXXXXXXX' }],
      };
      var request =
        gapi.client.tagmanager.accounts.containers.workspaces.tags.create(
          { 'parent': workspace.path }, helloWorldTag);
      return requestPromise(request);
    }

    /**
     * Updates a tag to fire on a particular trigger.
     *
     * @param {Object} tag The tag to update.
     * @param {Object} trigger The trigger which causes the tag to fire.
     * @return {Promise} A promise to update a tag to fire on a particular
     *    trigger.
     */
    function updateHelloWorldTagWithTrigger(tag, trigger) {
      console.log('Update hello world tag with trigger');
      tag['firingTriggerId'] = [trigger.triggerId];
      var request =
        gapi.client.tagmanager.accounts.containers.workspaces.tags.update(
          { 'path': tag.path }, tag);
      return requestPromise(request);
    }

    /**
     * Logs an error message to the console.
     *
     * @param {string|Object} error The error to log to the console.
     */
    function handleError(error) {
      console.log('Error when interacting with GTM API');
      console.log(error);
    }

    /**
     * Wraps an API request into a promise.
     *
     * @param {Object} request the API request.
     * @return {Promise} A promise to execute the api request.
     */
    function requestPromise(request) {
      return new Promise((resolve, reject) => {
        request.execute((response) => {
          if (response.code) {
            reject(response);
          }
          resolve(response);
        });
      });
    }
    </script>

    <script src="https://apis.google.com/js/client.js?onload=checkAuth">
    </script>
  </head>
  <body>
    <div id="authorize-div" style="display: none">
      <span>Authorize access to Tag Manager API</span>
      <!--Button for the user to click to initiate auth sequence -->
      <button id="authorize-button" onclick="handleAuthClick(event)">
        Authorize
      </button>
    </div>
    <pre id="output"></pre>
  </body>
</html>

    

Sonraki Adımlar

API'nin işleyiş şeklini öğrendiğinize göre, yararlanabileceğiniz bazı ek kaynaklar şunlardır: