AgentSkillsCN

gtm-api

执行 Google Tag Manager API 操作——创建、更新、删除并管理标签、触发器、变量和容器。适用于以编程方式操作 GTM、生成 API 调用、验证 GTM 配置、发布容器版本,或自动化标签管理流程时使用。

SKILL.md
--- frontmatter
name: gtm-api
description: Execute Google Tag Manager API operations - create, update, delete, and manage tags, triggers, variables, and containers. Use when working with GTM programmatically, generating API calls, validating GTM configurations, publishing container versions, or automating tag management workflows.

Google Tag Manager API

Execute GTM API operations with validation, error handling, and proper workflow patterns.

Quick Start

1. Understand the Hierarchy

code
Account
└── Container
    ├── Environments (deployment targets)
    ├── Versions (immutable snapshots)
    └── Workspaces (mutable, where changes happen)
        ├── Tags
        ├── Triggers
        └── Variables

Critical rule: All changes happen in workspaces; publishing creates versions.

2. Four Steps for Every Operation

  1. Read algorithminstructions.md
  2. Copy templaterequest-templates.md
  3. Validatevalidation-rules.md
  4. Execute with error handling → workflows.md

Core Execution Workflow

Step 1: Validate Inputs

code
BEFORE any API call:
  1. Validate required fields present
  2. Validate field types (strings, arrays, etc.)
  3. Verify entity references exist (trigger IDs, variable names)
  4. Check OAuth scopes sufficient
  5. Confirm container type supports operation

Step 2: Get or Create Workspace

code
workspaces = GET /accounts/{account_id}/containers/{container_id}/workspaces

IF workspaces is empty:
  workspace = POST /workspaces with {"name": "Default Workspace"}
ELSE:
  workspace = workspaces[0]

Store: workspace_id, workspace_path

Step 3: Execute Operation

Use the appropriate reference file:

Step 4: Handle Response

code
IF status 200/201: Extract IDs, return success
IF status 400: Check JSON syntax, validate fields
IF status 401: Refresh OAuth token
IF status 403: Check scopes OR rate limit (backoff)
IF status 404: Verify resource path/ID
IF status 409: Get fresh fingerprint, retry (max 3)
IF status 429: Exponential backoff (1s → 2s → 4s → 8s → 16s → 32s)
IF status 500: Retry with backoff

Critical Rules

Fingerprints

code
CREATE:  Don't include fingerprint
UPDATE:  MUST include current fingerprint (GET first)
DELETE:  Not needed

IDs vs Paths

code
API endpoints:     Use full path
                   "accounts/123/containers/456/workspaces/10/tags/5"

Entity references: Use ID only
                   firingTriggerId: ["5"]

Boolean Parameters

code
WRONG:  {"type": "boolean", "value": true}
RIGHT:  {"type": "boolean", "value": "true"}  // String!

Rate Limits

code
10,000 requests/day
0.25 QPS (1 request per 4 seconds)
On limit: Exponential backoff

Common Operations

Create a Tag

code
1. GET workspace
2. Verify triggers exist (GET /triggers/{id})
3. Build tag body with:
   - name (required)
   - type (required)
   - firingTriggerId (required, array of IDs)
   - parameter (array of typed params)
4. POST {workspace_path}/tags
5. Return tag_id

Template: request-templates.md → "Tag Templates"

Update a Tag

code
1. GET {tag_path} → extract fingerprint
2. Merge updates with current state
3. Include fingerprint in body
4. PUT {tag_path}
5. On 409: Get fresh fingerprint, retry

Publish Changes

code
1. GET {workspace_path}/status
   - Check for conflicts (resolve first)
   - Check for changes (nothing to publish if empty)
2. POST {workspace_path}:create_version with name/notes
3. POST {version_path}:publish
4. Return version_id

Algorithm: instructions.md → "Instruction: Publish Changes"

List Resources with Pagination

code
all_items = []
page_token = None

LOOP:
  response = GET {path}/{resource_type}?pageToken={page_token}
  all_items.extend(response.items)
  page_token = response.nextPageToken
  IF page_token is None: BREAK

RETURN all_items

OAuth Scopes

ActionScope
Read anythingtagmanager.readonly
Create/edit tagstagmanager.edit.containers
Publishtagmanager.publish
Delete containerstagmanager.delete.containers
Manage userstagmanager.manage.users

Scopes are additive. Publishing requires: readonly + edit.containers + publish


Path Patterns

ResourcePath
Containeraccounts/{id}/containers/{id}
Workspace.../containers/{id}/workspaces/{id}
Tag.../workspaces/{id}/tags/{id}
Trigger.../workspaces/{id}/triggers/{id}
Variable.../workspaces/{id}/variables/{id}
Version.../containers/{id}/versions/{id}

Special paths:

  • /versions/live - Currently published version
  • /workspaces/{id}:create_version - Create version
  • /versions/{id}:publish - Publish version

Tag Parameter Structure

Parameters use typed objects:

json
{
  "parameter": [
    {"type": "template", "key": "measurementId", "value": "G-XXXXX"},
    {"type": "boolean", "key": "sendPageView", "value": "true"},
    {"type": "list", "key": "eventParameters", "list": [...]}
  ]
}

Types: template (string), boolean (string "true"/"false"), integer, list, map


Reference Documentation

Execution (When Doing)

FileUse When
instructions.mdStep-by-step algorithms for operations
request-templates.mdCopy-paste JSON templates
validation-rules.mdValidating before sending
workflows.mdComplex flows, decision trees

Understanding (When Learning)

FileUse When
context.mdMental model, architecture
schemas.mdComplete entity structures
api-reference.mdAll endpoints, methods
examples.mdReal-world request/response pairs
quick-reference.mdLookup tables, type codes

Common Mistakes to Avoid

Including auto-generated fields in CREATE

code
WRONG: {"tagId": "5", "path": "...", "name": "My Tag"}
RIGHT: {"name": "My Tag", "type": "html", "firingTriggerId": ["5"]}

Missing fingerprint in UPDATE

code
WRONG: PUT /tags/5 with {"name": "Updated"}
RIGHT: GET /tags/5 first, then PUT with current fingerprint

Using paths in entity references

code
WRONG: {"firingTriggerId": ["accounts/123/.../triggers/5"]}
RIGHT: {"firingTriggerId": ["5"]}

Execution Template

When given a GTM API task:

code
1. IDENTIFY operation type (create/update/delete/list/publish)
2. FIND algorithm in instructions.md
3. GET template from request-templates.md (if creating/updating)
4. VALIDATE using validation-rules.md
5. EXECUTE with proper auth headers
6. HANDLE errors using workflow from workflows.md
7. RETURN result with IDs or error with fix suggestion