Python Rank Tracking API Client: requests, Retries and pandas
TrackSERPs does not publish a Python package. You call the REST API with requests or httpx, and about 100 lines of client code cover what an SDK would: a Bearer header, request timeouts, cursor pagination, retries that wait for Retry-After on 429, idempotency keys on POST, run polling, and webhook signature checks. This page gives that client, plus a webhook receiver and a pandas export.
Key facts
- requests has no default timeout, so every call needs an explicit timeout or a stalled connection can hang a script.Source: docs.python-requests.org
- urllib3's Retry does not retry POST by default and honours Retry-After only for 413, 429 and 503.Source: urllib3.readthedocs.io
- httpx's transport retries option only covers connection errors and connect timeouts, not 429 or 5xx responses.Source: python-httpx.org
- Python's hmac.compare_digest is the documented way to compare a computed digest with a value sent by a third party.Source: docs.python.org
- pandas.json_normalize flattens nested JSON objects into columns, which suits ranking rows that contain an ai_overview object.Source: pandas.pydata.org
There is no Python SDK, and you do not need one
TrackSERPs is a plain JSON REST API at https://api.trackserps.com/v1. The only packaged client is the TypeScript one, covered on the Node SDK page. In Python you use requests or httpx and handle the chores every client has: the Bearer header, a timeout, next_cursor, the right retries, and never double-submitting a write.
Our position: copy one short client module, understand each of its six behaviours, and keep it in your repo. A generated client adds a dependency and hides the rules that matter, such as which 429 responses are worth retrying. The webhook check below follows the same signing rule as the TypeScript SDK's verifyWebhook.
This page is the integration reference: a reusable client, a webhook receiver, a pandas export, a scheduled job and a concurrency example. For a longer tutorial that builds a ranking report step by step, read the Python rank tracking guide. For the endpoints, the TrackSERPs API overview and the API reference are the source of truth.
Setup: keys, scopes and the safe test key
Create a key in the app under the API keys page. Keys carry scopes: rankings:read is always present and covers every read endpoint, while keywords:write, runs:write, shares:write and webhooks:write unlock the matching writes and need a plan with write access. A key can also be limited to specific projects and IP addresses; a project outside the list returns 404.
Start with a ts_test_ key. It reads a synthetic demo project, never runs a real check and never spends credits. Write calls are validated and return realistic responses, but nothing is saved. Every response carries X-TrackSERPs-Test-Mode: true, so your code can assert it is not touching live data.
python -m venv .venv && source .venv/bin/activate
pip install requests pandas
export TRACKSERPS_API_KEY="ts_test_replace_me"
A key in a query string is rejected with 400 key_in_query; it belongs only in the Authorization: Bearer <key> header, which the client below sets once on its session.
The client: six behaviours in about 100 lines
Save this as trackserps_client.py. It reuses connections through a requests.Session and raises a typed exception carrying the API's code, request_id and fields. Branch on code, never on the message.
import os
import random
import time
import uuid
from typing import Any, Iterator, Optional
import requests
BASE_URL = "https://api.trackserps.com/v1"
TERMINAL_RUN_STATUSES = {"completed", "partial", "failed", "paused_no_credits"}
class TrackSerpsError(Exception):
def __init__(self, status, code, message, request_id=None, fields=None, retry_after=None):
super().__init__(f"{status} {code}: {message} (request_id={request_id})")
self.status = status
self.code = code
self.message = message
self.request_id = request_id
self.fields = fields or {}
self.retry_after = retry_after
class TrackSerps:
def __init__(self, api_key=None, base_url=BASE_URL, timeout=30, max_retries=3, max_wait=60):
key = api_key or os.environ["TRACKSERPS_API_KEY"]
self.base_url = base_url.rstrip("/")
self.timeout = timeout
self.max_retries = max_retries
self.max_wait = max_wait
self.session = requests.Session()
self.session.headers.update(
{"Authorization": f"Bearer {key}", "Accept": "application/json"}
)
def request(self, method: str, path: str, *, params=None, json=None, idempotency_key=None) -> Any:
headers = {}
if method == "POST":
# One key per logical request, reused on every retry of it.
headers["Idempotency-Key"] = idempotency_key or str(uuid.uuid4())
params = {k: v for k, v in (params or {}).items() if v is not None}
attempt = 0
while True:
try:
resp = self.session.request(
method, f"{self.base_url}{path}", params=params,
json=json, headers=headers, timeout=self.timeout,
)
except (requests.ConnectionError, requests.Timeout):
if attempt >= self.max_retries:
raise
time.sleep(self._backoff(attempt))
attempt += 1
continue
if resp.status_code == 204:
return None
if resp.ok:
return resp.json()
try:
err = resp.json().get("error", {})
except ValueError:
err = {}
code = err.get("code", "api_error")
retry_after = self._retry_after(resp)
# Retry only plain rate limiting and 5xx. run_too_soon and
# quota_exceeded are also 429, but waiting a few seconds will not help.
retryable = (resp.status_code == 429 and code == "rate_limited") or resp.status_code >= 500
if retryable and attempt < self.max_retries:
wait = retry_after if retry_after is not None else self._backoff(attempt)
if wait <= self.max_wait:
time.sleep(wait)
attempt += 1
continue
raise TrackSerpsError(
resp.status_code, code, err.get("message", resp.reason),
request_id=err.get("request_id") or resp.headers.get("X-Request-Id"),
fields=err.get("fields"), retry_after=retry_after,
)
@staticmethod
def _retry_after(resp) -> Optional[float]:
value = resp.headers.get("Retry-After")
try:
return float(value) if value is not None else None
except ValueError:
return None
@staticmethod
def _backoff(attempt: int) -> float:
return 0.5 * (2 ** attempt) + random.uniform(0, 0.2)
def paginate(self, path: str, items_key: str, params=None) -> Iterator[dict]:
params = dict(params or {})
while True:
page = self.request("GET", path, params=params)
yield from page[items_key]
if not page.get("next_cursor"):
return
params["cursor"] = page["next_cursor"]
# Thin wrappers over endpoints in openapi.yaml
def projects(self, **params) -> Iterator[dict]:
return self.paginate("/projects", "projects", params)
def latest_rankings(self, project_id: str, **params) -> Iterator[dict]:
return self.paginate(f"/projects/{project_id}/rankings/latest", "rankings", params)
def trigger_run(self, project_id: str, *, keyword_ids=None, fresh=None, dry_run=False) -> dict:
body = {k: v for k, v in {"keyword_ids": keyword_ids, "fresh": fresh}.items() if v is not None}
return self.request(
"POST", f"/projects/{project_id}/runs",
params={"dry_run": "true"} if dry_run else None, json=body or None,
)
def get_run(self, project_id: str, run_id: str) -> dict:
return self.request("GET", f"/projects/{project_id}/runs/{run_id}")
def wait_for_run(self, project_id: str, run_id: str, interval=60, timeout=1800) -> dict:
deadline = time.monotonic() + timeout
while True:
run = self.get_run(project_id, run_id)
if run["status"] in TERMINAL_RUN_STATUSES:
return run
if time.monotonic() + interval > deadline:
raise TimeoutError(f"run {run_id} still {run['status']} after {timeout}s")
time.sleep(interval)
What each behaviour is for
- Timeout.
requestshas no default timeout, so a stalled connection can hang a nightly job forever. The client passestimeout=30every time. - Retry only what is safe. Network errors,
5xx, and429with coderate_limitedare retried. Everything else raises immediately. - Honour
Retry-After. The client sleeps that long, up tomax_wait(60 seconds), and raises beyond that so the caller decides. - Idempotency keys. Every
POSTgets anIdempotency-Key, generated once per logical call and reused on each retry. If a timeout hid a successful response, the retry returns the original result instead of holding credits twice. Reusing a key with a different payload returns409 idempotency_mismatch. - Pagination. List endpoints return
next_cursor, which isnullon the last page. Thelimitparameter defaults to 50 and goes up to 500.
You could mount an HTTPAdapter with a urllib3 Retry instead. Two documented details catch people out: POST is not in the default allowed_methods, and Retry-After is honoured only for 413, 429 and 503. Retry also cannot tell rate_limited from run_too_soon, which is why the hand-written loop earns its lines. The httpx transport retries option covers only connection failures.
Which 429 is which
Four different situations return status 429. Only the first is worth an automatic retry.
| Code | Cause | Headers sent | What to do |
|---|---|---|---|
rate_limited | Per-key requests-per-minute limit | Retry-After, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset | Sleep Retry-After seconds, retry |
quota_exceeded | Monthly API call allowance used up | Retry-After | Stop; wait for the billing month or change plan |
run_too_soon | Second manual run on a project within 10 minutes | Retry-After | Do not retry; use the last run or wait |
rate_limited (IP lockout) | 20 failed authentications within 5 minutes from one IP | Retry-After (300 seconds), no X-RateLimit-* | Fix the key first; the client gives up because 300 is above max_wait |
Your per-minute limit is on the account usage endpoint (GET /account/usage, field api.rate_limit_per_minute), and it depends on the plan. The bulk history endpoint counts as five requests toward both the per-minute limit and the monthly quota, so budget accordingly. Read the rate limits and errors pages for the full list of codes.
List projects and read latest rankings with pagination
Reads spend no credits. The client's projects() and latest_rankings() generators follow next_cursor for you.
from trackserps_client import TrackSerps
client = TrackSerps()
for project in client.projects():
print(project["id"], project["name"], project["domain"], project["keywords_count"])
project_id = next(client.projects())["id"]
for r in client.latest_rankings(project_id, device="desktop", limit=500):
rank = r["rank"] if r["rank"] is not None else "not in top 100"
print(f"{r['phrase']}: {rank} (7d change: {r['change_7d']})")
Each ranking item has keyword_id, phrase, device, date, rank, rank_absolute, ranking_url, serp_features, ai_overview, change_7d, change_30d and checked. Four details to code for:
rankisnullwhen the domain was checked and is not in the top 100. It is never0. A date ofnullwithchecked: falsemeans the keyword has never been checked yet; skip it rather than treating it as unranked.rankandrank_absolutediffer.rankcounts organic positions only;rank_absolutecounts ads and SERP features above you too. Report the one you mean.change_7dis positive when you improved. A drop is a negative number, which is the opposite of what some tools use. It isnullwhen the keyword is unranked at either end of the comparison (ranked at only one end), so guard for it before doing arithmetic.- Filters.
device(desktopormobile),tag, andinclude=competitorsnarrow or expand the response. Unknown query parameters are ignored, but known ones are strictly validated and a bad value returns422 validation_errorwith afieldsobject.
Keyword history, SERP snapshots and share of voice follow the same pattern: call client.request("GET", path) with the path from the spec, such as /projects/{project_id}/rankings/history with start and end dates in YYYY-MM-DD.
Trigger a run and wait for it
Projects check on their own schedule, so most scripts only read. Trigger a run when you add keywords, need a targeted refresh, or want data newer than today's shared cache.
client = TrackSerps()
project_id = "cmwc0f1yp0005rqk7w1plnab1"
estimate = client.trigger_run(project_id, dry_run=True)
if not estimate["allowed"]:
raise SystemExit(f"cannot run: {estimate['reason']}")
print(f"would hold {estimate['would_hold']} credits, balance after {estimate['balance_after']}")
run = client.trigger_run(project_id, keyword_ids=["cmwc0f2ab0007rqk7x9kd3m2p", "cmwc0f2cd0009rqk7y2me4n3q"], fresh=True)
print("queued", run["run_id"], "holding", run["credits_held"], "credits")
result = client.wait_for_run(project_id, run["run_id"], interval=60, timeout=1800)
print(result["status"], result["keywords_checked"], result["credits_charged"])
What to know about runs:
- A dry run is free.
?dry_run=truereturnswould_hold,balance_after,allowedandreasonwithout starting anything. - Timing. Checks normally take 10 to 20 minutes, even for a single keyword. If the same phrase, location, language and device was already fetched the same UTC day, the check completes immediately and still costs one credit per phrase per device.
fresh=Trueskips that cache and always takes the full wait. - Statuses. A run moves through
queuedandrunning, and ends ascompleted,partial,failedorpaused_no_credits. The client treats all four as final. Forpartial, checkkeywords_checkedand decide whether to re-run the rest. - Limits. One manual run per project every 10 minutes (
429 run_too_soonwithRetry-After), at most 10 run requests per key per hour, and402 insufficient_creditswhen the balance cannot cover the hold. Pass at most 500keyword_ids. - Targeted runs. They update rankings for their own keywords only and are left out of
runs/latestandlast_run_at. - Poll gently. Once a minute is plenty; tighter polling only spends request quota.
Once a run is completed, read latest_rankings for the keywords you targeted.
Receive a webhook instead of polling
For anything unattended, let TrackSERPs call you. Register an endpoint with the client (this needs a key with webhooks:write). The signing secret is returned once, so store it immediately.
hook = client.request("POST", "/webhooks", json={
"url": "https://hooks.example.com/trackserps",
"events": ["run.completed", "rankings.updated", "lookup.completed"],
"description": "Nightly rank pipeline",
})
print(hook["webhook"]["id"], hook["secret"]) # whsec_..., shown only once
The URL must be HTTPS and must resolve to a public address; private, loopback and link-local hosts are refused, and redirects are not followed. The other events you can subscribe to are run.failed, credits.low, credits.exhausted and alert.triggered. Here is a receiver using only the standard library, with signature verification:
import hashlib
import hmac
import json
import os
import time
from http.server import BaseHTTPRequestHandler, HTTPServer
SECRETS = [s for s in (
os.environ.get("TRACKSERPS_WEBHOOK_SECRET"),
os.environ.get("TRACKSERPS_WEBHOOK_PREVIOUS_SECRET"), # only during a rotation
) if s]
SEEN_EVENT_IDS = set() # use Redis or a database table in production
def verify_webhook(raw_body: bytes, header: str, secrets, tolerance: int = 300) -> bool:
timestamp, signatures = None, []
for part in header.split(","):
key, _, value = part.strip().partition("=")
if key == "t" and value.isdigit():
timestamp = value
elif key == "v1":
signatures.append(value.lower())
if timestamp is None or not signatures:
return False
if abs(time.time() - int(timestamp)) > tolerance:
return False
signed_payload = timestamp.encode() + b"." + raw_body
for secret in secrets:
expected = hmac.new(secret.encode(), signed_payload, hashlib.sha256).hexdigest()
if any(hmac.compare_digest(expected, sig) for sig in signatures):
return True
return False
class Handler(BaseHTTPRequestHandler):
def do_POST(self):
raw = self.rfile.read(int(self.headers.get("Content-Length", 0)))
header = self.headers.get("TrackSERPs-Signature", "")
if not verify_webhook(raw, header, SECRETS):
self.send_response(400)
self.end_headers()
return
event = json.loads(raw)
if event["id"] not in SEEN_EVENT_IDS: # event ids are stable across retries
SEEN_EVENT_IDS.add(event["id"])
handle(event)
self.send_response(200) # answer fast: the sender times out after 10 seconds
self.end_headers()
def handle(event: dict) -> None:
data = event["data"]
if event["type"] == "rankings.updated":
for change in data["changes"]:
before, after = change["previous_rank"], change["rank"]
print(f"{change['phrase']} [{change['device']}]: {before} -> {after}")
elif event["type"] == "run.completed":
print(f"Run {data['run_id']} finished: {data['status']}, {data['keywords_checked']} keywords")
elif event["type"] == "lookup.completed":
print(f"Lookup {data['id']} {data['status']}: rank {(data['result'] or {}).get('rank')}")
if __name__ == "__main__":
HTTPServer(("0.0.0.0", 8080), Handler).serve_forever()
How the signature works: the TrackSERPs-Signature header looks like t=<unix>,v1=<hex>. The signed payload is the timestamp, a dot, and the exact raw body bytes, hashed with HMAC-SHA256 using the whole whsec_... string as the key. Verify against the raw bytes before parsing JSON, because re-serialising changes whitespace and breaks the hash. During the 24-hour grace window after a secret rotation the header carries two v1 values, which is why the function accepts a list of secrets and any matching signature. Compare with hmac.compare_digest, not ==.
Operational rules for the receiver:
- Answer within 10 seconds. Do the slow work in a queue; return
200first. - Expect repeats. Failed deliveries are retried with growing delays, 8 attempts in total, and the event
idis stable across attempts. Deduplicate on it. - Failures disable the endpoint. After 20 consecutive failures the endpoint is disabled and the account owner is emailed. The deliveries log,
GET /webhooks/{id}/deliveries, shows status code, attempts and duration for 30 days.
The rankings.updated payload lists changes with keyword_id, phrase, device, previous_rank, rank and ai_overview, plus changes_total. See webhooks and signatures for every event, or the guide on alerting on ranking drops with webhooks for a full alert pipeline.
Export to pandas
Ranking rows contain a nested ai_overview object, so pandas.json_normalize is the right entry point: it turns ai_overview.present into a column. Two choices matter. Cast rank to the nullable Int64 so a missing rank stays missing rather than becoming a float, and filter on change_7d knowing a drop is negative.
import sys
import pandas as pd
from trackserps_client import TrackSerps
client = TrackSerps()
project_id = sys.argv[1]
rows = list(client.latest_rankings(project_id, limit=500))
df = pd.json_normalize(rows, sep="_") # ai_overview.present becomes ai_overview_present
df["rank"] = df["rank"].astype("Int64") # keeps null (not in the top 100) as <NA>, never 0
# One row per keyword and device, so pivot (not pivot_table) keeps unranked rows
# without inventing keyword/phrase combinations that do not exist.
wide = df.pivot(index=["keyword_id", "phrase"], columns="device", values=["rank", "change_7d"])
wide.columns = [f"{metric}_{device}" for metric, device in wide.columns]
lost_ground = df[df["change_7d"] <= -3].sort_values("change_7d")
print(lost_ground[["phrase", "device", "rank", "change_7d"]].to_string(index=False))
df.to_csv("rankings_latest.csv", index=False)
wide.to_csv("rankings_wide.csv")
Run it as python export_rankings.py cmwc0f1yp0005rqk7w1plnab1. It writes a long CSV, a wide one with desktop and mobile side by side, and prints keywords that lost three or more positions in seven days.
A scheduled job that builds your own history
Many teams want rows in their own warehouse. The trick is reading on your own cadence without duplicating data: the check schedule belongs to the project (daily, weekly, monthly or manual), so a daily script against a weekly project sees the same date six days out of seven. Key your rows on (date, keyword_id, device) and skip what you already have.
import csv
import os
import sys
from pathlib import Path
from trackserps_client import TrackSerps
OUT = Path(os.environ.get("SNAPSHOT_FILE", "rankings_history.csv"))
FIELDS = ["date", "project_id", "keyword_id", "phrase", "device", "rank", "rank_absolute", "ranking_url"]
def existing_keys() -> set:
if not OUT.exists():
return set()
with OUT.open(newline="") as f:
return {(r["date"], r["keyword_id"], r["device"]) for r in csv.DictReader(f)}
def main() -> int:
client = TrackSerps()
seen = existing_keys()
new_rows = []
for project in client.projects():
for r in client.latest_rankings(project["id"], limit=500):
if r["date"] is None: # never checked yet
continue
key = (r["date"], r["keyword_id"], r["device"])
if key in seen: # schedule has not produced a newer check yet
continue
new_rows.append({
"date": r["date"], "project_id": project["id"],
"keyword_id": r["keyword_id"], "phrase": r["phrase"], "device": r["device"],
"rank": r["rank"], "rank_absolute": r["rank_absolute"], "ranking_url": r["ranking_url"],
})
write_header = not OUT.exists()
with OUT.open("a", newline="") as f:
w = csv.DictWriter(f, fieldnames=FIELDS)
if write_header:
w.writeheader()
w.writerows(new_rows)
print(f"appended {len(new_rows)} rows")
return 0
if __name__ == "__main__":
sys.exit(main())
Schedule it with cron, a systemd timer or whatever your platform provides. A crontab line that runs after the project's check window:
15 9 * * * cd /srv/rank-job && . .venv/bin/activate && TRACKSERPS_API_KEY=ts_live_replace_me python daily_snapshot.py >> snapshot.log 2>&1
In production, load the key from a secrets manager, and swap the CSV for a table with a unique constraint on the same three columns so the seen check becomes an upsert.
For a row every day regardless, set the project to a daily schedule. That is a credit decision, since each phrase per device costs one credit per check; see the billing documentation.
Fan out across projects with httpx
Agencies often have dozens of projects. httpx.AsyncClient lets you read them concurrently, but the per-key request limit is shared by every call, so cap concurrency instead of firing everything at once.
import asyncio
import os
import httpx
BASE_URL = "https://api.trackserps.com/v1"
async def main() -> None:
headers = {"Authorization": f"Bearer {os.environ['TRACKSERPS_API_KEY']}"}
limiter = asyncio.Semaphore(4) # at most 4 requests in flight
async with httpx.AsyncClient(base_url=BASE_URL, headers=headers, timeout=30) as http:
async def get(path: str, **params) -> dict:
async with limiter:
r = await http.get(path, params=params)
r.raise_for_status()
return r.json()
projects = (await get("/projects", limit=500))["projects"]
pages = await asyncio.gather(*(get(f"/projects/{p['id']}/rankings/latest", limit=500) for p in projects))
for project, page in zip(projects, pages):
top3 = sum(1 for r in page["rankings"] if r["rank"] and r["rank"] <= 3)
print(f"{project['name']}: {top3} rankings in the top 3 (first page of results)")
asyncio.run(main())
Four in flight is a conservative default; raise it only after reading api.rate_limit_per_minute from your usage endpoint. This sample uses raise_for_status with no retries and reads only the first 500 rankings per project, so add the retry rules above and follow next_cursor before pointing it at big accounts.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
401 unauthorized | Missing or wrong Bearer header, revoked or expired key (key_revoked, key_expired) | Check the header is Authorization: Bearer ts_...; create a new key |
400 key_in_query | Key sent as a query parameter | Move it to the header |
403 forbidden_scope | Key lacks the scope, such as runs:write | Create a key with the scope; write scopes need a plan with write access |
422 validation_error | Unknown field, bad enum or out-of-range value | Read fields on the exception; unknown body fields are rejected |
402 insufficient_credits | Balance cannot cover the run | Dry run first; the error includes needed and available |
409 idempotency_mismatch | Same Idempotency-Key reused with a different body | Generate a fresh key per logical request |
429 run_too_soon | Manual run within the 10-minute cooldown | Read retry_after on the exception; reuse the last run |
| Rankings never update | Run still queued, or the project schedule is weekly | Check get_run; remember a normal check takes 10 to 20 minutes |
| Webhook signature fails | Body parsed before hashing, wrong secret, clock skew over 5 minutes | Hash the raw bytes, use the whsec_ string as-is, sync the server clock |
When not to use this
If you only need rankings in a spreadsheet, a connector is less work than a script; the n8n community node and the Postman collection both call the same API without code. If an AI assistant should query rankings in conversation, the MCP server is a better fit. And if your stack is TypeScript, the Node SDK already does everything the client above does, including async pagination and lookup waiting.
To start, follow the API quickstart with a test key, paste in the client and list your projects. When the output looks right, swap in a live key.
Frequently asked questions
Is there an official TrackSERPs Python SDK?
How do I handle 429 errors from the TrackSERPs API in Python?
How long does a run take, and should I poll or use a webhook?
Can I test my Python code without spending credits?
Why is rank null instead of 0 in the response?
How do I verify a TrackSERPs webhook in Python?
Should my script trigger runs or just read results?
Sources & references
- Requests documentation: Advanced usage (sessions, timeouts, retries)(checked 2026-11-11)
- urllib3 documentation: urllib3.util.Retry(checked 2026-11-11)
- HTTPX documentation: Transports(checked 2026-11-11)
- Python documentation: hmac(checked 2026-11-11)
- pandas documentation: json_normalize(checked 2026-11-11)