A SERP tracking API workflow checks the same query, market, and result depth on a schedule. This Python example stores one successful snapshot per scheduled slot in SQLite. It keeps the returned links so you can tell an absent target from a result whose destination you could not verify.
What does a SERP tracking API workflow measure?
A SERP tracking API workflow measures where a URL or domain appears in the returned organic results. Keep the target host and page selection fixed alongside these request settings:
| Field | Why it matters |
|---|---|
| Keyword | Defines the search demand being observed |
| Search engine | Keeps Google and Bing result sets separate |
| Country | Sets the country for the request |
| Language | Sets the result-language preference |
| Checked time | Makes movement and freshness measurable |
SearchCans accepts country as an ISO 3166-1 alpha-2 code and language as a BCP 47 language code. Use the same pair on every scheduled run. A ranking from country: "us", language: "en" should not be compared with a run that used another market definition.
The current Google Search API request does not expose a device selector or city/ZIP parameter. Do not label the output as mobile, desktop, or city-level tracking unless the request contract actually supports that dimension. The country and language reference lists the available values.
What should the rank tracking data model contain?
Keep the query definition separate from the observations. That makes it possible to change a schedule without rewriting history and prevents one keyword’s settings from leaking into another.
A compact model can use three tables:
tracked_queries: keyword, engine, country, language, target host, and page depth.serp_runs: query ID, scheduled slot, actual check time, observation status, and request identifier when available.serp_results: run ID, position, URL, title, and snippet.
Store all returned organic results for the requested page depth. If you save only your target URL, you lose the evidence needed to explain why a position changed. A competitor, marketplace, documentation page, or search feature may have entered the result set even when your page did not change.
Store a null position with an explicit observation status. A successful response can contain no organic rows, contain direct results without the target, or contain a row you cannot attribute. A failed request belongs in the scheduler’s error log.
How do you request Google rankings from SearchCans?
The endpoint is POST https://www.searchcans.com/api/v1/search. The required fields are t for the engine and s for the query. The first block sets up a request for page 1 in US English. Use Python 3.9 or newer with SQLite 3.24 or newer and install requests. Paste the three Python blocks into the same file in order. Set SEARCHCANS_API_KEY before running the script.
import os
import requests
SEARCH_URL = "https://www.searchcans.com/api/v1/search"
QUERY = {
"t": "google",
"s": "google search api",
"country": "us",
"language": "en",
"p": 1,
"d": 30000,
}
def fetch_organic(query, api_key):
response = requests.post(
SEARCH_URL,
headers={"Authorization": f"Bearer {api_key}"},
json=query,
timeout=(5, 35),
allow_redirects=False,
)
if response.status_code != 200:
raise RuntimeError(f"SearchCans HTTP {response.status_code}")
body = response.json()
if not isinstance(body, dict):
raise ValueError("Expected a SearchCans response object")
code = body.get("code")
if type(code) is not int or code != 0:
raise RuntimeError(f"SearchCans API code {code!r}")
data = body.get("data")
if not isinstance(data, dict) or not isinstance(data.get("organic"), list):
raise ValueError("Expected a data.organic array")
return data["organic"]
Read the reported position and link from data.organic. A valid empty array is a completed observation. A missing or malformed array stops the run before it can write a misleading snapshot.
How do p and page change the observation?
Use p when you need one specific result page. Use page when you want pages 1 through N in one request. Do not set both above 1; p takes priority if they conflict.
{
"t": "google",
"s": "serp tracking api",
"country": "us",
"language": "en",
"page": 3
}
At the standard Google Search rate, pages 1, 2, and 3 use three credits when the request succeeds. A successful p: 3 request uses one credit for page 3. Fix the depth in the query definition so a movement from position 9 to position 14 is not confused with a change from one-page tracking to three-page tracking.
How do you match a target domain without false positives?
Compare the exact hostname after removing a leading www.. A URL such as https://other.example/?site=searchcans.com gives you a different hostname. A Google /goto or /url link gives you a wrapper. Leave that row unresolved and keep the original link for review.
import re
from urllib.parse import unquote, urlsplit
DNS_LABEL = r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"
DNS_HOST = re.compile(rf"{DNS_LABEL}(?:[.]{DNS_LABEL})+")
GOOGLE_HOST = re.compile(
r"(?:[a-z0-9-]+[.])*google[.](?:com(?:[.][a-z]{2})?|co[.][a-z]{2}|[a-z]{2})"
)
def normalized_host(host):
host = host.lower().removesuffix(".")
if len(host) > 253 or not DNS_HOST.fullmatch(host):
return None
return host.removeprefix("www.")
def direct_host(link):
if not isinstance(link, str) or "\\" in link:
return None
if any(c.isspace() or ord(c) < 32 or ord(c) == 127 for c in link):
return None
try:
url = urlsplit(link)
_ = url.port # Reject invalid port text.
except ValueError:
return None
if url.scheme not in {"http", "https"} or not url.hostname or url.username is not None:
return None
host = normalized_host(url.hostname)
path = unquote(url.path).rstrip("/")
if host and GOOGLE_HOST.fullmatch(host) and path in {"/goto", "/url"}:
return None
return host
def observe_rank(organic, target_domain):
target = normalized_host(target_domain)
if target is None:
raise ValueError("Pass the target as a DNS hostname")
unresolved = 0
best = None
for row in organic:
link = row.get("link") if isinstance(row, dict) else None
host = direct_host(link)
if host is None:
unresolved += 1
elif host == target:
position = row.get("position")
if type(position) is not int or position < 1:
unresolved += 1
elif best is None or position < best["position"]:
best = {"position": position, "url": link}
if best is not None:
return {"status": "matched", **best, "unresolved_rows": unresolved}
if unresolved:
status = "unresolved"
elif organic:
status = "not_found_in_depth"
else:
status = "no_results"
return {"status": status, "position": None, "url": None, "unresolved_rows": unresolved}
If a batch contains a direct match and an unresolved row, record the best verified position with the unresolved count. The wrapper could still conceal an earlier result. Report not_found_in_depth only when the returned rows can be attributed and none match. To track a particular page, define a separate rule for paths and query strings before collecting it.
How do you store rank history in SQLite?
Pass the scheduler’s intended time as SERP_RUN_SLOT_UTC, for example 2026-11-27T14:00:00Z. Use that same value when rerunning the job. The actual check time can change. SQLite keeps the first successful snapshot for each query definition and slot, including a valid empty response.
import json
import sqlite3
from contextlib import closing
from datetime import datetime, timezone
def utc_timestamp(value):
timestamp = datetime.fromisoformat(value.replace("Z", "+00:00"))
if timestamp.tzinfo is None:
raise ValueError("Use an ISO 8601 timestamp with a UTC offset")
return timestamp.astimezone(timezone.utc).isoformat()
def query_key(query, target_domain):
fields = ("t", "s", "country", "language", "p", "page")
dimensions = {name: query[name] for name in fields if name in query}
dimensions["target"] = normalized_host(target_domain)
return json.dumps(dimensions, sort_keys=True)
def save_run(path, key, slot, checked_at, observation, organic):
with closing(sqlite3.connect(path)) as db, db:
db.execute("""
CREATE TABLE IF NOT EXISTS rank_tracker_slots (
query_key TEXT NOT NULL,
slot_utc TEXT NOT NULL,
checked_at_utc TEXT NOT NULL,
status TEXT NOT NULL,
position INTEGER,
observation_json TEXT NOT NULL,
organic_json TEXT NOT NULL,
PRIMARY KEY (query_key, slot_utc)
)
""")
inserted = db.execute("""
INSERT INTO rank_tracker_slots (
query_key, slot_utc, checked_at_utc, status, position,
observation_json, organic_json
) VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (query_key, slot_utc) DO NOTHING
""", (
key, utc_timestamp(slot), utc_timestamp(checked_at), observation["status"],
observation["position"], json.dumps(observation), json.dumps(organic),
))
return inserted.rowcount == 1
def main():
target = "searchcans.com"
slot = utc_timestamp(os.environ["SERP_RUN_SLOT_UTC"])
organic = fetch_organic(QUERY, os.environ["SEARCHCANS_API_KEY"])
checked_at = datetime.now(timezone.utc).isoformat()
observation = observe_rank(organic, target)
inserted = save_run(
"rank_history.sqlite3", query_key(QUERY, target),
slot, checked_at, observation, organic,
)
if inserted:
print(observation)
else:
print("Snapshot already stored for this query and slot")
if __name__ == "__main__":
main()
The example writes to a new rank_tracker_slots table, leaving older tables intact. A rerun still sends the API request. A successful rerun can use credits even when SQLite discards the duplicate. Keep the raw JSON if you later split result rows out for reporting.
Which failures should a rank tracker retry?
Retry only failures that can change when you wait. SearchCans documents two lane-related cases:
- HTTP
429: all available Parallel Lanes were occupied at the time of the request. - API code
1010inside an HTTP 200 response: all Parallel Lanes were occupied.
Both are temporary. Queue the work, cap concurrency to the account’s available lanes, and retry with a short backoff. HTTP 500 and 503, network timeouts, and the API timeout status are also retry candidates. Check the response body for business errors even when the transport returns HTTP 200.
Do not repeatedly retry HTTP 400, 401, 402, or 403. Those indicate an invalid request, bad credentials, insufficient credits, or missing permission. Retrying without changing the cause only delays the job and makes logs harder to read. The error code reference lists the current meanings.
The sample makes one request. If the scheduler retries a temporary failure, give it an attempt limit and keep the original slot. Record the failed attempt separately.
On 27 November 2026, a US English Google request for SERP tracking API Python rank tracker workflow with a 22,000 ms timeout returned HTTP 200 and code: -1001 (timeout). A separate Bing request for the same phrase returned code: 0 with organic rows. Replaying those responses exercises the two paths: the Google error leaves the slot open for retry, and the Bing response can be stored.
Set application concurrency to the lane count rather than launching an unbounded thread pool. Parallel Lanes limit simultaneous live requests, not the number of requests allowed in an hour. See Rate Limits and Parallel Lanes before setting worker counts.
How often should rankings be checked?
Match the schedule to the decision the data supports:
- Daily: active launches, incident monitoring, or a small set of commercial keywords.
- Two or three times per week: established pages where daily movement would not change a decision.
- Weekly: broad portfolios, long-tail queries, and discovery work.
More frequent checks do not automatically create better SEO decisions. They create more observations, more storage, and more noise. Search results can move between runs because of index updates, regional variation, result features, and normal volatility. Use rolling medians or several consecutive observations before treating a one-position move as a trend.
Run each market at a consistent UTC time. Keep the scheduled time and actual check time so you can spot delayed observations. Leave failed slots visible in the scheduler log.
How do you estimate SERP tracking API cost?
Start with the number of tracked queries, markets, checks, and requested pages:
monthly credits = keywords x markets x checks per month x pages per check
Tracking 500 keywords in two markets once per day at one page per check uses about 30,000 credits in a 30-day month. Requesting pages 1 through 3 would use about 90,000 credits. This estimate covers standard Google Search requests before any retry attempts. Budget for storage and scheduling separately.
SearchCans uses prepaid credits, and the current plan, lane count, and credit validity are listed on the pricing page. Build estimates from that live source instead of copying a price into application logic.
What should a production rank tracking dashboard show?
A useful dashboard should answer a small number of operational questions:
- Was the target matched, absent in the returned depth, or unresolved?
- What is the latest position and seven-run median?
- Which URL ranks for the query now?
- Did the ranking URL change?
- Did the run fail or return a valid empty result array?
- How many credits and retries did the collection job use?
Add alerts for missing runs, repeated authentication or credit errors, ranking URL changes, and sustained position changes. Avoid alerting on every single-position move. A noisy alerting system gets ignored quickly.
How do you keep Google and Bing observations separate?
Keep the engine in the observation key. Use the parameters each engine actually supports. The slot identifies the scheduled check and the observed time tells you when the response arrived.
observation key = engine + query + market parameters + page selection + target host + scheduled UTC slot
Use t: "google" and t: "bing" in separate requests. For Bing use its documented country and page parameters. The Google example’s language and p fields belong to the Google request.
Keep each market and depth in a separate series. A later direct match can be compared with a prior confirmed absence. A prior unresolved result leaves that comparison open.
Use the SearchCans Playground to inspect a request and response, then move the same payload into your script. Keep the API key in an environment variable and review the Google Search API reference before production use.
Before adding more keywords, rerun one slot and confirm that SQLite still holds one row. Check a later slot separately to confirm that a new observation is appended.
Accept a bulk tracking run without losing failed keywords
Deduplicate query definitions before scheduling a bulk run. Track the attempted slots in the scheduler even when some requests fail. Record a failure against the same query and slot that a later retry will use.
A bulk request can finish with only some keywords observed. Retain an explicit status for every scheduled tuple so the dashboard cannot mistake a partial run for a broad ranking decline. When comparing observations, keep depth and market settings the same.
| Outcome | Stored observation |
|---|---|
| Target matched | Best verified position, matched URL and unresolved count |
| Target absent in attributable results | Null position, not_found_in_depth and checked depth |
| Unresolved row without a verified match | Null position, unresolved and raw results |
| Empty organic array | Null position and no_results |
| API or transport error | Scheduler error log and no snapshot |
| Market or depth changed | Separate time series |
Before alerting on a ranking loss, check that both observations used the same request settings and that neither was unresolved. The snapshot records what came back for that request. It cannot attribute a change to a Google update.
Reference documentation: www.searchcans.com — /google-search-api.