To use the Search Console API with Python, authenticate with a service account or Application Default Credentials, call searchanalytics().query() from google-api-python-client with the dimensions you want (query, page, date, country, device), and page through results 25,000 rows at a time with startRow until a page comes back short. That gives you the average Google position for every query your site appeared for, well past the UI's 1,000-row cap. Run it once a day for one finalized day and store the rows, and you have a free, first-party rank tracker built on real impressions instead of a scraped SERP.
This guide goes further than the quick script in our overview of free ways to check keyword rankings. It covers choosing between a service account and user credentials, every request field that changes the numbers you get back (dataState, aggregationType, type), the row and quota limits, and a complete script that writes daily snapshots to SQLite. Everything below was checked against Google's API reference in December 2026, using google-api-python-client 2.201.0 and google-auth 2.61.0 on Python 3.12.
What the Search Console API can and can't tell you about keyword positions
The Search Analytics endpoint returns the same data as the Performance report: clicks, impressions, CTR and average position, grouped by whatever dimensions you ask for. The position is an average of your topmost position across real searches that showed your site. It is not a live check of where you sit right now for one location and device, which is what a commercial keyword rank checker API sells.
That distinction decides whether this is the right tool:
| Question | Search Console API | Third-party rank checker API |
|---|---|---|
| Where did my site actually appear for real users? | Yes, averaged over the day | No, it samples one SERP |
| Every query I rank for, including long tail | Yes, up to the row limits | Only keywords you pay to track |
| Competitors' positions | No | Yes |
| Keywords where I have zero impressions | No, they don't exist in the data | Yes |
| Cost | Free, quota-limited | Per keyword or per request |
| Data freshness | Finalized after roughly 2 to 3 days; provisional data sooner | Same day |
If your question is "what does Google show for this keyword in Chicago on mobile today", buy SERP data. If it's "how is my site ranking across everything it's visible for", the free Google API is the more accurate source, because it measures real impressions. Bing has a free equivalent too; our Bing keyword rank checker guide covers its Webmaster Tools API.
Set up the Search Console API for Python
You need three things: a Google Cloud project with the API enabled, credentials that Search Console recognises, and the client libraries.
- In the Google Cloud console, create or pick a project and enable the Google Search Console API.
- Install the libraries into a virtual environment:
python3 -m venv .venv && source .venv/bin/activate
pip install google-api-python-client google-auth
- Choose an authentication method from the next section.
The read-only scope is enough for everything in this article. The query reference accepts either https://www.googleapis.com/auth/webmasters.readonly or the read-write https://www.googleapis.com/auth/webmasters. Ask for the read-only one; a leaked token then can't submit sitemaps or change anything.
Service account vs OAuth vs Application Default Credentials
| Method | Best for | What Search Console needs |
|---|---|---|
| Service account key (JSON) | Cron jobs, servers, CI | The service account email added as a user on the property |
| Application Default Credentials (your user) | Running scripts from your laptop | Your Google account already has access; set a quota project |
| OAuth installed-app flow | Tools other people run with their own accounts | Each user signs in and consents |
Service account. In IAM, create a service account and a JSON key for it. Its email looks like rank-tracker@your-project.iam.gserviceaccount.com. Search Console doesn't know about Google Cloud IAM, so you have to add that email to the property yourself: Settings > Users and permissions > Add user. Per Google's permissions help page, only owners can add users, and a Restricted user can already view the Performance report, so Restricted is the right level for a read-only job. Google's own Indexing API setup guide uses the same pattern of adding a service account email to a Search Console property. Treat the key file like a password: keep it out of Git and rotate it if it leaks.
Application Default Credentials (ADC). For a script on your own machine, this avoids key files entirely. Log in once with the Search Console scope:
gcloud auth application-default login \
--scopes=https://www.googleapis.com/auth/webmasters.readonly,https://www.googleapis.com/auth/cloud-platform
gcloud auth application-default set-quota-project my-gcp-project
The quota project matters. User credentials have no project of their own, so the API needs to know which project's quota to charge, and that project must have the Search Console API enabled. We run our own Search Console exports this way. Google's gcloud reference says that scopes for APIs outside Google Cloud should be requested with your own OAuth client via --client-id-file; if Google refuses the sign-in with the default client, create a Desktop OAuth client in your project and pass its JSON file there. Note that ADC user tokens can expire, and a cron job then fails with a refresh error that needs an interactive login, which is why unattended jobs should use a service account.
The searchanalytics.query request, field by field
The Python client exposes the endpoint as service.searchanalytics().query(siteUrl=..., body=...). The site URL is either a Domain property written as sc-domain:example.com or a URL-prefix property with its exact protocol and trailing slash, such as https://www.example.com/. Getting this string wrong is the most common cause of a 403.
These are the body fields, per the API reference:
| Field | What it does | Gotcha |
|---|---|---|
startDate, endDate |
Inclusive range, YYYY-MM-DD |
Dates are Pacific Time, not UTC |
dimensions |
Grouping: query, page, country, device, date, hour, searchAppearance, brandedClassification |
Order matters: keys come back in the same order |
type |
web (default), image, video, news, googleNews, discover, webMultimodal |
searchType is deprecated; use type |
dimensionFilterGroups |
Filters with equals, contains, notContains, notEquals, includingRegex, excludingRegex |
Only and groups; equals is case-sensitive for query and page |
aggregationType |
auto, byProperty, byPage |
You can't use byProperty while grouping or filtering by page |
rowLimit |
1 to 25,000, default 1,000 | Leave it at default and you silently get 1,000 rows |
startRow |
Zero-based offset for paging | Past the end, you get a 200 with no rows |
dataState |
final (default), all, hourly_all |
all includes provisional data that may still change |
A few of these deserve more than a table cell.
dataState and data delays
By default you only get finalized data. Google's guide to getting all your data says data is typically available after 2 to 3 days, and recommends finding the newest available day by running a date-grouped query over the past 10 days rather than assuming.
Set dataState to all to include fresh, unfinalized data. When you also group by date, the response carries metadata.first_incomplete_date: values from that day onward may still change. hourly_all works with the hour dimension and returns metadata.first_incomplete_hour. For a rank tracker, store only final data, and use all for dashboards where seeing yesterday's movement matters more than exact numbers.
Aggregation by page vs by property
This is why two correct queries can disagree. Aggregating by property, a search that showed three of your URLs counts as one impression at your topmost position. Aggregating by page, each URL gets its own impression and position. The Performance report help explains the same split in the UI.
For "what position does my site hold for this keyword", group by query alone and request byProperty. For "which URL ranks for this keyword", add page, which forces page aggregation. Don't average the page-level rows to get the property-level number; it won't match.
Search appearance, branded queries and hours
Three dimensions have special rules. The all-your-data guide says searchAppearance can't be combined with other dimensions, so you query it alone first, then filter by each value. brandedClassification (BRANDED or NON_BRANDED) only has data from February 21, 2026, only for top-level properties with enough volume, and can't be combined with a query filter or grouping. hour needs dataState: hourly_all.
Paging past 25,000 rows with startRow
The limit is per request, not per query. Google's instructions are simple: request 25,000 rows, increase startRow by 25,000, and stop when a response has zero rows. The function below stops one request earlier, as soon as a page comes back with fewer than 25,000 rows:
PAGE_SIZE = 25_000
def query_all(service, site, body):
"""Run searchanalytics.query, paging with startRow until a page comes back short."""
body = dict(body, rowLimit=PAGE_SIZE, startRow=0)
rows = []
while True:
resp = service.searchanalytics().query(siteUrl=site, body=body).execute(num_retries=5)
page = resp.get("rows", [])
rows.extend(page)
if len(page) < PAGE_SIZE:
return rows
body["startRow"] += PAGE_SIZE
Two things to know. First, a response with no data has no rows key at all, so use resp.get("rows", []). Second, execute(num_retries=5) makes the client retry 5xx and 429 responses with randomized exponential backoff; I checked this in the library's _should_retry_response. It also retries 403s only when the error reason is a rate limit, so a permissions 403 still fails immediately, which is what you want.
There is also a ceiling paging can't break. Google's performance data deep dive puts the API limit at 50,000 rows per day per site per search type, sorted by clicks. On a large site, the long tail beyond that is cut off. Requests without query or URL dimensions, such as by country or device, return everything.
The anonymized query gap
Your query rows will never add up to the total. Google drops queries that "aren't issued by more than a few dozen users over a two-to-three month period" to protect privacy, per the same deep dive. Those anonymized queries are included in unfiltered totals, but omitted from every query row and from any filtered request.
On a small site the gap is often large, because most long-tail queries are rare. The practical fix is to store the unfiltered daily total separately, as the script below does, and report "share of clicks attributed to visible queries" rather than pretending the rows are complete.
Build a daily rank tracker with Python and SQLite
This script uses the pieces above. Each run finds the newest finalized day, skips it if already stored, and writes three tables: query-level positions aggregated by property (your rank), query and page by country and device (which URL ranked where), and the unfiltered total (which includes anonymized queries).
"""Pull Search Console performance data into SQLite, one finalized day at a time."""
import datetime as dt
import sqlite3
import google.auth
from google.oauth2 import service_account
from googleapiclient.discovery import build
SCOPES = ["https://www.googleapis.com/auth/webmasters.readonly"]
PAGE_SIZE = 25_000 # the API maximum for rowLimit
def get_service(key_file=None, quota_project=None):
"""Service account if key_file is given, otherwise Application Default Credentials."""
if key_file:
creds = service_account.Credentials.from_service_account_file(key_file, scopes=SCOPES)
else:
creds, _ = google.auth.default(scopes=SCOPES, quota_project_id=quota_project)
return build("searchconsole", "v1", credentials=creds, cache_discovery=False)
def query_all(service, site, body):
"""Run searchanalytics.query, paging with startRow until a page comes back short."""
body = dict(body, rowLimit=PAGE_SIZE, startRow=0)
rows = []
while True:
resp = service.searchanalytics().query(siteUrl=site, body=body).execute(num_retries=5)
page = resp.get("rows", [])
rows.extend(page)
if len(page) < PAGE_SIZE:
return rows
body["startRow"] += PAGE_SIZE
def latest_final_date(service, site, search_type="web"):
"""Newest day that has finalized data (the API omits days with no data)."""
today = dt.date.today()
rows = query_all(service, site, {
"startDate": (today - dt.timedelta(days=10)).isoformat(),
"endDate": today.isoformat(),
"dimensions": ["date"],
"type": search_type,
"dataState": "final",
})
return max(r["keys"][0] for r in rows) if rows else None
SCHEMA = """
CREATE TABLE IF NOT EXISTS query_daily ( -- one row per query: your site's rank
day TEXT, query TEXT, clicks INTEGER, impressions INTEGER, ctr REAL, position REAL,
PRIMARY KEY (day, query)
);
CREATE TABLE IF NOT EXISTS query_page_daily ( -- which URL ranked, by country and device
day TEXT, query TEXT, page TEXT, country TEXT, device TEXT,
clicks INTEGER, impressions INTEGER, ctr REAL, position REAL,
PRIMARY KEY (day, query, page, country, device)
);
CREATE TABLE IF NOT EXISTS totals_daily ( -- property total, includes anonymized queries
day TEXT PRIMARY KEY, clicks INTEGER, impressions INTEGER, ctr REAL, position REAL
);
"""
TABLES = { # table -> (dimensions, aggregationType)
"query_daily": (["query"], "byProperty"),
"query_page_daily": (["query", "page", "country", "device"], "byPage"),
"totals_daily": ([], "byProperty"),
}
def snapshot_day(service, site, day, db):
"""Store one finalized day of web data in all three tables. Returns row counts."""
counts = {}
for table, (dims, agg) in TABLES.items():
body = {"startDate": day, "endDate": day, "type": "web",
"dataState": "final", "aggregationType": agg}
if dims:
body["dimensions"] = dims
rows = query_all(service, site, body)
n_cols = 1 + len(dims) + 4
with db:
db.executemany(
f"INSERT OR REPLACE INTO {table} VALUES ({','.join('?' * n_cols)})",
[(day, *r.get("keys", []), int(r["clicks"]), int(r["impressions"]),
r["ctr"], r["position"]) for r in rows],
)
counts[table] = len(rows)
return counts
if __name__ == "__main__":
import argparse
p = argparse.ArgumentParser()
p.add_argument("site", help='e.g. "sc-domain:example.com"')
p.add_argument("--key-file", help="service account JSON key (omit to use ADC)")
p.add_argument("--quota-project", help="GCP project to bill quota to when using user ADC")
p.add_argument("--db", default="gsc.sqlite")
a = p.parse_args()
svc = get_service(a.key_file, a.quota_project)
db = sqlite3.connect(a.db)
db.executescript(SCHEMA)
day = latest_final_date(svc, a.site)
if day is None:
raise SystemExit("no finalized data in the last 10 days")
if db.execute("SELECT 1 FROM totals_daily WHERE day=?", (day,)).fetchone():
print(f"{day} already stored")
else:
print(day, snapshot_day(svc, a.site, day, db))
Run it from cron once a day:
python gsc_rank.py "sc-domain:example.com" --key-file /etc/gsc/rank-tracker.json --db /var/lib/gsc/gsc.sqlite
How I tested it: I can't call Google's API from the machine this was written on, so I ran the script against googleapiclient.http.HttpMockSequence, which replays canned HTTP responses through the real client and discovery document. The test fed a 10-day date list, a 25,000-row page followed by a 1,234-row page, and a totals row, then asserted that the requests carried startRow 0 and 25,000, that the page-level request used byPage and the totals request had no dimensions, and that SQLite ended up with 26,234 detail rows. Run it against your own property on a small date range before trusting it.
Two design choices worth copying. Snapshotting one day per request keeps each query cheap, which is what Google recommends. And INSERT OR REPLACE with a natural primary key makes reruns idempotent, so a cron job that fires twice doesn't double-count.
Check one keyword's position over time
For a quick check of a specific query, filter instead of storing everything. This returns the daily property-level position for one keyword in one country, including provisional recent days:
import datetime as dt
from gsc_rank import get_service, query_all
def keyword_position(service, site, keyword, days=28, country=None):
"""Daily average position for one exact query (property-level, i.e. your best URL)."""
end = dt.date.today()
filters = [{"dimension": "query", "operator": "equals", "expression": keyword}]
if country: # ISO 3166-1 alpha-3, e.g. "usa", "gbr", "ind"
filters.append({"dimension": "country", "operator": "equals", "expression": country})
rows = query_all(service, site, {
"startDate": (end - dt.timedelta(days=days)).isoformat(),
"endDate": end.isoformat(),
"dimensions": ["date"],
"dimensionFilterGroups": [{"filters": filters}],
"dataState": "all", # include the last 1-3 days, still provisional
"aggregationType": "byProperty",
})
return [(r["keys"][0], round(r["position"], 1), int(r["impressions"])) for r in rows]
if __name__ == "__main__":
svc = get_service(quota_project="my-gcp-project")
for day, pos, impr in keyword_position(svc, "sc-domain:example.com", "keyword rank checker api"):
print(day, pos, impr)
Remember that equals is case-sensitive for queries, and that a query anonymized for privacy returns nothing at all, which looks identical to "not ranking".
Turn snapshots into a weekly rank report
Daily position is noisy. Weight by impressions and compare weeks:
WITH w AS (
SELECT query,
CASE WHEN day >= date(:end, '-6 days') THEN 'this_week' ELSE 'last_week' END AS wk,
SUM(impressions) AS impr,
SUM(position * impressions) / SUM(impressions) AS pos
FROM query_daily
WHERE day BETWEEN date(:end, '-13 days') AND :end
AND query IN ('bing keyword rank checker', 'search console api python')
GROUP BY query, wk
)
SELECT t.query,
ROUND(l.pos, 1) AS last_week_pos,
ROUND(t.pos, 1) AS this_week_pos,
ROUND(t.pos - l.pos, 1) AS change,
t.impr AS this_week_impr
FROM w t JOIN w l ON l.query = t.query AND l.wk = 'last_week'
WHERE t.wk = 'this_week'
ORDER BY t.impr DESC;
A negative change is an improvement, since position 1 is the top. The impression weighting is an approximation of what Search Console does over a range, which is fine for trends but won't exactly match the UI for the same dates. This is the comparison we run after events like the November 2026 core update. Once the queries are stored, grouping them into topics is easier with a keyword clustering tool than with hand-written regex.
Quotas and how to stay under them
Google publishes these Search Analytics limits on its usage limits page, as of December 2026:
| Limit | Value |
|---|---|
| Per site | 1,200 queries per minute |
| Per user | 1,200 queries per minute |
| Per project | 40,000 queries per minute, 30,000,000 per day |
| Load quota | Short-term (10-minute windows) and long-term (daily), not published as numbers |
The request count is rarely the problem. The load quota is. Google says grouping or filtering by both page and query is the most expensive request, and that load grows with the date range, so a six-month query costs far more than a one-day one. If you exceed the short-term load quota, wait 15 minutes and retry. The daily one-day snapshot above is the cheapest pattern that still gets every row; backfilling 16 months in one request is the most expensive.
To backfill history, loop over days with a pause, newest first, and stop when a day returns no rows. Search Console retains about 16 months of data, the window Google set with the new Search Console, so anything older is only available if you were already storing it.
Common errors
| Error | Usual cause | Fix |
|---|---|---|
403 User does not have sufficient permission for site |
Wrong siteUrl string, or the service account isn't a user on the property |
Use sc-domain: for Domain properties; add the account in Users and permissions |
403 mentioning a quota project or API not enabled |
ADC user credentials with no quota project, or the API is off in that project | set-quota-project, then enable the API there |
429 or a load quota error |
Too many expensive queries in a short window | Smaller date ranges, fewer dimensions, back off 15 minutes |
400 on a request that uses aggregationType |
byProperty with a page dimension or filter |
Use auto or byPage |
Empty rows |
The range is still unfinalized, the query is anonymized, or equals case doesn't match |
Try dataState: all, contains, or a wider range |
If a URL is missing from the data entirely, the problem is usually indexing, not ranking; start with our guide to crawled but not indexed pages.
Frequently Asked Questions
Is the Google Search Console API free?
Yes. There's no charge per request. You're limited by the published query-per-minute quotas and the unpublished load quotas, and by the 50,000-row daily ceiling per site and search type.
Can I check keyword positions with a Google API for keywords I don't rank for?
No. The Search Console API only reports queries where your site received impressions. For keywords where you have no visibility, or for competitors' positions, you need a third-party SERP or rank checker API.
Why doesn't the API match the Performance report in the UI?
Usually aggregation. Adding the page dimension switches to page aggregation, which counts impressions differently from the property-level chart. Anonymized queries, the final vs all data state, and Pacific Time date boundaries explain most of the rest.
How far back can I pull Search Console data with Python?
About 16 months, the same retention as the UI. If you want longer history, start storing daily snapshots now, because older data can't be requested later.
Does the API include AI Overviews and AI Mode?
Clicks and impressions from those features are counted inside the normal web search data; the API doesn't separate them. Our guide to the Search Console generative AI performance report covers what that separate report shows and its limits.
Should I use a service account or my own Google login?
Use a service account for anything unattended, such as cron or a server, because user tokens can expire and need an interactive login. Use Application Default Credentials for ad-hoc scripts on your laptop, since there's no key file to protect.
Bottom Line
The Search Console API gives you free, first-party keyword positions for everything your site is visible for, but only if you request it correctly: page through with startRow, pick byProperty for rank and byPage for URL analysis, store final data one day at a time, and keep the unfiltered total so the anonymized gap is visible. Set up the daily snapshot now; the history you collect is the part you can't buy back later.