TrackSERPs
Log in

Rank Tracking with Python: Complete API Tutorial

Quick answer

Python is the industry-standard language for SEO automation, data analysis, and search engine telemetry. By connecting Python's requests library to the TrackSERPs REST API v1, developers can automate keyword position audits, pull top-100 rankings into pandas DataFrames, monitor Google AI Overview citations, and trigger on-demand search scans. Authentication requires a single Bearer header, and responses follow standard HTTP semantics with cursor pagination and Retry-After rate limit handling.

Key facts

  • Python's requests library handles Bearer token authentication, query parameters, and JSON payloads across REST APIs.Source: requests.readthedocs.io
  • The TrackSERPs REST API returns organic positions, absolute ranks and AI Overview citations as JSON.Source: trackserps.com
  • HTTP 429 rate limit responses include Retry-After headers indicating the exact seconds to pause before retrying.Source: rfc-editor.org

What the script below does

TrackSERPs has no Python package; the REST API v1 is plain JSON, so you call it with requests. The script in this guide authenticates with an API key, lists your projects, pages through the latest rankings and reads the AI Overview citation columns, then loads them into pandas. Reading data costs no credits, only requests against your plan's monthly call allowance.

Because checks run on TrackSERPs' schedule, your script reads the latest stored result rather than waiting on a fresh search. That removes the usual reasons home-grown scrapers fail: broken HTML parsing and results that depend on where your server is.

Complete Python rank tracking implementation

This tutorial guides you through building a complete, runnable Python script that authenticates against TrackSERPs, lists active projects, paginates through keyword rankings, and extracts AI Overview citation data.

  1. Set up your Python virtual environment and dependencies

    Create an isolated virtual environment and install the required requests library:

    python3 -m venv venv
    source venv/bin/activate
    pip install requests
    
  2. Initialize authentication headers and API configuration

    Store your API key in an environment variable or local configuration file. Construct standard authorization headers with the Bearer token:

    import os
    import requests
    
    API_KEY = os.getenv("TRACKSERPS_API_KEY", "ts_test_zwd5jy1d_Vd5NTPaoDIOtsk5ZoPUSgjrtiUT6B1v9")
    BASE_URL = "https://api.trackserps.com/v1"
    
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Accept": "application/json"
    }
    
  3. Fetch projects and retrieve your target project ID

    Send a GET request to /v1/projects to list all tracking projects associated with your account:

    resp = requests.get(f"{BASE_URL}/projects", headers=headers)
    resp.raise_for_status()
    projects = resp.json().get("projects", [])
    
    if not projects:
        raise ValueError("No projects found in this account.")
    
    project = projects[0]
    project_id = project["id"]
    print(f"Tracking Project: {project['name']} ({project['domain']}) on {project['engine']}")
    
  4. Query latest keyword rankings with cursor pagination

    Send a GET request to /v1/projects/{projectId}/rankings/latest with query parameters for device and pagination limits:

    params = {"limit": 50}
    rank_resp = requests.get(f"{BASE_URL}/projects/{project_id}/rankings/latest", headers=headers, params=params)
    rank_resp.raise_for_status()
    rankings_data = rank_resp.json()
    rankings = rankings_data.get("rankings", [])
    
  5. Extract positions, SERP features, and AI Overview citations

    Iterate through the retrieved keyword array to extract programmatic rank, visual absolute rank, and generative citation cards:

    for r in rankings:
        phrase = r.get("phrase")
        rank = r.get("rank")
        abs_rank = r.get("rank_absolute")
        features = ", ".join(r.get("serp_features", []))
    
        aio = r.get("ai_overview", {}) or {}
        if aio.get("cited"):
            aio_status = f"Cited: True ({aio.get('cited_url')})"
        elif aio.get("present"):
            aio_status = "Present (Domain Not Cited)"
        else:
            aio_status = "No AI Overview"
    
        print(f"• {phrase:<30} | Rank #{rank or 'Unranked'} (Abs #{abs_rank or '—'}) | {aio_status}")
    

Complete runnable script

Here is the complete, self-contained Python script ready for execution:

import os
import sys
import time
import requests

API_KEY = os.getenv("TRACKSERPS_API_KEY", "ts_test_zwd5jy1d_Vd5NTPaoDIOtsk5ZoPUSgjrtiUT6B1v9")
BASE_URL = os.getenv("TRACKSERPS_BASE_URL", "https://api.trackserps.com/v1")

headers = {
    "Authorization": f"Bearer {API_KEY}",
    "Accept": "application/json"
}

def fetch_all_project_rankings(project_id: str, limit: int = 50):
    """Paginates through all keyword rankings for a project using next_cursor."""
    all_rankings = []
    cursor = None

    while True:
        params = {"limit": limit}
        if cursor:
            params["cursor"] = cursor

        resp = requests.get(f"{BASE_URL}/projects/{project_id}/rankings/latest", headers=headers, params=params)
        
        if resp.status_code == 429:
            retry_after = int(resp.headers.get("Retry-After", 5))
            print(f"Rate limited (429). Retrying after {retry_after}s...")
            time.sleep(retry_after)
            continue

        resp.raise_for_status()
        payload = resp.json()
        items = payload.get("rankings", [])
        all_rankings.extend(items)

        cursor = payload.get("next_cursor")
        if not cursor:
            break

    return all_rankings

def main():
    # 1. List projects
    print("Connecting to TrackSERPs API...")
    proj_resp = requests.get(f"{BASE_URL}/projects", headers=headers)
    proj_resp.raise_for_status()
    projects = proj_resp.json().get("projects", [])

    if not projects:
        print("No projects available.")
        sys.exit(0)

    target_project = projects[0]
    proj_id = target_project["id"]
    print(f"Loaded project: {target_project['name']} | Domain: {target_project['domain']}")

    # 2. Fetch all rankings
    rankings = fetch_all_project_rankings(proj_id, limit=50)
    print(f"Retrieved {len(rankings)} total keyword rankings.\n")

    # 3. Analyze rankings
    top_3 = [r for r in rankings if r.get("rank") is not None and r["rank"] <= 3]
    top_10 = [r for r in rankings if r.get("rank") is not None and r["rank"] <= 10]
    cited = [r for r in rankings if (r.get("ai_overview") or {}).get("cited")]

    print(f"--- Summary Metrics ---")
    print(f"Top 3 Keywords:       {len(top_3)}")
    print(f"Top 10 Keywords:      {len(top_10)}")
    print(f"AI Overview Citations: {len(cited)}")
    print("\n--- Sample Rankings ---")
    for r in rankings[:10]:
        aio = r.get("ai_overview") or {}
        cited_str = f"Cited ✓" if aio.get("cited") else ("Present" if aio.get("present") else "None")
        print(f"  • {r['phrase']:<28} Rank #{r['rank'] or '—':<2} | Abs #{r['rank_absolute'] or '—':<2} | AIO: {cited_str}")

if __name__ == "__main__":
    main()

Exporting rankings to pandas and spreadsheets

Once ranking records are fetched into Python dictionaries, converting them into a pandas DataFrame enables rapid analysis and CSV/Excel export:

import pandas as pd

# Convert rankings list to structured DataFrame
df = pd.DataFrame([
    {
        "keyword": r["phrase"],
        "device": r["device"],
        "organic_rank": r["rank"],
        "absolute_rank": r["rank_absolute"],
        "change_7d": r["change_7d"],
        "change_30d": r["change_30d"],
        "ranking_url": r["ranking_url"],
        "aio_present": (r.get("ai_overview") or {}).get("present"),
        "aio_cited": (r.get("ai_overview") or {}).get("cited"),
        "aio_cited_url": (r.get("ai_overview") or {}).get("cited_url"),
    }
    for r in rankings
])

# Save client-ready spreadsheet
df.to_csv("rankings_export.csv", index=False)
print("Saved rankings to rankings_export.csv")
Python Requests vs. TrackSERPs Node SDK
CapabilityFeaturePython (Requests)Node.js (@trackserps/sdk)
Ecosystem FitData science, Jupyter, pandas, automationFull-stack apps, Next.js, Express, backend services
Type DefinitionsTyped via Pydantic or manual dictionariesStrict TypeScript interfaces and openapi types
Pagination HandlingCustom while loop over next_cursorBuilt-in AutoPagingPromise and async iteration
Idempotency Auto-InjectionPass Idempotency-Key header manuallyAutomatic UUID generation for write operations

Handling errors and rate limiting

When running automated cron jobs or large data pipelines, enforce robust HTTP error handling:

  • Check status codes: Always use resp.raise_for_status() to catch 401 (invalid key), 403 (insufficient scope), or 404 errors early.
  • Honor 429 Retry-After: If request frequency triggers rate limiting, read resp.headers.get("Retry-After") and pause execution with time.sleep().
  • Set realistic timeouts: Always provide timeout=30 in requests.get() to prevent script hangs during network latency.

To learn how to receive automated ranking drop notifications pushed directly to your Python server, read our guide to ranking drop webhooks, or explore our REST API quickstart.

Frequently asked questions

What Python libraries are recommended for SERP rank tracking?
The standard requests library is ideal for HTTP communication, while pandas is recommended for tabular data manipulation, CSV/Excel export, and trend analysis.
How do I authenticate Python API requests with TrackSERPs?
Pass your API key as a Bearer token in the Authorization header: headers = {'Authorization': f'Bearer {API_KEY}', 'Accept': 'application/json'}.
Can Python scripts trigger on-demand search scans?
Yes. Sending a POST request to /v1/projects/{projectId}/runs with an Idempotency-Key header queues a fresh search scan across all project keywords.
How do I extract AI Overview citations in Python?
Each ranking item in the rankings array contains an ai_overview object with present, cited, and cited_url fields. Inspect r['ai_overview']['cited'] to verify domain citations.

Sources & references

  1. Python Requests Documentation(checked 2026-11-11)
  2. RFC 9110 — HTTP Semantics(checked 2026-11-11)

Get product updates and SEO tips

We will email you a link to confirm your address before anything else is sent.