Replace the Google Custom Search JSON API
Google is turning off the Custom Search JSON API. The API is closed to new customers, and existing customers must move to another solution by January 1, 2027. Google gives these terms on the Custom Search JSON API overview page and in the Programmable Search Engine blog post of January 20, 2026 .
This guide moves a site search from the Custom Search JSON API to the Relevan search API. You load the pages of your site into a Relevan index, change the search request, and read the new response.
Quick reference
The field names come from step 1. A sitemap source and the script write the same fields, except that only the script writes site. The full tables are in step 2.
| Custom Search JSON API | Relevan |
|---|---|
GET /customsearch/v1 | POST https://api.relevan.dev/v1/{orgId}/indexes/{indexName}/search with a JSON body |
key | The x-api-key header |
cx | {indexName} in the path |
q | query |
num | size |
start | from, which is start - 1 |
siteSearch | With the script: filters: [{ "field": "site", "value": "docs.example.com" }]. With a sitemap source, give each host its own index. |
sort | Relevan orders results by relevance. For a date range, use a range filter on lastmod. |
items[].title | results[].document.title |
items[].link | results[].document.url |
items[].snippet | Show results[].document.description. |
searchInformation.totalResults | searchContext.totalHits |
queries.nextPage | A next page exists when from + size is less than searchContext.totalHits and is 500 or less. |
Show description in the place of snippet. Step 1 fills description from the <meta name="description"> of the page. When a page lacks that tag, the script uses the first 300 characters of the text of the page. A sitemap source uses the <meta name="description"> tag first, then the og:description tag, and leaves description empty when the page has neither tag. If description is empty, show the start of body.
What is different
Relevan searches the documents in your index: the pages of the sitemaps that you add, and the documents that you upload. It is built to search your own sites and content.
For a search over your own site, you get these changes:
- You choose the fields of each page, and you can filter on them.
- Each result has an
explanationof why it matched. - You can send click and conversion feedback for each search. Relevan uses the feedback in offline training runs that tune the ranking of your index.
1. Load your site into an index
You have three ways to load the pages of your site. The first two make a sitemap source: Relevan fetches each page that your sitemap lists, writes the page to your index, and keeps the index in step with your site.
- In the console. Open Indexes in the console, open the create menu, and choose From a Website. Paste the URL of your sitemap and click Create index. The console shows a DNS TXT record that proves that you control the domain. Add the record at your DNS provider, then click Verify. When the check passes, the console starts the first sync. The Overview of the index has a Website source section that shows each sync.
- With the API. Claim the domain, add the TXT record, and add the sitemap to an index with the domain and source routes. Index a website from its sitemap gives each request.
- With the script below. It reads the
sitemap.xmlof your site, fetches each page, and uploads its title, URL, description, and text to the bulk document endpoint. Use it when you manage the site but not its DNS. It runs on your own server with Python and a write API key, as listed below.
What a sitemap source does
- When you add a sitemap on a verified domain, the first sync starts within 15 minutes. Then Relevan syncs each source about 24 hours after its last sync finished.
- When you verify the domain after you add the sitemap, the first sync starts at once.
- To sync at once, click Sync now in the Website source section, or call the sync route. You can start a manual sync of a source once in 10 minutes.
- A sync fetches the new pages and the pages whose
lastmodchanged, and deletes the documents of the pages that left the sitemap. - Relevan renders a page that builds its text with JavaScript.
- A sitemap source writes the same fields as the script, except
site. It can also writeauthor,published,tags, andtypefrom the metadata of the page.
Your plan limits the pages that Relevan fetches for your organization in a month, and the URLs of one sitemap. Only the pages that changed count toward the limit.
| Plan | Pages fetched a month | URLs of one sitemap |
|---|---|---|
| Free | 2,000 | 2,000 |
| Hobby | 10,000 | 10,000 |
| Small Business | 25,000 | 25,000 |
| Growth | 100,000 | 100,000 |
An Enterprise contract can raise both limits.
With the script
To use the script, you need:
- Python 3.10 or later, and the Relevan client:
pip install relevan. - A write API key from the console, in the
RELEVAN_API_KEYenvironment variable. A read key gets 403 when it creates an index.
Save the script as sitemap_to_relevan.py:
"""Load the pages of a sitemap.xml into a Relevan index.
Usage: python sitemap_to_relevan.py https://example.com/sitemap.xml site-pages
"""
import hashlib
import sys
import time
import urllib.request
import xml.etree.ElementTree as ET
from html.parser import HTMLParser
from urllib.parse import urlparse
from relevan import Client, RelevanAPIError
SITEMAP_NS = {"sm": "http://www.sitemaps.org/schemas/sitemap/0.9"}
SKIP_TAGS = {"script", "style", "noscript", "nav", "header", "footer", "aside", "svg"}
MAX_BODY_CHARS = 20_000
BATCH_SIZE = 100
def fetch(url):
request = urllib.request.Request(
url, headers={"User-Agent": "relevan-sitemap-loader"}
)
with urllib.request.urlopen(request, timeout=30) as response:
return response.read()
def sitemap_entries(sitemap_url):
"""Each (url, lastmod) in the sitemap. A sitemap index is read recursively."""
root = ET.fromstring(fetch(sitemap_url))
if root.tag.endswith("sitemapindex"):
for loc in root.findall("sm:sitemap/sm:loc", SITEMAP_NS):
yield from sitemap_entries(loc.text.strip())
return
for entry in root.findall("sm:url", SITEMAP_NS):
lastmod = entry.findtext("sm:lastmod", namespaces=SITEMAP_NS)
yield entry.findtext("sm:loc", namespaces=SITEMAP_NS).strip(), lastmod
class PageParser(HTMLParser):
def __init__(self):
super().__init__()
self.title = ""
self.description = ""
self.lang = ""
self.text = []
self.main_text = []
self._skip_depth = 0
self._main_depth = 0
self._in_title = False
def handle_starttag(self, tag, attrs):
attrs = dict(attrs)
if tag == "html":
self.lang = (attrs.get("lang") or "").split("-")[0].lower()
elif tag in SKIP_TAGS:
self._skip_depth += 1
elif tag == "main":
self._main_depth += 1
elif tag == "title" and not self._skip_depth and not self.title:
self._in_title = True
elif tag == "meta" and attrs.get("name") == "description":
self.description = attrs.get("content") or ""
def handle_endtag(self, tag):
if tag in SKIP_TAGS and self._skip_depth:
self._skip_depth -= 1
elif tag == "main" and self._main_depth:
self._main_depth -= 1
elif tag == "title":
self._in_title = False
def handle_data(self, data):
if self._in_title:
self.title += data
elif not self._skip_depth and data.strip():
self.text.append(data.strip())
if self._main_depth:
self.main_text.append(data.strip())
def page_document(url, lastmod):
parser = PageParser()
parser.feed(fetch(url).decode("utf-8", errors="replace"))
# Keep only the <main> element when the page has one, to leave out menus.
body = " ".join(parser.main_text or parser.text)[:MAX_BODY_CHARS]
parts = urlparse(url)
content = {
"title": parser.title.strip() or url,
"url": url,
"site": parts.hostname,
"description": parser.description.strip() or body[:300],
"body": body,
}
section = parts.path.strip("/").split("/")[0]
optional = {"section": section, "lang": parser.lang, "lastmod": lastmod}
content.update({name: value for name, value in optional.items() if value})
# A document id allows only letters, digits, "_", ".", ":", and "-", so a
# URL cannot be the id. A hash of the URL is stable across runs.
return hashlib.sha256(url.encode()).hexdigest()[:32], content
def create_index(client, org_id, index_name):
try:
client.indexes.create(org_id, name=index_name)
except RelevanAPIError as error:
if error.status_code != 409:
raise
return
client.mappings.create(
org_id,
index_name,
fields={
"title": {"use": ["searchable", "autocompletable"], "kind": "text"},
"description": {"use": ["searchable"], "kind": "text"},
"body": {"use": ["searchable"], "kind": "text"},
"url": {"use": ["filterable"], "kind": "id"},
"site": {"use": ["filterable"], "kind": "id"},
"section": {"use": ["filterable"], "kind": "id"},
"lang": {"use": ["filterable"], "kind": "id"},
"lastmod": {"use": ["filterable"], "kind": "date"},
},
)
def main(sitemap_url, index_name):
client = Client()
org_id = client.organizations.list()[0].id
create_index(client, org_id, index_name)
batch = []
for url, lastmod in sitemap_entries(sitemap_url):
try:
batch.append(page_document(url, lastmod))
except (OSError, ValueError) as error:
print(f"skip {url}: {error}", file=sys.stderr)
continue
print(f"read {url}")
if len(batch) == BATCH_SIZE:
client.documents.bulk_ingest(org_id, index_name, documents=batch)
batch = []
time.sleep(0.5)
if batch:
client.documents.bulk_ingest(org_id, index_name, documents=batch)
print(f"uploaded the pages of {sitemap_url} to {index_name}")
if __name__ == "__main__":
main(sys.argv[1], sys.argv[2])Run it with the URL of your sitemap and the name of a new index:
python sitemap_to_relevan.py https://www.example.com/sitemap.xml site-pagesThe script makes one document for each page:
| Field | Value |
|---|---|
title | The <title> of the page |
url | The URL from the sitemap |
site | The host name, for example docs.example.com |
section | The first segment of the path, for example blog for /blog/launch |
description | The <meta name="description"> of the page, or the first 300 characters of its text |
body | The text of the <main> element, or of the full page, up to 20,000 characters |
lang | The lang attribute of the <html> element, for example en |
lastmod | The <lastmod> date from the sitemap |
The document id is a hash of the URL, so a second run updates each page in place. To remove a page that left the sitemap, delete its document with the document endpoint, or load the site into a new index.
Relevan builds the index in the background. Before you search, wait until the index status is ready and readyToSearch is true. Get your data in shows the request.
The script reads the HTML of each page as the server sends it. For a page that builds its text with JavaScript, use a sitemap source, which renders the page, or export the content from your CMS or database and upload it with the same bulk endpoint.
2. Change the search request
With your coding agent
After step 1, you can give this prompt to your coding agent, such as Claude Code, Copilot CLI, or Codex. Replace site-pages with the name of your index.
Migrate this codebase's Google Custom Search JSON API calls to Relevan.
Endpoint and auth:
- Replace each GET https://www.googleapis.com/customsearch/v1 request with
POST https://api.relevan.dev/v1/{orgId}/indexes/site-pages/search and a JSON body.
- Send the API key in the x-api-key header. Read the key from the RELEVAN_API_KEY
environment variable, and keep the key on the server.
- Get {orgId} once from GET https://api.relevan.dev/v1/organizations (the "id" of the
first item), and keep it in configuration as RELEVAN_ORG_ID.
- Remove the Google key and cx parameters and their configuration.
Request mapping:
- q -> query
- num -> size (1 to 100)
- start (starts at 1) -> from = start - 1 (a maximum of 500)
- siteSearch=<host> -> filters: [{ "field": "site", "value": "<host>" }] when the index
has a site field. An index from a sitemap source holds the pages of each host that
its sitemap lists. For such an index, remove siteSearch when the sitemap lists one
host. Otherwise, stop and ask me.
- lr=lang_<code> -> filters: [{ "field": "lang", "value": "<code>" }]
- sort=date:r:<YYYYMMDD>:<YYYYMMDD> -> filters: [{ "field": "lastmod", "gte": "<YYYY-MM-DD>", "lte": "<YYYY-MM-DD>" }]
- Any other sort: remove it. Relevan orders results by relevance.
- exactTerms -> add the phrase to query in double quotes.
- excludeTerms -> add each word to query with a minus sign, for example -password.
Response mapping:
- items -> results
- items[].title -> results[].document.title
- items[].link -> results[].document.url
- items[].displayLink -> results[].document.site, or the host of results[].document.url
- items[].snippet and htmlSnippet -> results[].document.description. If
description is empty, use the first 200 characters of results[].document.body.
- searchInformation.totalResults (a string) -> searchContext.totalHits (a number)
- searchInformation.searchTime (seconds) -> took (milliseconds)
- queries.nextPage -> a next page exists when from + size is less than
searchContext.totalHits and from + size is 500 or less.
Keep the existing results UI unchanged. Convert the Relevan response to the shape
that the UI reads now, in one function. Keep searchContext.queryId of each search
next to its results, for click feedback later. For Python code, you can use the
relevan client (pip install relevan): client.search.search(org_id, index_name,
query=..., size=..., offset=..., filters=[...]), where offset is from. Update the
tests that mock the Google response, and run the tests.By hand
The Custom Search JSON API takes a GET request with query parameters. Relevan takes a POST request with a JSON body. Your API key goes in the x-api-key header, and the index name goes in the path in place of cx.
Custom Search JSON API:
curl "https://www.googleapis.com/customsearch/v1?key=$GOOGLE_API_KEY&cx=$SEARCH_ENGINE_ID&q=reset+password&num=10&start=11&siteSearch=docs.example.com"Relevan:
curl -X POST https://api.relevan.dev/v1/{orgId}/indexes/site-pages/search \
-H "x-api-key: $RELEVAN_API_KEY" \
-H "content-type: application/json" \
-d '{
"query": "reset password",
"size": 10,
"from": 10,
"filters": [{ "field": "site", "value": "docs.example.com" }]
}'The same search in Python. Custom Search JSON API:
import os
import requests
response = requests.get(
"https://www.googleapis.com/customsearch/v1",
params={
"key": os.environ["GOOGLE_API_KEY"],
"cx": os.environ["SEARCH_ENGINE_ID"],
"q": "reset password",
"num": 10,
"start": 11,
"siteSearch": "docs.example.com",
},
)
for item in response.json().get("items", []):
print(item["title"], item["link"], item["snippet"])Relevan:
from relevan import Client
from relevan.resources.search import SearchFilterType0
client = Client()
org = client.organizations.list()[0]
results = client.search.search(
org.id,
"site-pages",
query="reset password",
size=10,
offset=10,
filters=[SearchFilterType0(field="site", value="docs.example.com")],
)
for hit in results.results:
print(hit.document["title"], hit.document["url"], hit.document["description"])Request parameters
| Custom Search JSON API | Relevan |
|---|---|
key | The x-api-key header. Use a read key for search. |
cx | The index name in the path: /v1/{orgId}/indexes/{indexName}/search |
q | query |
num (1 to 10) | size (1 to 100, default 10) |
start (starts at 1) | from (starts at 0, a maximum of 500). Use from = start - 1. The Python client calls it offset. |
siteSearch with siteSearchFilter=i | With the script, which writes site: { "field": "site", "value": "docs.example.com" }. The site field comes only from the script. A sitemap source indexes each host under the verified domain that the sitemap lists, so give each host its own index. For a path such as example.com/blog, filter on section. |
siteSearch with siteSearchFilter=e | Filters list the values to keep. So use an in filter that lists every host to keep, or keep the excluded pages out of the index. |
lr, hl | A filter on lang: { "field": "lang", "value": "fr" }. Text analysis supports english and none. |
dateRestrict, sort=date:r:... | A range filter on lastmod: { "field": "lastmod", "gte": "2026-11-01" } |
sort=date | Relevan orders results by relevance. |
exactTerms | Put the phrase in quotes in query, for example reset "two-factor code". Each result must contain a quoted phrase. |
excludeTerms | Put a minus sign before the word in query, for example reset -password. Relevan leaves out each document with password in a searchable field. |
orTerms | Add the words to query. A result can match some of the words. To give a word more weight, use boost, for example { "reset": 2 }. |
searchType=image | Relevan searches the text of the documents in your index, and returns documents. To show an image for each result, change the script in three places: add "image": {"use": ["filterable"], "kind": "id"} to its mapping, set content["image"] in page_document, for example from the og:image meta tag, and run it with a new index name. The script sets the mapping only when it creates the index. |
safe, gl, cr | You choose the pages in the index. To filter on another property, add it as a field. |
Response fields
| Custom Search JSON API | Relevan |
|---|---|
items[] | results[] |
items[].title | results[].document.title |
items[].link | results[].document.url |
items[].displayLink | results[].document.site, or the host of results[].document.url |
items[].snippet, htmlSnippet | Show results[].document.description. results[].matchedTerms lists the words that matched, so you can mark them in the text. |
items[].pagemap | Declare each value that you need, such as an image URL, as a field in the mapping of a new index, then store it in each document. Each field comes back in results[].document. |
searchInformation.totalResults | searchContext.totalHits (a number) |
searchInformation.searchTime | took (in milliseconds) |
queries.nextPage | A next page exists when from + size is less than searchContext.totalHits and is 500 or less, the maximum from. |
spelling.correctedQuery | When a query returns zero results, Relevan can run a less strict query: a one-word query with typo tolerance, or a long query that needs fewer of its words. When the second query finds results, searchContext.fallback says so. |
| (none) | results[].explanation: why the result matched. searchContext.queryId: the id that the feedback request needs. |
Custom Search JSON API response, shortened:
{
"searchInformation": { "searchTime": 0.21, "totalResults": "42" },
"items": [
{
"title": "Reset your password - Example Docs",
"link": "https://docs.example.com/account/reset-password",
"displayLink": "docs.example.com",
"snippet": "To reset your password, open Settings and select ...",
"pagemap": { "metatags": [{ "og:image": "https://docs.example.com/og.png" }] }
}
]
}Relevan response, shortened. It comes from a test index of the 17 pages of docs.relevan.dev, for the query send click feedback:
{
"results": [
{
"id": "<the hash of the URL>",
"score": 2.335301,
"document": {
"url": "https://docs.relevan.dev/guides/get-your-data-in",
"body": "Get your data in This guide takes you from a new organization to your first sear ...",
"lang": "en",
"site": "docs.relevan.dev",
"title": "Get your data in",
"section": "guides",
"description": "Search that understands your customers"
},
"explanation": "Matched: \"send\", \"sent\", \"feedback\", \"click\", \"clicks\" in body (2.34). Total score: 2.335",
"matchedFields": ["body"],
"matchedTerms": ["send", "sent", "feedback", "click", "clicks"]
}
],
"searchContext": {
"queryUsed": "send click feedback",
"totalHits": 12,
"matchedTerms": ["send", "sent", "feedback", "click", "clicks", "end"],
"topContributingFields": ["body"],
"titleField": "title",
"scoringSummary": "Highest retrieval score 2.335. Matched: \"send\", \"sent\", \"feedback\", \"click\", \"clicks\" in body (2.34). Total score: 2.335",
"suggestions": "All query terms contributed to at least one match. Fields searched: [body, description, title].",
"searchableFields": ["body", "description", "title"],
"sessionId": "9b4b1308-7748-48f0-b50d-1bbffe18a7eb",
"queryId": "Root=1-6b05b1d2-122e85424fe0c7a37c665eda"
},
"took": 191
}3. Send feedback
When a user clicks a result, send a click event from your server with the queryId of the search and the document id. Send feedback in the Getting started guide shows the request.
Cost
The Custom Search JSON API gives 100 queries a day free. Each further 1,000 queries cost $5, up to 10,000 queries a day. Relevan sells monthly plans with a fixed number of searches.
| Searches a month | Custom Search JSON API (estimate) | Relevan plan |
|---|---|---|
| 3,000 | $0 | Free: $0, 10,000 searches |
| 10,000 | $34.95 | Free: $0, 10,000 searches |
| 50,000 | $235 | Hobby: $20, 50,000 searches |
| 250,000 | $1,234.95 | Small Business: $79, 250,000 searches |
| 1,000,000 | Over the limit of 10,000 a day | Growth: $299, 1,000,000 searches |
The Custom Search JSON API column assumes the same number of queries each day of a 30-day month. For example, 50,000 searches are about 1,667 a day. 100 of them are free, so 1,567 a day are billed: 47,000 in the month, at $5 for each 1,000.
Each Relevan plan also limits the storage of your documents: 100 MiB on Free, 300 MiB on Hobby, 1 GiB on Small Business, and 2 GiB on Growth. The price of each plan is fixed. When an organization uses all the searches of its plan, a search gets 402 until the first day of the next month (UTC). See pricing for each plan.
Prices are as of November 2026. Check Google’s overview page for the current Custom Search JSON API terms.
Questions
Email hello@relevan.dev with the questions about your migration.