GTM API Overview: Automate Google Tag Manager Management
GTM API can be very handy If you are using Google Tag Manager on a daily basis. This guide is an introduction on how to use the API to automate repetitive work. We will show you how to set up access and get started with fetching GTM’s data (containers, accounts, etc).
GA4’s API
We also wrote a guide on how to get started with GA4 API a while ago. Feel free to check it out after finishing this article.
Enable GTM API In Your Google Cloud Project
Section titled “Enable GTM API In Your Google Cloud Project”You need a Google cloud project. If you already have one, you can enable the API directly.
Enable GTM’s API
Section titled “Enable GTM’s API”You can name it whatever you want. Next, use search for “APIs” using the search bar.
Alternatively, you can click on APIs and services, and select Enable APIs and services.
Lastly, look for Google Tag Manager and enable the API.
Create a Service Account for GTM API Access
Section titled “Create a Service Account for GTM API Access”What is a service account?
A service account in Google Cloud Platform allows our python app to perform specific tasks like accessing Google Tag Manager remotely.
Create a new service account To interact with GTM API
Section titled “Create a new service account To interact with GTM API”We need to create a new service account to enable our python scripts to control Google Tag Manager.
Generate a Key
Section titled “Generate a Key”Once you set it up, you will be able to see it in the service accounts list. Click on your newly created service account. Generate a new key and download the file.
Add the service account email address to Google Tag Manager
Section titled “Add the service account email address to Google Tag Manager”Like a human user, the service account needs permission to access your accounts. You need to browse to GTM and open the admin panel.
Access Google Tag Manager using GTM API
Section titled “Access Google Tag Manager using GTM API”Let’s create a folder on our computer to store scripts. Next, move the JSON file that contains the key we downloaded to the folder.
Rename the JSON key to just **key.json** as in the screenshot. Next, add a file and name it whatever you want as long as the extension is .ipynb (we are using a Jupyter notebook for better data visualization experience).
Configure libraries and modules to interact with Google Tag Manager
Section titled “Configure libraries and modules to interact with Google Tag Manager”We need to install new libraries to be able to interact with our account.
# Install or upgrade the Google API Python client library, which is used for interacting with Google services (e.g., Gmail, Drive, Sheets)!pip install --upgrade google-api-python-client
# Install or upgrade the oauth2client library, which helps handle OAuth 2.0 authentication for secure access to Google APIs!pip install --upgrade oauth2client
# Install or upgrade the httplib2 library, which provides tools for making HTTP requests (e.g., GET, POST) to communicate with APIs!pip install --upgrade httplib2Python
- First, we installed the Google API Python client library: We’ll use it to interact with GTM via the API.
- Next, we added the
oauth2clientlibrary: It handles authentication and ensures secure access to Google APIs. - Finally, we installed the
httplib2library: This serves as the messenger between the API and our Python app.
The next step is to import some modules:
import json # Import the JSON library for working with JSON data (e.g., parsing, serialization)from google.oauth2 import service_account # Import service account tools for Google API authenticationfrom googleapiclient.discovery import build # Import the build function to create Google API clientsPython
import json: handle and format data usingJSONformat.from google.oauth2 import service_account: securely log in to Google services using ourkey.json.from googleapiclient.discovery import build: connect to GTM and send requests to access accounts and containers.
Authentication using your Key
Section titled “Authentication using your Key”Next, let’s try to authenticate and access one of our accounts using the script below.
# Load the service account key from the JSON fileSERVICE_ACCOUNT_FILE = 'key.json' # Change this to your key file nameSCOPES = ['https://www.googleapis.com/auth/tagmanager.readonly']
# Create credentials using the service accountcredentials = service_account.Credentials.from_service_account_file( SERVICE_ACCOUNT_FILE, scopes=SCOPES)
# Build the GTM serviceservice = build('tagmanager', 'v1', credentials=credentials)
#Define function to fetch accounts from GTM container
def list_gtm_accounts(service): # Retrieve and print GTM accounts accounts = service.accounts().list().execute()
if 'accounts' in accounts: for account in accounts['accounts']: print(f'Account ID: {account["accountId"]}, Name: {account["name"]}') else: print("No accounts found.")
#execute functionlist_gtm_accounts(service)Python
Once I run the script, it will list the available accounts in my GTM container.
Example: use GTM API to list containers
Section titled “Example: use GTM API to list containers”Finally, let’s retrieve a list of our containers for one account. We will use the following code.
def list_containers(service, account_id): """ List all containers for a specific GTM account ID. """
# Call the API to list containers response = service.accounts().containers().list(accountId=account_id).execute()
# Access the 'containers' key to get the list of containers containers = response.get('containers', [])
if not containers: print(f"No containers found for Account ID: {account_id}.") return
print(f"Containers for Account ID {account_id}:") for container in containers: print(f' - Container ID: {container["containerId"]}, Name: {container["name"]}')
# Test script with your account IDaccount_id = '123456789' # Replace with your own GTM IDlist_containers(service, account_id)Python
Replace the ID with the own GTM account ID, and the script will list all available containers in your account.