Why You Sometimes See an Empty User ID in GA4 (and How to Work Around It)

Github Documentation

If you’ve ever wanted to automatically pull your Google Tag Manager (GTM) container data into Google Sheets — or just run GTM API requests inside Apps Script — this guide is for you.

In this blog post, I’ll walk you through how I connected the GTM API to Google Apps Script to read container data, using nothing but code and some configuration in Google Cloud Platform.

🛠️ Why Use Apps Script for GTM?

  • No need for third-party tools

  • Easy to run and manage from Google Sheets

  • Perfect for automation, reporting, or building internal GTM documentation tools


 

✅ Step 1: Create a Google Apps Script Project

  1. Open script.google.com

  2. Create a new project

  3. Name your project (e.g., “GTM API Connector”)


✅ Step 2: Link Your Project to Google Cloud

  1. Go to Project Settings

  2. Copy your Project Number

  3. In the Google Cloud Console, create a new project or use an existing one

  4. Enable the Tag Manager API v2


✅ Step 3: Set Up Your appsscript.json File

In Apps Script, enable the manifest file:

  • Go to ⚙️ Settings → Show appsscript.json

Then paste:

json
{
"timeZone": "Europe/Zurich",
"oauthScopes": [
"https://www.googleapis.com/auth/script.external_request",
"https://www.googleapis.com/auth/tagmanager.readonly"
]
}

This gives your script permission to connect to external APIs and read GTM containers.


✅ Step 4: Write the Script to Call GTM API

Here’s a simple function that gets your GTM containers:

javascript
 

function getGTMContainers() {
const accessToken = ScriptApp.getOAuthToken();
const accountId = 'YOUR_GTM_ACCOUNT_ID';

const url = `https://www.googleapis.com/tagmanager/v2/accounts/${accountId}/containers`;

const response = UrlFetchApp.fetch(url, {
method: ‘get’,
headers: {
Authorization: ‘Bearer ‘ + accessToken
},
muteHttpExceptions: true
});

 

Logger.log(response.getContentText());
}

Make sure to replace 'YOUR_GTM_ACCOUNT_ID' with your actual GTM account ID.


✅ Step 5: Run & Authorize

  • Click the ▶️ Run button

  • Apps Script will ask for authorization

  • Grant access

  • Open View > Logs to see the API response

You should see JSON data containing your GTM containers.


🚀 What’s Next?

Now that your script is connected to GTM:

  • You can extend it to log tags, triggers, and variables

  • Or push the data into Google Sheets for documentation or audits


💬 Final Thoughts

Connecting GTM API to Apps Script opens up a ton of automation opportunities for analysts and developers. You don’t need complex frameworks or tools — just a bit of Apps Script and a GCP project.

If you’d like me to share a follow-up on how I pushed the API data into Google Sheets, let me know in the comments or reach out.

About Me

Hisham Ghanayem

Lets talk data 

Gallery