Google Tag Manager API - Developer's Guide

This developer's guide walks you through the steps required to access a Google Tag Manager account, and create and manage entities using the Tag Manager API.

Introduction

This guide walks you through various steps to access and configure a Google Tag Manager account. Upon completion you will have a basic understanding of how to do the following tasks:

  • Create a Tag Manager service object.
  • Authenticate and authorize a user.
  • Work with the Tag Manager API to access and manage resources.

Before you begin

Before you begin the guide, we recommend that you become familiar with Google Tag Manager by visiting the following sites:

  • How to get started – a user guide on how to get started with Google Tag Manager.
  • API Reference – learn about the API interface and supported operations.

Using a test account

If you intend to use the Tag Manager API to create, configure, or delete entities, we recommend that you implement and verify your code with a test account. Using a test account will help prevent you from making accidental changes to an active account. Once you've tested and confirmed that your code is working as expected using the test account, then you can start using the implementation with your real accounts.

Select a language

Multiple programming languages are covered in this guide. Select the language you intend to follow:

Java


Java is selected for all code snippets in this guide.

Python


Python is selected for all code snippets in this guide.

Program overview

The example program included in this guide is a command-line app. Given an account ID, the app finds a container named Greetings and creates a Universal Analytics tag in that container. When a user visits hello-world.html, the tag sends a pageview hit.

To develop this application, you need to follow these steps:

  1. Set up your environment and project in the Google API Console.
  2. Create a Tag Manager service object.
    1. Authorize access to a Tag Manager account.
    2. Create a Tag Manager service object.
  3. Query the API, handle the response, and output the results.
    1. Get an initialized Tag Manager service object.
    2. Use the Tag Manager service object to query the Tag Manager API to do the following tasks:
      1. Retrieve the Greetings container for the authenticated Google Tag Manager account.
      2. Create the Universal Analytics tag.
      3. Create the rule to fire the tag.
      4. Update the tag to fire on the rule.

Set up your environment and project

Create the Greetings container

This guide assumes you have a Google Tag Manager account with a container named Greetings. Follow the instructions for Setup and Workflow (Web) to create an Account and a Container named Greetings.

Install a client library

Before you start, install and configure a Google APIs client library.

Create and configure a project in the Google API Console

To get started using Tag Manager API, you need to first use the setup tool, which guides you through creating a project in the Google API Console, enabling the API, and creating credentials.

This guide uses an Installed Application authentication flow. Follow the instructions below to create your project credentials. When prompted, select Installed Application for APPLICATION TYPE and Other for INSTALLED APPLICATION TYPE.

  1. From the Credentials page, click Create credentials > OAuth client ID to create your OAuth 2.0 credentials or Create credentials > Service account key to create a service account.
  2. If you created an OAuth client ID, then select your application type.
  3. Fill in the form and click Create.

Your application's client IDs and service account keys are now listed on the Credentials page. For details, click a client ID; parameters vary depending on the ID type, but might include email address, client secret, JavaScript origins, or redirect URIs.

Download the client details by clicking the Download JSON button. Rename this file to client_secrets.json. This file will be used later on for authentication purposes.

Create a Tag Manager service object

The Tag Manager service object is what you'll use to make API requests.

The steps required to create a Tag Manager service object are as follows:

  1. Authorize access to a Google Tag Manager account.
  2. Instantiate the Tag Manager service object.

Authorize access to a Google Tag Manager account

When a user starts an application built with the Google Tag Manager API, they will have to grant the application access to their Google Tag Manager account. This process is called authorization. The recommended method for authorizing users is OAuth 2.0. If you'd like to learn more, read Tag Manager API Authorization.

The code below uses the project and client details created above to authenticate the user of the application and asks their permission to access Google Tag Manager on their behalf.

The application will attempt to open the default browser and navigate the user to a URL hosted on google.com. The user will be prompted to sign-in and grant the application access to their Tag Manager account. Once granted, the application will attempt to read a code from the browser window, then close the window.

Note: If an error occurs, the application will instead prompt the user to enter their authorization code on the command line.

Java

/**
 * Access and manage a Google Tag Manager account.
 */

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.tagmanager.Tagmanager;
import com.google.api.services.tagmanager.TagmanagerScopes;
import com.google.api.services.tagmanager.model.Condition;
import com.google.api.services.tagmanager.model.Container;
import com.google.api.services.tagmanager.model.Parameter;
import com.google.api.services.tagmanager.model.Rule;
import com.google.api.services.tagmanager.model.Tag;

import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class HelloWorld {
  // Path to client_secrets.json file downloaded from the Developer's Console.
  // The path is relative to HelloWorld.java.
  private static final String CLIENT_SECRET_JSON_RESOURCE = "client_secrets.json";

  // The directory where the user's credentials will be stored for the application.
  private static final File DATA_STORE_DIR = new File("PATH_TO_DIRECTORY");

  private static final String APPLICATION_NAME = "HelloWorld";
  private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
  private static NetHttpTransport httpTransport;
  private static FileDataStoreFactory dataStoreFactory;

  public static void main(String[] args) {
    try {
      httpTransport = GoogleNetHttpTransport.newTrustedTransport();
      dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);

      // Authorization flow.
      Credential credential = authorize();
      Tagmanager manager = new Tagmanager.Builder(httpTransport, JSON_FACTORY, credential)
          .setApplicationName(APPLICATION_NAME).build();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  private static Credential authorize() throws Exception {
    // Load client secrets.
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
        new InputStreamReader(HelloWorld.class.getResourceAsStream(CLIENT_SECRET_JSON_RESOURCE)));

    // Set up authorization code flow for all auth scopes.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport,
        JSON_FACTORY, clientSecrets, TagmanagerScopes.all()).setDataStoreFactory(dataStoreFactory)
        .build();

    // Authorize.
    return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
  }
}

    

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', 'v1', scope, 'client_secrets.json')


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

Query the Tag Manager API

The Tag Manager service object can be used to query the Tag Manager API. The following steps are required to implement the sample program:

  1. Retrieve the Greetings container
  2. Create the Universal Analytics tag
  3. Create the rule to fire the tag
  4. Update the tag to fire on the rule

1. Retrieve the Greetings container

The following function illustrates how a Tag Manager service object can be used to query the Tag Manager API to list all containers of an account and retrieve the container named Greetings.

Java

  /*
   * Find the greetings container ID.
   *
   * @param service the Tag Manager service object.
   * @param accountId the ID of the Tag Manager account from which to retrieve the
   *    Greetings container.
   *
   * @return the greetings container if it exists.
   *
   */
  private static Container findGreetingsContainer(Tagmanager service, String accountId)
      throws Exception {
    for (Container container :
        service.accounts().containers().list(accountId).execute().getContainers()) {
      if (container.getName().equals("Greetings")) {
        return container;
      }
    }
    throw new IllegalArgumentException("No container named Greetings in given account");
  }
    

Python

def FindGreetingsContainerId(service, account_id):
  """Find the greetings container ID.

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

  Returns:
    The dictionary that represents 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(
      accountId=account_id).execute()

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

Next update the main execution branch of the program to call the findGreetingsContainer function given a Tag Manager accountId. For example:

Java

  public static void main(String[] args) {
    try {
      httpTransport = GoogleNetHttpTransport.newTrustedTransport();
      dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);

      // Authorization flow.
      Credential credential = authorize();
      Tagmanager manager = new Tagmanager.Builder(httpTransport, JSON_FACTORY, credential)
          .setApplicationName(APPLICATION_NAME).build();

      // Get tag manager account ID.
      String accountId = args[0];

      // Find the greetings container.
      Container greetings = findGreetingsContainer(manager, accountId);

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
    

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

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

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

  # Find the greetings container.
  container_id = FindGreetingsContainerId(service, account_id)
    

2. Create the Universal Analytics tag

The following code snippet uses the Tag Manager API to create a Universal Analytics tag. You can review the Tag create method reference for the list of required and optional properties that can be set when creating a tag and the Tag Dictionary Reference for a list of properties for each tag type.

Java

  /**
   * Create the Universal Analytics Hello World Tag.
   *
   * @param accountId the ID of the account holding the container.
   * @param containerId the ID of the container to create the tag in.
   * @param service the Tag Manager service object.
   * @return the newly created Tag resource.
   */
  private static Tag createHelloWorldTag(String accountId, String containerId, Tagmanager service) {
    Tag ua = new Tag();
    ua.setName("Universal Analytics Hello World");
    ua.setType("ua");

    List<Parameter> uaParams = new ArrayList<Parameter>();
    Parameter trackingId = new Parameter();
    trackingId.setKey("trackingId").setValue(UA_TRACKING_ID).setType("template");
    uaParams.add(trackingId);

    ua.setParameter(uaParams);
    ua = service.accounts().containers().tags().create(accountId, containerId, ua)
        .execute();

    return ua;
  }

    

Python

def CreateHelloWorldTag(service, account_id, container_id, tracking_id):
  """Create the Universal Analytics Hello World Tag.

  Args:
    service: the Tag Manager service object.
    account_id: the ID of the account holding the container.
    container_id: the ID of the container to create the tag in.
    tracking_id: the Universal Analytics tracking ID to use.

  Returns:
    The API response as a dict representing the newly created Tag resource
    or an error.
  """

  hello_world_tag = {
      'name': 'Universal Analytics Hello World',
      'type': 'ua',
      'parameter': [{
          'key': 'trackingId',
          'type': 'template',
          'value': str(tracking_id),
      }],
  }

  response = service.accounts().containers().tags().create(
      accountId=account_id,
      containerId=container_id,
      body=hello_world_tag).execute()

  return response

    

3. Create the rule to fire the tag

Now that a tag has been created, the next step is to create a Rule that will fire on any page ending in hello-world.html.

The rule will be named Hello World Rule and will fire based on a single condition using the endsWith condition type. For example:

Java

  /**
   * Create the Hello World Rule.
   *
   * @param accountId the ID of the account holding the container.
   * @param containerId the ID of the container to create the rule in.
   * @param service the Tag Manager service object.
   *
   * @return the newly created Rule resource.
   **/
  private static Rule createHelloWorldRule(String accountId, String containerId, Tagmanager service) {
    Rule helloWorld = new Rule();
    helloWorld.setName("Hello World");

    List<Condition> conditions = new ArrayList<Condition>();
    Condition endsWithHelloWorld = new Condition();
    endsWithHelloWorld.setType("endsWith");
    List<Parameter> params = new ArrayList<Parameter>();
    params.add(new Parameter().setKey("arg0").setValue("{{url}}").setType("template"));
    params.add(new Parameter().setKey("arg1").setValue("hello-world.html").setType("template"));
    endsWithHelloWorld.setParameter(params);
    conditions.add(endsWithHelloWorld);

    helloWorld.setCondition(conditions);
    helloWorld = service.accounts().containers().rules().create(accountId, containerId, helloWorld)
        .execute();

    return helloWorld;
  }

    

Python

def CreateHelloWorldRule(service, account_id, container_id):
  """Create the Hello World Rule.

  Args:
    service: the Tag Manager service object.
    account_id: the ID of the account holding the container.
    container_id: the ID of the container to create the rule in.

  Returns:
    The API response as a dict representing the newly created Rule resource
    or an error.
  """

  hello_world_rule = {
      'name': 'Hello World Rule',
      'condition': [{
          'parameter': [
              {'key': 'arg0', 'type': 'template', 'value': '{{url}}'},
              {'key': 'arg1', 'type': 'template', 'value': 'hello-world.html'},
          ],
          'type': 'endsWith',
      }]
  }

  response = service.accounts().containers().rules().create(
      accountId=account_id,
      containerId=container_id,
      body=hello_world_rule).execute()

  return response

    

4. Update the tag to fire on the rule

Now that a tag and rule have been created they need to be assocated with each other. To do this add the ruleId to the list of firingRuleIds associated with the tag. For example:

Java

  /**
   * Update a Tag with a Rule.
   *
   * @param tag the tag to associate with the rule.
   * @param rule the rule to associate with the tag.
   *
   */
  private static void fireTagOnRule(Tag tag, Rule rule) {
    List<String> firingRuleIds = new ArrayList<String>();
    firingRuleIds.add(rule.getRuleId());
    tag.setFiringRuleId(firingRuleIds);
  }
    

Python

def UpdateHelloWorldTagWithRule(service, account_id, container_id, tag_id,
                                rule_id):
  """Update a Tag with a Rule.

  Args:
    service: the Tag Manager service object.
    account_id:  the ID of the account holding the container.
    container_id: the ID of the container to create the rule in.
    tag_id: the ID of the tag to associate with the rule.
    rule_id: the ID of the rule to associate with the tag.
  """
  # Get the tag to update.
  tag = service.accounts().containers().tags().get(
      accountId=account_id,
      containerId=container_id,
      tagId=tag_id).execute()

  # Update the Firing Rule for the Tag.
  tag['firingRuleId'] = [rule_id]

  # Update the Tag.
  response = service.accounts().containers().tags().update(
      accountId=account_id,
      containerId=container_id,
      tagId=tag_id,
      body=tag).execute()
    

Next update the main execution branch of the program to call the create and update functions. For example:

Java

  public static void main(String[] args) {
    try {
      httpTransport = GoogleNetHttpTransport.newTrustedTransport();
      dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);

      // Authorization flow.
      Credential credential = authorize();
      Tagmanager manager = new Tagmanager.Builder(httpTransport, JSON_FACTORY, credential)
          .setApplicationName(APPLICATION_NAME).build();

      // Get tag manager account ID.
      String accountId = args[0];

      // Find the greetings container.
      Container greetings = findGreetingsContainer(manager, accountId);
      String containerId = greetings.getContainerId();

      // Create the hello world tag.
      Tag ua = createUATag(accountId, containerId, manager);

      // Create the hello world rule.
      Rule hello = createHelloWorldRule(accountId, containerId, manager);

      // Update the hello world tag to fire based on the hello world tag.
      fireTagOnRule(ua, hello);
      ua = manager.accounts().containers().tags().update(accountId, containerId, ua.getTagId(), ua)
          .execute();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
    

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

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

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

  # Find the greetings container.
  container_id = FindGreetingsContainerId(service, account_id)

  # Create the hello world tag.
  tag = CreateHelloWorldTag(service, account_id, container_id, 'UA-1234-5')

  # Create the hello world rule.
  rule = CreateHelloWorldRule(service, account_id, container_id)

  # Update the hello world tag to fire based on the hello world tag.
  UpdateHelloWorldTagWithRule(service, account_id, container_id, tag['tagId'], rule['ruleId'])
    

Next Steps

Now that you're familiar with how the API works, there are some additional resources for you: