How to migrate Google Custom Search API in Python
Google's Custom Search JSON API is shutting down on January 1, 2027. If your Python app still calls service.cse().list(...).execute(), you'll need to replace that integration before the deadline. Google has already close
Google's Custom Search JSON API is shutting down on January 1, 2027. If your Python app still calls service.cse().list(...).execute(), you'll need to replace that integration before the deadline. Google has already closed the API to new customers. Its official notice points existing users toward a different product for searches limited to 50 domains, or a sales-led option for broader web search.
If you need search results as data rather than a search widget or a generated answer, Spidra Search is one option. It returns titles, links, descriptions, and source-specific fields as JSON. This walkthrough replaces the usual googleapiclient call with a Python client, handles Spidra's asynchronous responses and pagination, and provides a small compatibility helper for existing code that expects Google's title, link, and snippet fields.
The example uses requests so the HTTP changes are visible. Spidra also has a Python SDK that handles job polling if you're writing a new integration rather than migrating an old one.
Start with the Google code you're replacing
A common Custom Search implementation looks like this:
from googleapiclient.discovery import build
def google_search(search_term, api_key, cse_id):
service = build("customsearch", "v1", developerKey=api_key)
response = service.cse().list(
q=search_term, cx=cse_id, num=10
).execute()
return response.get("items", [])
The function returns a list of results containing fields such as title, link, and snippet. Returning response.get("items", []) matters because Google omits items when a search has no matches.
Migrating involves more than changing the endpoint. A Custom Search request uses an engine ID (cx) and numbered offsets (start). Spidra takes the query and any domain restrictions in its JSON request, returns url and description instead of link and snippet, and uses opaque tokens to continue a result set.
| Existing Google code | Spidra equivalent |
|---|---|
q, cx
|
query, optionally includeDomains
|
num=10 |
limit=10 (up to 20 per source) |
items[].link, items[].snippet
|
web[].url, web[].description
|
start, queries.nextPage
|
pageTokens, nextPageTokens
|
siteSearch, siteSearchFilter
|
includeDomains, excludeDomains
|
searchType="image" |
sources=["images"] |
dateRestrict="d7" |
startDate/endDate, or coarser timeRange
|
The rest of the Google response is not automatically preserved. We'll handle the fields most applications use and identify the important gaps later.
Make your first Spidra search in Python
Use Python 3.9 or newer. Install requests and create an API key in the Spidra dashboard. New accounts include 300 free credits without requiring a payment card.
pip install requests
export SPIDRA_API_KEY="spd_YOUR_API_KEY"
Spidra accepts POST /search with an Authorization: Bearer header. Passing "wait": true often gives you the finished result in the same response, but searches that take longer return a job ID. Your code still needs to poll for completion.
Save this complete client as spidra_cse_migration.py. It includes the normal search request, pagination, and the compatibility helper we'll use below.
"""Google Custom Search JSON API migration helpers for Spidra Search.
Install: pip install requests
Set: export SPIDRA_API_KEY='spd_YOUR_API_KEY'
Run: python spidra_cse_migration.py
The legacy helper preserves only the common title/link/snippet fields,
not Google's complete response schema or its search rankings.
"""
import os
import time
import requests
BASE_URL = "https://api.spidra.io/api"
IN_PROGRESS = {"queued", "pending", "active", "running"}
class SpidraAPIError(RuntimeError):
def __init__(self, status, details):
super().__init__(f"Spidra API error ({status}): {details}")
self.status = status
self.details = details
class SearchClient:
def __init__(self, api_key=None, session=None):
self.api_key = api_key or os.environ["SPIDRA_API_KEY"]
self.session = session or requests.Session()
self._legacy_cache = {}
def _request(self, method, path, payload=None):
response = self.session.request(
method,
f"{BASE_URL}{path}",
headers={"Authorization": f"Bearer {self.api_key}"},
json=payload,
timeout=30,
)
try:
body = response.json()
except ValueError as exc:
raise SpidraAPIError(response.status_code, "Non-JSON response") from exc
if response.status_code >= 400:
raise SpidraAPIError(response.status_code, body)
return body
def search(self, query, *, sources=None, limit=10, timeout=180, **options):
"""Return the completed REST API envelope, including result/data."""
payload = {
"query": query,
"sources": sources or ["web"],
"limit": limit,
"wait": True,
**options,
}
envelope = self._request("POST", "/search", payload)
deadline = time.monotonic() + timeout
while envelope.get("status") in IN_PROGRESS:
job_id = envelope.get("jobId")
if not job_id:
raise SpidraAPIError("missing jobId", envelope)
if time.monotonic() >= deadline:
raise TimeoutError(f"Search {job_id} did not finish within {timeout}s")
time.sleep(min(2, max(0, deadline - time.monotonic())))
envelope = self._request("GET", f"/search/{job_id}")
if envelope.get("status") != "completed":
raise SpidraAPIError(envelope.get("status", "unknown"), envelope.get("error"))
if not isinstance(envelope.get("result"), dict):
raise SpidraAPIError("missing result", envelope)
if envelope["result"].get("success") is False:
raise SpidraAPIError("unsuccessful search", envelope.get("error"))
return envelope
@staticmethod
def items(envelope, source="web"):
return envelope["result"]["data"].get(source, []) or []
@staticmethod
def next_token(envelope, source="web"):
return (envelope["result"]["data"].get("nextPageTokens") or {}).get(source)
def collect(self, query, *, target=30, limit=10, max_pages=10, source="web", **options):
"""Collect distinct search results, bounded by page count and target."""
items, seen = [], set()
token = None
for _ in range(max_pages):
page_options = dict(options)
if token:
page_options["pageTokens"] = {source: token}
envelope = self.search(query, sources=[source], limit=limit, **page_options)
page = self.items(envelope, source)
if not page:
break
for item in page:
if item.get("url") and item["url"] not in seen:
seen.add(item["url"])
items.append(item)
if len(items) >= target:
return items
token = self.next_token(envelope, source)
if not token:
break
return items
def cse_items(self, query, *, num=10, start=1, site=None):
"""Return a list of Google-style title/link/snippet items.
This supports the common `return res.get('items', [])` pattern.
It is not a complete cse().list().execute() replacement.
"""
if not 1 <= num <= 10 or start < 1 or start + num - 1 > 100:
raise ValueError("Expected 1 <= num <= 10 and a window within 1..100")
options = {"includeDomains": [site]} if site else {}
# Tuple components are hashable, unlike raw includeDomains lists.
cache_key = (query, site)
pages = self._legacy_cache.setdefault(cache_key, [])
need = start - 1 + num
have = sum(len(self.items(p)) for p in pages)
while have < need and len(pages) < 10:
call_options = dict(options)
if pages:
token = self.next_token(pages[-1])
if not token:
break
call_options["pageTokens"] = {"web": token}
envelope = self.search(query, limit=10, **call_options)
if not self.items(envelope):
break
pages.append(envelope)
have += len(self.items(envelope))
raw = [item for page in pages for item in self.items(page)]
return [
{
"title": item.get("title", ""),
"link": item.get("url", ""),
"snippet": item.get("description") or "",
}
for item in raw[start - 1:need]
]
if __name__ == "__main__":
client = SearchClient()
response = client.search("google custom search json api migration", limit=10)
for hit in client.items(response)[:2]:
print(hit["title"])
print(hit["url"])
Run it with:
python spidra_cse_migration.py
The following two URLs were returned for the same query in the supplied November 24 live run (the output is shortened to the first two results):
Migrate from Custom Search Site Restricted JSON API
https://docs.cloud.google.com/generative-ai-app-builder/docs/migrate-from-cse
Custom Search JSON API | Google for Developers
https://developers.google.com/custom-search/v1/overview
Inside search(), a successful result is under envelope["result"]["data"]["web"]. The items() helper gives you that list directly. You don't have to build your own result parser, and an empty result set gives you an empty list rather than a missing-key exception.
The client also checks terminal job states and raises a useful error if the request fails. That matters in a production integration: a search that returns a job ID is not a completed search yet.
Replace offset pagination with cursor pagination
Google's start=11 fetches the second page of ten results. Spidra instead returns a token for the next page inside nextPageTokens. You send it back in pageTokens along with the same query and filters.
The collect() method in the file handles that loop, stops after a configured number of pages, and removes repeated URLs. Here's how to ask for up to 30 unique search results:
from spidra_cse_migration import SearchClient
client = SearchClient()
hits = client.collect(
"google custom search json api migration",
target=30,
limit=10,
max_pages=5,
)
In the supplied live verification, that query produced 30 distinct results across three pages, with the positions continuing from 1 through 30. A deeper run also found one repeated URL across 100 results. This is why collect() keeps a seen set rather than assuming every new page contains entirely new URLs.
Don't build the loop around totalResults, even if your previous CSE implementation did. Spidra doesn't provide that estimate. It provides a next-page token while further results are available. The explicit max_pages bound also protects you from unintentionally collecting far more than your application needs.
Preserve the fields your existing code expects
You might not be ready to update every function that uses Google's link and snippet keys. The included cse_items() method lets those callers keep reading the same three fields while you migrate their search provider:
from spidra_cse_migration import SearchClient
client = SearchClient()
items = client.cse_items(
"python tutorial", num=10, start=11,
site="docs.python.org",
)
for item in items:
url = item["link"]
description = item["snippet"]
cse_items() converts url to link and description to snippet. It also walks earlier cursor pages when callers request an offset such as start=11, and caches those pages in memory so subsequent calls don't fetch them again in the same client instance.
This is a compatibility helper for the common items list, not a drop-in replacement for the entire service.cse().list(...).execute() interface. It doesn't reproduce Google's engine configuration, totalResults, pagemap, spelling suggestions, or arbitrary CSE parameters. The cache is intentionally per-process; start a new client when you need fresh results.
There's another cost to offset compatibility: fetching start=11 on a new client needs the first page's cursor before it can fetch page two. If you control the application, moving it to collect() or native cursor pagination is better than maintaining offset behavior indefinitely.
Carry your search restrictions over
Domain-restricted search is straightforward when you know the sites your product should search. Rather than configuring a cx engine, send the domains with each request:
client = SearchClient()
response = client.search(
"python tutorial", limit=10,
includeDomains=["docs.python.org"],
)
Spidra enforces includeDomains and excludeDomains on web results. You can specify up to 20 domains in one filter. If your old CSE setup depended on a larger collection of domains or custom engine refinements, audit that configuration before switching. A domain list isn't a replacement for every engine setting.
Date restrictions also need attention. Google's dateRestrict="d7" meant a specific recent period. Spidra's timeRange="week" favors recent results but is not a strict date filter. Use explicit dates if your application needs a bounded period:
response = client.search(
"artificial intelligence", limit=10,
startDate="2026-11-01",
endDate="2026-11-20",
)
Don't send timeRange and startDate/endDate in the same request. Spidra returns a validation error when you combine them. For language preferences, pass language="de"; treat it as a preference, not a guarantee that every result will have a German title. SafeSearch is available as safeSearch="strict" or "off", without Google's intermediate setting. These options are described in the Search API reference.
For image results, change the source rather than adding Google's searchType parameter:
response = client.search(
"mechanical keyboard", sources=["images"], limit=10
)
images = client.items(response, "images")
Image items can include imageUrl, thumbnailUrl, and the URL of the page hosting the image. If you're migrating image handling, update the consuming code as well as the query.
Go beyond an ordinary list of links
If you're replacing CSE inside a research tool or an AI agent, you may need more than web search results. Spidra can search multiple sources in one request, with separate result lists for web, news, images, videos, research papers, and GitHub issues or repositories.
For example, a product research tool can get web pages and news in one job:
response = client.search(
"artificial intelligence announcement",
sources=["web", "news"], limit=10,
)
web_results = client.items(response, "web")
news_results = client.items(response, "news")
When an application needs the source page itself, scrapeOptions can fetch Markdown content for the top web results as part of the same search job:
response = client.search(
"posthog before_send config",
sources=["web"], limit=3,
scrapeOptions={"formats": ["markdown"], "maxResults": 2},
)
The selected results can include a markdown field. Pages that can't be read may lack it, so handle that as an optional field. Content fetching also takes longer and is charged separately from the search. See Search API versus scraping API for when it's worth retrieving page content instead of stopping at the URLs.
Check these differences before switching production traffic
Google's service is retiring, but a migration still needs to preserve the behavior your application depends on. These are the differences I'd test against actual production queries:
- Rankings won't match exactly. Spidra returns search results as data, not a copy of your old Google Programmable Search Engine configuration. Check result relevance on a representative set of queries.
-
No
totalResultsor Googlepagemap. Page on tokens. For page content, request Markdown withscrapeOptions; structured page data is only available for some results, not a guaranteed replacement forpagemap. - Domain filters aren't engine definitions. They restrict results to the domains you send, but they don't reproduce Google's promotions or refinements.
-
Some options work only on certain sources. For example,
sort="date"is for news; date filtering and SafeSearch support also vary by source. Inspectwarningsif you combine sources and filters. - Search results can overlap across pages. Keep a URL deduplication step, especially for longer pagination chains.
One billing detail is easy to miss during testing. Spidra charges one credit per ten results per source, rounded up, and a source returning no results is free. Re-submitting the same search within five seconds can reuse its existing job ID. If you're reconciling search usage from response envelopes, deduplicate by job ID rather than counting the same job twice. The credit rules explain the underlying charges.
For a production cutover, run a sample of your existing queries through both providers while CSE is still available. Compare the fields your code reads, check the behavior of filters and empty result sets, and validate your cost assumptions. Switch the traffic only when the new responses meet the needs of your application.
You now have a Python client for Spidra Search, a bounded cursor paginator, and a compatibility helper for the most common Google result fields. If your application needs only search-result URLs and snippets, the migration can stay small. If it needs page content or additional search sources, the same API can support those workflows without a separate discovery step.
Create a free account at Spidra, set SPIDRA_API_KEY, and run the example against a query your application actually uses.
Frequently asked questions
When does the Google Custom Search JSON API shut down?
Google says existing customers must transition by January 1, 2027. The API is already closed to new customers. Google's published guidance points to Vertex AI Search for searches covering up to 50 domains, or a separate full-web search discussion for broader requirements.
Is Spidra Search a drop-in replacement for googleapiclient?
No. Spidra has a different HTTP request and response model, and it does not reproduce Google's cx engine or every response field. The cse_items() helper above adapts common result fields during migration, but broader integrations must be updated deliberately.
Can I retrieve more than Google's 100-result limit?
Spidra's cursor pagination can continue beyond 100 results when further results are available. The supplied live verification retrieved more than 100. Always set a maximum page count and deduplicate URLs in long-running collection jobs.
Can I migrate an image search or domain-restricted search?
Yes. Set sources=["images"] for image results or use includeDomains and excludeDomains for supported search sources. Image metadata and domain filtering aren't identical to Google's response and engine settings, so test the fields and restrictions your application uses.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.