How To Use The Google Tag Manager API

by Adam Hill

Using the Google Tag Manager (GTM) API can be a frustrating exercise. Client libraries in particular have limited documentation to learn from and even fewer concrete examples. In this post, I’ll explain the PHP client library (available here) and how to use it for some common auditing operations.

Getting Started

Setup

Setting up the GTM PHP library consists of 3 steps:

  1. Create a Google account (you probably already have one)
  2. Create a project in the Google API Console (see the Managing Projects page)
  3. Install the library

This post will not go into the details of these items. On the 3rd item, I’ll assume that the library has been downloaded locally.

Authenticating and Authorizing

There are two types of access that can be used for API calls: simple and authorized. Simple API access does not access private user data and so is not suitable to this work. Authorized API access, on the other hand, does have access to private user data, and uses OAuth 2.0 to authenticate. Authorized API access is a typical requirement for most GTM API operations so plan to get OAuth working in your app.

For your application to have authorized access, the owner of the private data (the person that owns the GTM container of interest in our case) must grant your application access. This is all accomplished with OAuth 2.0 libraries. What does this look like in practice? If you are writing an application that will interrogate a client’s GTM account, that client will have to add your application as a user to the GTM account you are targeting. It is important to have the correct permission level assigned to the user account for your application. For instance, if you plan on creating entities in a GTM container, your application would need Editor-level permission in that GTM account.

Using the API

Before getting into the details of the API, it is important to point out that we are skipping over the details of setting up your application, API tokens, client ID and client secret. These are important concepts that should be well understood but they lie outside of the scope of this post. To get more familiar with the concepts, this is a good place to start.

Initializing the App

With that out of the way, let’s dig in. We’ll be discussing a Server-to-Server application. In that scenario, we’ll be calling our PHP script from our dev server which will interrogate a Google server hosting the GTM containers of interest. This is an important distinction from the Web Server Application context especially with respect to OAuth 2.0 configuration.

To get the script up and running, we first need to construct the client object. The client object is the container used for classes and configuration in the API library. In its simplest form, the client object can be constructed as follows:

$client = new Google_Client();
$client->setApplicationName("My App Name");

The client object is also where we provide the authentication configuration. Our example has downloaded the credentials JSON file to be referenced by our application. We configure this as follows:

$KEY_FILE_LOCATION = __DIR__ . '/service-account-credentials.json';
$client->setAuthConfig($KEY_FILE_LOCATION);

Next, we configure the scope of our API interactions. The GTM API offers 7 different API scopes which offer various levels of interaction with the GTM components. Because our example today only needs to read the configuration of the containers, we use the https://www.googleapis.com/auth/tagmanager.readonly scope. It gets set like this:

$client->setScopes(['https://www.googleapis.com/auth/tagmanager.readonly']);

The last step is to build the service object. API services are directed through queries to a service object that is specific to the service you want to interact with, GTM in our case. To construct this object, we instantiate a new service object and pass our newly created client object to it:

$analytics = new Google_Service_TagManager($client);

We now have everything we need to start hitting the API.

Calling the API

The GTM API provides access to resources and methods from the service object that we created above. Syntactically, the service, resource and method are linked in the style of a standard PHP method chain $service->resource->method(args). Most methods require some arguments but will also accept a parameter array as a final parameter. The following image provides an overview of the parent-child relationship of GTM resources. This will help us determine where to look in the API for the methods we need.

We can now construct a simple Hello World style script to confirm that our script initialization is successful and to confirm we have connectivity between our services account and our GTM account. Let’s start by asking for a list of accounts that our service app has access to. To do this, we will use the listAccounts() method provided by the accounts GTM resource. This looks like:

$analytics->accounts->listAccounts('~all')

Where $analytics is the service object we just created, accounts is a GTM resouce and listAccounts() is a method available to the accounts resource.

Our script now looks like the following:

<?php

//path to the GA PHP API script
require_once __DIR__ . '/google-api-php-client-2.1.3/vendor/autoload.php';

$analyticsObj = initializeAnalytics();
getAccounts($analyticsObj);

function initializeAnalytics() {

//Create variable for the service account credentials file
$KEY_FILE_LOCATION = __DIR__ . '/service-account-credentials.json';

//Create client variable
$client = new Google_Client();
$client->setApplicationName("Container App");
$client->setAuthConfig($KEY_FILE_LOCATION);
$client->setScopes(['https://www.googleapis.com/auth/tagmanager.readonly']);
$analytics = new Google_Service_TagManager($client);

return $analytics;
}

function getAccounts($analytics_obj) {

 //Get all Account IDs the user has access to
 $accounts = $analytics_obj->accounts
 ->listAccounts('~all');

 print_r ($accounts);
}

If everything has worked, you should get  something like the following:

Google_Service_TagManager_ListAccountsResponse Object
(
   [collection_key:protected] => accounts
   [accountsType:protected] => Google_Service_TagManager_Account
   [accountsDataType:protected] => array
   [internal_gapi_mappings:protected] => Array
       (
       )

   [modelData:protected] => Array
       (
           [accounts] => Array
               (
                   [0] => Array
                       (
                           [accountId] => #####
                           [name] => ACME1
                       )

                   [1] => Array
                       (
                           [accountId] => #####
                           [name] => ACME2
                       )

                   [2] => Array
                       (
                           [accountId] => #####
                           [name] => ACME3
                       )
               )

       )

   [processed:protected] => Array
       (
       )

)

In general, the best way to determine which methods are available is to look directly at the API code. The API directory structure is initially organized by the service type. Inside each service is a directory listing the resources and, more importantly, their machine names.

For instance you may want a script that lists all containers that belong to an account. To get a sense of where to start, it is often instructive to look at the base Google GTM API for the resource you’re interested in, in this case Containers. In the Methods list, we see there is a list method. Therefore, we should expect a list type operation in the PHP library. In the Resource directory of the GTM portion of the API, we find a AccountsContainers.php file. Examining this file, we find a listAccountsContainers function which is the method we’ll want to call. Examining the function definition also gives us the required parameters:

public function listAccountsContainers($accountId, $optParams = array())

We see that we need to pass an account ID. We saw in our first completed script how to generate the account IDs available to your service app. You may have noticed that the methods listed in the PHP files in the Resource directory provide methods that apply to collections of resources, Accounts instead of a specific Account for instance. To find the specifics of the methods available to individual instances of the resources (a specific account for instance), examine the PHP files with the singular version of the name of the resource you are interested in. So, to have a specific account ID returned via the PHP API library, we can use the getAccountId() function described in the Account.php file.

Listing all the container associated with an account might look like the following:

function getContainers($analytics_obj) {

 //Get all Account IDs the user has access to
 $accounts = $analytics_obj->accounts
 ->listAccounts('~all');

 foreach ($accounts->getAccounts() as $account) {

   //now use the account ID to get the containers
   $containers = $analytics->accounts_containers
   ->listAccountsContainers($account->getAccountId());
   print_r ($containers);

 }
}

To go one level deeper, perhaps you want to now list all of the tags associated with the containers. You may have intuited from the parent-child diagram above that if you want to access methods from the Tags resource, you need to access the Containers resource, but how specifically do you do that? In fact, the reader may have noticed that Tags are actually a child of Workspaces but tags may also be accessed directly from Containers. A similar exercise can be undertaken to find the specifics of the list type function for tags.

In the Resource directory of the GTM portion of the API, we find a AccountsContainersTags.php file. Examining this file we find a listAccountsContainersTags function which is likely the method we’ll want to call. Examining the function defintion also gives us the required parameters:

public function listAccountsContainersTags($accountId, $containerId, $optParams = array())

Since we are one level lower in the parent-child relationships, to retrieve the tags we need to pass an account ID and a container ID. So, whereas you had to first get an individual account to ask for a list of containers, we now have to get an individual container to ask for a list of tags. Putting it all together, we get the following:

<?php

//path to the GA PHP API script
require_once __DIR__ . '/google-api-php-client-2.1.3/vendor/autoload.php';

$analyticsObj = initializeAnalytics();
getGtmElements($analyticsObj);

function initializeAnalytics() {

 //Create variable for the service account credentials file
 $KEY_FILE_LOCATION = __DIR__ . '/service-account-credentials.json';

 //Create client variable
 $client = new Google_Client();
 $client->setApplicationName("Container App");
 $client->setAuthConfig($KEY_FILE_LOCATION);
 $client->setScopes(['https://www.googleapis.com/auth/tagmanager.readonly']);
 $analytics = new Google_Service_TagManager($client);

 return $analytics;
}

function getGtmElements($analytics_obj) {

 //Get all Account IDs the user has access to
 $accounts = $analytics_obj->accounts->listAccounts('~all');

 foreach ($accounts->getAccounts() as $account) {

   //now use the account ID to get the containers
   $containers = $analytics->accounts_containers->listAccountsContainers($account->getAccountId());

   foreach ($containers->getContainers() as $container) {
     $containerTags = $analytics->accounts_containers_tags->listAccountsContainersTags($account->getAccountId(), $container->getContainerId());

     //Do more things...

     }
   }
 }
}

We’ve shown how to get started using the GTM API PHP Client Library and how to start manipulating entities at different levels of the GTM configuration hierarchy. Hopefully this provides a good starting point for your GTM application. Make extensive use of browsing the client API package to discover how to implement some of the more interesting API calls like creating and removing tags and triggers!

Adam Hill

Implementation Specialist

Adam Hill is an Implementation Specialist at Napkyn Analytics. With a background in software development, data visualization, and physics, he brings a rich blend of experience to our clients as they work to transform and evolve their analytics technology practices.

See more posts from Adam