Python for GTM Engineers: The Scripts That Cover 80% of the Job

Python for GTM engineers is three scripts: clean a CSV, call an API with retries and receive a signed webhook. Here's the copy-ready code for each, how to set up and schedule them, and the time math.

Pixel-art server rack beside a CRM board, small Python scripts moving clean records between sales tools.

Python for GTM engineers comes down to three scripts: one that cleans a CSV, one that calls an API with retries, and one that receives a signed webhook. Those three cover most data jobs that no-code tools handle badly. Learn files, loops, dictionaries and the requests library, and you can build all three in a week.

Most GTM engineers start in visual builders. That's the right place to start. Then a list import hits 40,000 rows, an API starts returning 429 errors, or a webhook needs a signature check. The visual builder turns into a maze of branches.

That's when a short script wins. This guide gives you the setup, the three scripts with code you can copy, how to schedule them, a worked example with the time math, and the mistakes that bite first.

Key takeaways

  • Learn three scripts, not a language. CSV cleanup, API calls with retries and a webhook receiver cover most GTM jobs.
  • Always set a timeout. The requests library has no timeout by default, so one slow API can hang a whole job.
  • Retry reads, not creates. Retrying a create call can make duplicates, so let the safe calls retry first.
  • Check every webhook signature. Use a constant-time compare, so nobody can fake events into your CRM.
  • Log every run. A script with no log and no owner fails in silence.

Why should a GTM engineer learn Python?

A GTM engineer builds the systems that move leads, accounts and signals between tools. Most of that work fits in no-code tools. Some of it doesn't.

Here's where I draw the line.

Job No-code is fine Python wins
New form fill to CRM and Slack Yes Only if the logic gets heavy
Clean a 40,000-row event list Slow and costly per row Seconds, with a rejects file
Pull every record from a paged API Painful loops A short while loop
Handle rate limits and retries Basic settings Full control of waits and limits
Check a webhook signature Often missing A few lines with the hmac module
Logic with many rules A wall of branches Plain if and else you can read

No-code tools are great for flows a teammate needs to see and edit. The n8n vs Zapier vs Make comparison covers which one fits. Python is for the jobs that loop, retry or get complex. Many good setups use both: the visual tool catches the event, then calls a script for the hard part.

Python also sits well next to SQL. SQL asks questions of a warehouse. Python moves and fixes data between tools. If you already know the SQL queries marketers use, Python is the natural next step. The GTM engineering skills guide puts both in order.

What Python do you actually need?

Less than you think. Most GTM scripts use the same handful of ideas.

Concept What it does in GTM work Example
Variables and strings Hold and fix values like emails and names email.strip().lower()
Lists Hold many records rows = []
Dictionaries One record with named fields {"email": "a@b.co"}
Loops Do the same thing to every row for row in rows:
If and else Apply your rules if domain in FREE_DOMAINS:
Functions Name a step so you can reuse it def clean_row(row):
Files Read and write CSVs and logs open("clean.csv", "w")
The requests library Call APIs session.get(url, timeout=30)
try and except Catch an error without crashing the run except requests.RequestException:

Skip classes, web frameworks and data science libraries for now. Learn them when a real job needs them, not before.

How do you set up Python for GTM work?

Use one folder per project and a virtual environment in it. A virtual environment is a private copy of Python's add-ons for that folder, so one project can't break another.

mkdir gtm-scripts && cd gtm-scripts
python3 -m venv .venv
source .venv/bin/activate
pip install requests
mkdir data logs

Keep secrets out of the code. Put each API key in an environment variable and read it at run time.

export CRM_API_KEY="paste-your-key-here"
export WEBHOOK_SECRET="paste-the-signing-secret-here"

Then lay out the folder so anyone can follow it:

gtm-scripts/
  .venv/              # never commit this
  data/               # input and output files, also not committed
  logs/               # one log file per script
  clean_csv.py
  enrich.py
  webhook_receiver.py
  .gitignore          # lists .venv, data, logs and any .env file

If you'd rather have an agent write the first draft, a coding agent in the terminal is a fine teacher. The Claude Code for marketers guide shows how to work with one safely. Read every line it writes before you run it on real data.

How do you clean a CSV with Python?

List cleanup is the most common GTM script. Event lists, webinar exports and old CRM dumps all come in messy. The goal is a clean file to import and a rejects file a person can review.

Python's built-in csv module docs give two rules worth knowing. First, open CSV files with newline="". Without it, line breaks inside quoted fields get read wrong. Second, set the encoding when a file isn't plain UTF-8. Many exports from spreadsheets start with a hidden marker. The utf-8-sig encoding strips it, so your first column name doesn't come out garbled.

Here's a script that trims and lowercases emails, fixes name case, pulls the domain, flags free email domains and removes duplicates.

import csv
import re

FREE_DOMAINS = {"gmail.com", "yahoo.com", "hotmail.com", "outlook.com", "icloud.com"}
EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[a-z]{2,}$")
FIELDS = ["email", "first_name", "company", "domain", "free_email"]


def clean_row(row):
    email = (row.get("Email") or "").strip().lower()
    first = (row.get("First Name") or "").strip()
    if first.isupper() or first.islower():
        first = first.title()  # only fix names typed in all caps or all lowercase
    domain = email.split("@")[-1] if "@" in email else ""
    return {
        "email": email,
        "first_name": first,
        "company": (row.get("Company") or "").strip(),
        "domain": domain,
        "free_email": domain in FREE_DOMAINS,
    }


seen = set()
counts = {"kept": 0, "bad email": 0, "duplicate": 0}

with open("data/raw.csv", newline="", encoding="utf-8-sig") as src, \
     open("data/clean.csv", "w", newline="", encoding="utf-8") as ok_file, \
     open("data/rejects.csv", "w", newline="", encoding="utf-8") as bad_file:
    good = csv.DictWriter(ok_file, fieldnames=FIELDS)
    rejects = csv.DictWriter(bad_file, fieldnames=FIELDS + ["reason"])
    good.writeheader()
    rejects.writeheader()

    for row in csv.DictReader(src):
        r = clean_row(row)
        if not EMAIL_RE.match(r["email"]):
            rejects.writerow({**r, "reason": "bad email"})
            counts["bad email"] += 1
        elif r["email"] in seen:
            rejects.writerow({**r, "reason": "duplicate"})
            counts["duplicate"] += 1
        else:
            seen.add(r["email"])
            good.writerow(r)
            counts["kept"] += 1

print(counts)

A few choices here matter more than the code.

  • Nothing gets thrown away. Every dropped row lands in the rejects file with a reason. A person can scan it in two minutes.
  • The name fix is careful. Python's title() would turn "McDonald" into "Mcdonald". So the script only fixes names typed in all caps or all lowercase.
  • Deduplication runs on the clean email. "Ana@Acme.com " and "ana@acme.com" are the same person once trimmed and lowercased.
  • It prints counts. If 30% of rows get rejected, you look before you import.

Match your output column names to your CRM's fields before the import. The CRM field naming checker helps keep them consistent.

How do you call an API with retries?

The second script loops over records and calls an API for each one. This is where most homemade scripts break. The API basics guide covers the concepts. Here's the code.

Two facts from the requests advanced usage docs shape everything. First, requests don't time out unless you set a timeout, so a slow server can hang your script for minutes or more. Second, requests doesn't retry failed calls by default. You add retries with the Retry class from urllib3, mounted on a Session. A Session also reuses the same connection for calls to one host, which makes big loops faster.

import csv
import logging
import os
import time

import requests
from requests.adapters import HTTPAdapter
from urllib3.util import Retry

logging.basicConfig(filename="logs/enrich.log", level=logging.INFO,
                    format="%(asctime)s %(levelname)s %(message)s")

API_KEY = os.environ["CRM_API_KEY"]   # fails fast if the key is missing
BASE_URL = "https://api.example.com/v1/companies"


def make_session():
    retry = Retry(
        total=5,
        backoff_factor=1,
        status_forcelist=[429, 500, 502, 503, 504],
        allowed_methods={"GET", "PUT"},   # no POST: a retried create can duplicate
    )
    session = requests.Session()
    session.mount("https://", HTTPAdapter(max_retries=retry))
    session.headers.update({"Authorization": f"Bearer {API_KEY}"})
    return session


def get_company(session, domain):
    resp = session.get(BASE_URL, params={"domain": domain}, timeout=30)
    resp.raise_for_status()   # turns 4xx and 5xx answers into errors
    return resp.json()


session = make_session()
ok, failed = 0, 0

with open("data/clean.csv", newline="", encoding="utf-8") as src:
    for row in csv.DictReader(src):
        if row["free_email"] == "True" or not row["domain"]:
            continue
        try:
            company = get_company(session, row["domain"])
            # write the result wherever it belongs: a file, a database or the CRM
            ok += 1
        except requests.RequestException as err:
            logging.warning("failed %s: %s", row["domain"], err)
            failed += 1
        time.sleep(0.2)   # stay under about five calls a second

logging.info("done: %s ok, %s failed", ok, failed)

Here's what each setting does.

Setting What it does Why it matters
timeout=30 Gives up after 30 seconds of silence One stuck call can't freeze the whole run
total=5 Tries a failed call up to five more times Brief outages fix themselves
backoff_factor=1 Waits longer before each new try Gives a busy server room to recover
status_forcelist Retries on 429 and server errors only A 404 or 401 won't fix itself, so it fails fast
allowed_methods Retries reads and updates, not creates A retried create can make a duplicate record
time.sleep(0.2) Paces the loop Keeps you under the vendor's rate limit

The urllib3 Retry reference fills in the rest. The wait doubles with each retry, capped at 120 seconds by default. It obeys the server's Retry-After header by default on 413, 429 and 503 answers. And POST isn't in its default list of methods to retry, which is the safe choice.

A 429 is an API rate limit answer: the vendor is asking you to slow down. Good retry logic waits and tries again. Bad retry logic hammers the server and gets your key blocked.

How do you pull every record from a paged API?

Most APIs won't hand you 40,000 records in one answer. They send a page, often 100 records, plus a marker for the next page. That marker is usually called a cursor. You keep asking until the answer comes back with no cursor.

def get_all_contacts(session, url):
    records, cursor = [], None
    while True:
        params = {"limit": 100}
        if cursor:
            params["after"] = cursor
        resp = session.get(url, params=params, timeout=30)
        resp.raise_for_status()
        data = resp.json()
        records.extend(data["results"])
        cursor = data.get("next_cursor")   # field names differ by vendor
        if not cursor:
            return records

The field names change from vendor to vendor, so check the docs. The shape stays the same. Two habits help. Save each page to a file as you go, so a crash on page 300 doesn't cost you the first 299. And log the page count, so you can tell a full pull from a cut-off one.

How do you receive a webhook in Python?

The third script listens for events. A webhook is a message one tool sends to a URL you own when something happens, like a form fill or a signed contract. The webhooks for marketers guide explains the idea. Here's a small receiver.

It does three jobs. It checks the signature, so only the real sender gets in. It skips events it has already seen, since senders retry. And it answers fast, then leaves the heavy work for later.

import hashlib
import hmac
import json
import os
from http.server import BaseHTTPRequestHandler, HTTPServer

SECRET = os.environ["WEBHOOK_SECRET"].encode()
seen_ids = set()   # use a database table in production, so restarts keep it


class Receiver(BaseHTTPRequestHandler):
    def do_POST(self):
        length = int(self.headers.get("Content-Length", 0))
        body = self.rfile.read(length)

        sent = self.headers.get("X-Signature", "")
        expected = hmac.new(SECRET, body, digestmod=hashlib.sha256).hexdigest()
        if not hmac.compare_digest(expected, sent):
            self.send_response(401)
            self.end_headers()
            return

        event = json.loads(body)
        event_id = event.get("id")
        if event_id not in seen_ids:
            seen_ids.add(event_id)
            with open("data/events.jsonl", "a", encoding="utf-8") as f:
                f.write(json.dumps(event) + "\n")   # a worker picks these up later

        self.send_response(200)
        self.end_headers()


HTTPServer(("0.0.0.0", 8000), Receiver).serve_forever()

The signature check is the part people skip. The sender signs each message with a shared secret. You sign the body the same way and compare.

Python's hmac module docs say to use compare_digest() for that check, not ==. A plain == stops at the first wrong character. That tiny time gap can leak how much of a fake signature was right. Over many tries, an attacker can use it to guess a valid one. compare_digest() takes the same time either way.

Each vendor signs a little differently. The header name, the hash type and whether a timestamp is part of the signed text all vary. Read the sender's docs and match them exactly.

This receiver is a learning tool. For production, run the same logic in a proper web framework or a serverless function behind HTTPS, with the seen IDs in a database.

How do you run scripts on a schedule?

A script you have to remember to run is a chore. A scheduled script is a system. On a Mac or Linux server, a cron job is the simplest way to run one on a timer.

Flow from source to clean, enrich, write and log, with the log step marked as the one that keeps a script trusted.Flow from source to clean, enrich, write and log, with the log step marked as the one that keeps a script trusted.
Every script here follows the same path. The log at the end is what turns a one-off script into a system.
0 6 * * 1-5 cd /home/you/gtm-scripts && .venv/bin/python enrich.py >> logs/enrich.log 2>&1

Every scheduled script needs four things:

  1. A log. Write when it ran, how many rows it touched and every failure.
  2. An alert. If the failed count passes a set share, post to a Slack channel someone reads.
  3. An owner. One named person who fixes it when it breaks.
  4. A dry-run mode. A flag that runs every step but writes nothing, for testing changes.

When a script outgrows your laptop, move it to a small cloud server, a serverless function or the code step in your workflow tool. The code stays the same. Only the trigger changes.

How do you test a script before it touches real data?

Give every script a dry-run mode. It runs every step, prints what it would change and writes nothing. Python's built-in argparse module makes this a few lines.

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--dry-run", action="store_true", help="show changes, write nothing")
args = parser.parse_args()

for change in planned_changes:
    if args.dry_run:
        print("would update", change["id"], change["fields"])
    else:
        update_record(session, change)

Run the dry run first, every time you change the code. Read the output. Then run it for real on a small batch. It is the cheapest insurance a script can have.

Worked example: a weekly list cleanup, by hand and by script

Here's the time math with assumed numbers. Plug in yours.

Bar chart of yearly hours for a weekly list cleanup: 156 by hand, 17 with a script including build time.Bar chart of yearly hours for a weekly list cleanup: 156 by hand, 17 with a script including build time.
Worked example with assumed times: 3 hours a week by hand against a 4-hour build and 15 minutes of weekly review. Worked example from this guide.

Say your team gets 2,000 rows a week from events, webinars and partner lists. Today, someone cleans them in a spreadsheet before import. They fix emails, remove duplicates, flag free email domains and look up missing company domains. That takes 3 hours a week.

Now say you build the CSV script and the API script above. Building and testing them takes 4 hours, once. After that, the run takes seconds. A person spends 15 minutes a week scanning the rejects file and the log.

Over a 52-week year, the hand process costs 3 × 52 = 156 hours. The script costs the 4 hours to build plus 0.25 × 52 = 13 hours of review, so 17 hours in total.

There's a hidden gain too. Hand cleanup drifts. One week someone dedupes on email, the next week on name. The script applies the same rules every time, and the rejects file shows exactly what it dropped and why.

What are the common mistakes with Python for GTM?

No timeout. The script hangs on one slow call and nobody notices for a day. Set a timeout on every request.

Retrying creates. A lost answer plus a blind retry equals a duplicate record. Retry reads and updates first. Look up before you create.

Keys in the code. A key pasted into a script ends up in a repo, then in a screenshot. Use environment variables.

Silent failures. A bare except: pass hides every error. Log what failed and why.

Testing on the full list first. Run on 20 rows. Check every output row. Then run on 200. Then on everything.

Ignoring encoding. A file with accented names comes out garbled because the encoding was wrong. Set it when you open the file.

One-off scripts nobody owns. A script that runs the pipeline is a product. Give it a README, a log and an owner. If your CRM is already full of the mess these scripts prevent, the CRM cleanup use case shows how we fix it at the source.

What should you do this week?

If you'd rather have the scripts built, scheduled and watched for you, our GTM engineering service does that work, from the first cleanup script to a full pipeline.

My take: learn three scripts, not a language

You don't need to become a software engineer. You need to clean a file, call an API without breaking it and receive an event safely. That's three scripts, and they cover most of what no-code tools do badly.

Learn them on your own messy data. Add the timeout, the retries, the signature check and the log from day one. Those four habits separate a script that saves you hours from one that costs you a weekend.

Then stop. Reach for more Python only when a real job asks for it. In my experience, the best GTM builders write less code, not more. They just put the right code in the right places.

FAQ

Do GTM engineers need to know Python?

Not on day one, but it pays off fast. No-code tools cover most simple flows. Python takes over when you need to clean big files, loop through an API with care, check webhook signatures or run logic that would take twenty steps in a visual builder. A few hundred lines of Python cover most of the job.

How long does it take to learn enough Python for GTM work?

If you already think in fields, filters and steps, a few focused weeks is enough for the scripts in this guide. Learn files, loops, dictionaries, functions and the requests library first. Skip classes, web frameworks and data science tools until a real job needs them. Build on your own messy CSVs, not toy data.

Should I use Python or a no-code tool like Zapier or n8n?

Use no-code for simple trigger and action flows that a teammate may need to edit. Use Python when the job loops over thousands of rows, needs careful retries, or has logic that would sprawl across many steps. Many teams use both: a no-code tool catches the event, then calls a small Python script to do the hard part.

Is it safe to put API keys in a Python script?

No. Keep keys out of the code. Store them in environment variables or a secrets manager, and read them at run time with os.environ. Add any local .env file to .gitignore so it never lands in a repo. Give each script its own key with the fewest rights it needs, so a leak is easy to contain.

Where should GTM Python scripts run?

Start on your own machine with a cron schedule. When a script matters to the business, move it to a small cloud server, a serverless function or your workflow tool's code step. Wherever it runs, it needs logs, an alert on failure and a named owner. A script nobody watches will fail quietly.

Can AI write these Python scripts for me?

Yes, and it's a good way to learn. Coding agents can write a first draft of every script here in minutes. You still need to read the code, run it on a sample file and check the output row by row. Know enough Python to spot when a script deletes, overwrites or sends something it shouldn't.

More like this

Startup? Let's talk.

20 minute fit call. You'll leave knowing the first thing we'd fix and roughly what it costs. If we're not the right fit, we'll tell you who is.