Sub topic 4
Pulling Query-Level Data with the Search Console API
The Search Console web interface shows at most 1,000 rows per report and gives you no way to join queries to pages over a custom date range. The API removes both limits. This chapter shows how to export daily query-and-page rows, page through them, and store them for the cohort analysis in the next chapter.
Prerequisites
This chapter assumes you have:
- Read access to your site's property in Search Console.
- A Google Cloud project where you can enable an API and create credentials.
- Python 3.9 or later with
pandas,google-api-python-clientandgoogle-authinstalled. - Familiarity with the Performance report's four metrics: clicks, impressions, CTR and average position.
Why export through the API
For an AI Overviews study you need three things the interface does not give you:
- Daily granularity. Before/after comparisons need a row per day, so you can set the change date without guessing.
- Query and page together. Cohorts are built from queries, and revenue is joined later at the landing-page level.
- A reproducible snapshot. Search Console keeps about 16 months of data. If you save an export now, your baseline survives after the original dates age out.
Search Console has no AI Overviews filter in the API. Clicks and impressions from AI features are counted inside the ordinary web search type. You will detect exposure separately (a later chapter covers SERP tracking). This export is the raw material only.
Set up access
- In Google Cloud, enable the Google Search Console API for your project.
- Create a service account and download its JSON key.
- In Search Console, open Settings > Users and permissions and add the service account's email address as a user. Restricted (read-only) permission is enough.
- Use the read-only scope,
https://www.googleapis.com/auth/webmasters.readonly.
The service account sees only properties it has been added to. If a call returns a 403 error, the missing permission step is the most common cause.
from google.oauth2 import service_account
from googleapiclient.discovery import build
SCOPES = ["https://www.googleapis.com/auth/webmasters.readonly"]
creds = service_account.Credentials.from_service_account_file(
"service-account.json", scopes=SCOPES
)
service = build("searchconsole", "v1", credentials=creds)
# Confirm which properties this account can read.
for entry in service.sites().list().execute().get("siteEntry", []):
print(entry["siteUrl"], entry["permissionLevel"])The siteUrl you pass later must match the property type exactly. A domain property is written sc-domain:example.com. A URL-prefix property is written with the protocol and trailing slash, such as https://www.example.com/. The two are separate datasets, and the domain property includes all subdomains and protocols.
The shape of a request
A request body names a date range, the dimensions to group by, and a page of rows to return. The core call looks like this:
body = {
"startDate": "2026-01-01",
"endDate": "2026-03-31",
"dimensions": ["date", "query", "page"],
"rowLimit": 25000,
"startRow": 0,
}
resp = service.searchanalytics().query(
siteUrl="sc-domain:example.com", body=body
).execute()
rows = resp.get("rows", []) # each row: keys, clicks, impressions, ctr, positionEach returned row has keys, clicks, impressions, ctr and position. The keys list follows the order of dimensions, so ["2026-01-14", "blue widgets", "https://example.com/widgets"] matches ["date", "query", "page"].
Key parameters:
| Parameter | Meaning | Notes |
|---|---|---|
| `dimensions` | Grouping columns | `date`, `query`, `page`, `country`, `device`, `searchAppearance` |
| `rowLimit` | Rows per response | Maximum 25,000 |
| `startRow` | Zero-based offset | Used for paging |
| `type` | Search type | Defaults to `web`. Other values include `image`, `video` and `news`. |
| `dataState` | Freshness | `final` (default) or `all`, which includes fresh, still-changing data |
| `dimensionFilterGroups` | Row filters | For example, exclude branded queries |
Use dataState: "final" for a study. The all setting includes the most recent days, which are incomplete and get revised. Mixing them into a "post" period makes your latest days look as if clicks fell.
Paging through every row
A quarter of query-and-page data usually exceeds 25,000 rows. The API does not return a "next page" token. You increase startRow by the page size until a response comes back with fewer rows than you asked for.
Here is a complete function that implements the loop and returns a tidy DataFrame:
import pandas as pd
def fetch_gsc(service, site_url, start_date, end_date,
dimensions=("date", "query", "page"), page_size=25000):
all_rows = []
start_row = 0
while True:
body = {
"startDate": start_date,
"endDate": end_date,
"dimensions": list(dimensions),
"rowLimit": page_size,
"startRow": start_row,
"dataState": "final",
}
resp = service.searchanalytics().query(
siteUrl=site_url, body=body
).execute()
rows = resp.get("rows", [])
all_rows.extend(rows)
if len(rows) < page_size:
break
start_row += page_size
df = pd.DataFrame(all_rows)
if df.empty:
return df
keys = pd.DataFrame(df["keys"].tolist(), index=df.index, columns=list(dimensions))
return pd.concat([keys, df.drop(columns="keys")], axis=1)
df = fetch_gsc(service, "sc-domain:example.com", "2026-01-01", "2026-03-31")
df.to_csv("gsc_2026_q1.csv", index=False)
print(df.shape)
print(df.head())The function names the key columns from the dimensions you passed, so the later code can use df["query"] directly. The earlier snippet in this tutorial's cohort chapter builds the same columns from keys by hand. Either approach gives the same result.
What the export does not contain
An export is only as good as its known gaps. Check these before you trust a total.
Anonymized queries are missing
Google withholds rare queries for privacy. These "anonymized queries" are counted in the page and date totals but do not appear as query rows. If you export with ["date"] only and then with ["date", "query"], the query-level click total will be lower. This is expected, not a bug.
daily = fetch_gsc(service, "sc-domain:example.com",
"2026-01-01", "2026-03-31", dimensions=("date",))
by_query = df.groupby("date")["clicks"].sum()
check = pd.DataFrame({
"total": daily.set_index("date")["clicks"],
"with_query": by_query,
})
check["coverage"] = check["with_query"] / check["total"]
print(check["coverage"].describe())Keep the coverage figure. Your report should say something like "query-level rows cover 78% of clicks". If coverage changes sharply between the pre and post periods, your cohort comparison may be distorted by it.
A daily row cap
The API returns a limited number of rows per day per search type, ordered by clicks, so the long tail of low-click query and page combinations may be cut off on large sites. Check Google's current documentation for the exact limit. If your site is large, request narrower slices, for example one device or country at a time, and combine them. You can also reduce the grain by dropping page when you only need query-level numbers.
Average position is not a rank
position is an impression-weighted average of the topmost position your site held when it appeared. A row's position blends different countries, devices and result layouts. Treat it as a trend indicator, not as the rank you would see on one search.
Quotas
The API enforces per-site and per-user query rates. Long exports across many slices should include a short pause and a retry with backoff when you receive a 429 or 5xx error. Check the current quota page rather than relying on a number remembered from a blog post.
Aggregating correctly
Once the data is a DataFrame, one habit prevents the most common mistake in these studies. Never average the ctr column. Each row's CTR has a different number of impressions behind it, so an unweighted mean overweights tiny rows. Sum clicks and impressions first, then divide.
by_month = (
df.assign(month=pd.to_datetime(df["date"]).dt.to_period("M"))
.groupby("month")[["clicks", "impressions"]].sum()
)
by_month["ctr"] = by_month["clicks"] / by_month["impressions"]
print(by_month)Do the same for position: weight it by impressions, as in (df["position"] * df["impressions"]).sum() / df["impressions"].sum().
Common errors
- 403 "User does not have sufficient permission". The service account is not a user on that property, or
siteUrluses the wrong property type. - Empty
rowsfor a valid range. The dates are too recent, the range is older than the retention window, or the site has no data for that search type. - Totals that do not match the interface. You compared different filters, search types or
dataState, or you are looking at a query-level export that excludes anonymized queries. - Duplicated rows after a re-run. You appended a new export to an old file with overlapping dates. Save one file per range, or deduplicate on the dimension columns.
Checklist before moving on
- The service account lists your property and shows the expected permission level.
- The row count from your paging loop is greater than 25,000 for a quarter (if it is not, confirm the date range).
- You have a query coverage ratio from the date-only comparison.
- Totals are stored as sums of clicks and impressions, with CTR recomputed.
- The raw export is saved to disk with the date range in the file name.
Exercise
You export a quarter of data with dimensions ["date", "query"] and compute the site's overall CTR as df["ctr"].mean(). A colleague gets a different number using df["clicks"].sum() / df["impressions"].sum(). Which is correct for a study of the site's click-through rate, and why might the query-level total of clicks also be lower than the total shown in the Performance report?
Show answer
The second figure is correct. Each row's CTR rests on a different number of impressions, so an unweighted mean gives a row with 3 impressions the same weight as a row with 30,000. Summing clicks and impressions first and then dividing weights every impression equally. The query-level clicks are lower because Google withholds anonymized (rare) queries from query rows for privacy, even though those clicks count in the date and page totals. Measure the coverage by comparing a date-only export with the query-level one.