> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tinyfish.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Migrate from the Google Custom Search JSON API

> Google discontinues the Custom Search JSON API on January 1, 2027. Map every request parameter, response field and error to TinySearch, with a tested adapter in Python and TypeScript.

Google has closed the Custom Search JSON API to new customers and discontinues it on **January 1, 2027**. After that date, requests to `customsearch/v1` stop returning results. TinySearch has the same basic shape: one `GET` request in, a ranked list of titles, URLs and snippets out. To migrate, send `query` instead of `q`, move your key into an `X-API-Key` header, drop `cx`, and read `results[].url` where you read `items[].link` today.

> [!NOTE]
>
> Checked against Google's documentation and the [TinySearch reference](https://docs.tinyfish.ai/tinysearch/reference) on November 29, 2026. Real responses on this page were captured that day and trimmed.

## At a glance

| | Google Custom Search JSON API | TinySearch |
| - | - | - |
| Status | Closed to new customers. Discontinued January 1, 2027 | Available |
| Endpoint | `GET https://www.googleapis.com/customsearch/v1` | `GET https://api.search.tinyfish.ai` |
| Authentication | `key` query parameter | `X-API-Key` header |
| Engine setup | A Programmable Search Engine ID (`cx`) on every request | None |
| Results per request | 1 to 10 (`num`) | Up to 10 per page |
| Deepest result | 100 (`start + num` cannot exceed 100) | 110 (`page` 0 to 10) |
| Free usage | 100 queries a day | 12,000 requests a day, reset at 00:00 UTC |
| Rate limit | Set by your Google Cloud quota | 30 requests a minute and 500 an hour on the free tier. Search Packs go up to 1,200 a minute, with no contract |
| Result types | Web, image | Web, news, research papers |
| Client libraries | Google API client libraries | [`tinyfish`](https://pypi.org/project/tinyfish/) (Python), [`@tiny-fish/sdk`](https://www.npmjs.com/package/@tiny-fish/sdk) (TypeScript), CLI, MCP |

## Who needs to migrate

Any code that calls `https://www.googleapis.com/customsearch/v1` (or `customsearch.googleapis.com`) needs a new search provider before January 1, 2027. That includes backend services, internal assistants, AI agents and scheduled jobs that use Google's client libraries (`build("customsearch", "v1")` in Python, `google.customsearch` in Node.js).

Google's notice on the API page reads: "The Custom Search JSON API is closed to new customers. Vertex AI Search is a favorable alternative for searching up to 50 domains. Alternatively, if your use case necessitates full web search, contact us to express your interest in and get more information about our full web search solution." Vertex AI Search is being renamed Agent Search, and it uses a different API from `customsearch/v1`. If you search the whole web from your own servers, from apps or from agents, TinySearch covers that case.

Search boxes on your website are a separate case. Google's help center says engines already set to "Search the entire web" can keep that setting until January 1, 2027, and that new engines must use "Sites to search", which covers up to 50 domains. Nonprofit, accredited education and government engines are exempt from the 50-domain limit.

> [!WARNING]
>
> Do not switch "Search the entire web" off to test a change. Google's help center says that once it is off, it cannot be switched back on.

Find every call site before you change anything:

```bash theme={null}
# Direct HTTP calls and client-library calls
rg -n "customsearch/v1|customsearch\.googleapis\.com|cse\(\)\.list|build\(\s*[\"']customsearch|google\.customsearch" .

# Configuration that holds the engine ID or key
rg -n "GOOGLE_CSE|CSE_ID|SEARCH_ENGINE_ID|\bcx\b" --glob '!*.lock' .
```

Code search misses scripts, notebooks and no-code tools. In each Google Cloud project, open the API metrics in Cloud Monitoring, choose the resource type "Consumed API" and filter on `service = 'customsearch.googleapis.com'` to see what still calls the API.

For each call site, write down the parameters it sends and the response fields it reads. The tables below map each one.

> [!WARNING]
>
> Starting late? Keep three steps: list the call sites, switch them to the [Google-shaped adapter](#a-google-shaped-adapter) behind a feature flag, and check your 20 most important queries before you turn the flag on.

## Migrate in seven steps

**1. List every call site**

Run the searches above. Note the parameters each call sends and the response fields it reads, such as `items[].link` or `searchInformation.totalResults`.

**2. Create a TinyFish API key**

Create a key at [agent.tinyfish.ai/api-keys](https://agent.tinyfish.ai/api-keys), one per environment. Keys are shown once, so store each as a secret straight away. See [Authentication](https://docs.tinyfish.ai/authentication.md).

**3. Translate the request**

Rename and convert parameters with the [request table](#request-parameters). Remove `cx` and `key`.

**4. Translate the response**

Update field reads with the [response table](#response-fields), or wrap TinySearch in the [Google-shaped adapter](#a-google-shaped-adapter) while you move call sites one at a time.

**5. Update error handling**

Rewrite retries around TinySearch status codes and `error.details`. The [errors section](#errors-and-limits) covers which cases to retry and which to stop on.

**6. Run both side by side**

Send the same real queries to both APIs while your Google access still works, and compare the results. See [Test before you switch](#test-before-you-switch).

**7. Cut over and clean up**

Switch behind a feature flag, watch errors and latency, then remove the Google key and engine ID from your configuration before January 1, 2027.

## Before and after

The same search, first with Google, then with TinySearch.

```bash Google (curl) theme={null}
curl -G "https://www.googleapis.com/customsearch/v1" \
  --data-urlencode "key=$GOOGLE_API_KEY" \
  --data-urlencode "cx=$GOOGLE_CSE_ID" \
  --data-urlencode "q=data retention regulations"
```

```bash TinySearch (curl) theme={null}
curl -G "https://api.search.tinyfish.ai" \
  --data-urlencode "query=data retention regulations" \
  -H "X-API-Key: $TINYFISH_API_KEY"
```

```python Google (Python) theme={null}
from googleapiclient.discovery import build

service = build("customsearch", "v1", developerKey=GOOGLE_API_KEY)
res = service.cse().list(q="data retention regulations", cx=GOOGLE_CSE_ID).execute()
for item in res.get("items", []):
    print(item["title"], item["link"])
```

```python TinySearch (Python SDK) theme={null}
from tinyfish import TinyFish

client = TinyFish()  # reads TINYFISH_API_KEY
response = client.search.query(query="data retention regulations")
for r in response.results:
    print(r.title, r.url)
```

```python TinySearch (requests) theme={null}
import os
import requests

resp = requests.get(
    "https://api.search.tinyfish.ai",
    params={"query": "data retention regulations"},
    headers={"X-API-Key": os.environ["TINYFISH_API_KEY"]},
    timeout=30,
)
resp.raise_for_status()
for r in resp.json()["results"]:
    print(r["title"], r["url"])
```

```typescript Google (TypeScript) theme={null}
const url = new URL("https://www.googleapis.com/customsearch/v1");
url.search = new URLSearchParams({
  key: process.env.GOOGLE_API_KEY!,
  cx: process.env.GOOGLE_CSE_ID!,
  q: "data retention regulations",
}).toString();

const data = await (await fetch(url)).json();
for (const item of data.items ?? []) console.log(item.title, item.link);
```

```typescript TinySearch (TypeScript SDK) theme={null}
import { TinyFish } from "@tiny-fish/sdk";

const client = new TinyFish(); // reads TINYFISH_API_KEY
const response = await client.search.query({ query: "data retention regulations" });
response.results.forEach((r) => console.log(r.title, r.url));
```

A TinySearch response for that query, trimmed to two of ten results:

```json theme={null}
{
  "query": "data retention regulations",
  "results": [
    {
      "position": 1,
      "site_name": "europarl.europa.eu",
      "title": "Towards new EU data retention rules",
      "snippet": "against imposing retention obligations on\nall current and future data handlers, noting that such an approach may amount to blanket retention\nrequirements and to mass surveillance. In addition, the",
      "url": "https://europarl.europa.eu/RegData/etudes/BRIE/2026/789333/EPRS_BRI(2026)789333_EN.pdf",
      "date": "2026-07-09T16:02:46Z"
    },
    {
      "position": 2,
      "site_name": "law.cornell.edu",
      "title": "16 CFR § 312.10 - Data retention and deletion requirements.",
      "snippet": "the operator must establish, implement, and maintain a written data retention policy that sets forth the purposes for which children's personal information is collected, the business need for",
      "url": "https://law.cornell.edu/cfr/text/16/312.10"
    }
  ],
  "total_results": 10,
  "page": 0
}
```

Every web result has five core fields: `position`, `site_name`, `title`, `snippet` and `url`. Some also carry a `date`, and its format varies (an ISO timestamp, or text such as `May 10, 2018`). Snippets can include line breaks and markdown, so clean them if you display them as plain text.

## Request parameters

Every `cse.list` parameter, and what to send instead.

| Google parameter | TinySearch | How to convert |
| - | - | - |
| `key` | `X-API-Key` header | Move the key from the URL into the header |
| `cx` | none | Remove it. TinySearch has no engine to configure. Express an engine's site list with `include_domains` |
| `q` | `query` | Rename |
| `num` | none | Each page holds up to 10 results. Slice the list if you need fewer |
| `start` | `page` | `page = (start - 1) / 10`, from 0 to 10. `position` restarts at 1 on each page |
| `siteSearch` + `siteSearchFilter=i` | `include_domains` | A comma-separated list, so several sites per request |
| `siteSearch` + `siteSearchFilter=e` | `exclude_domains` | A comma-separated list |
| `dateRestrict` | `recency_minutes` | `d[N]` = N × 1,440, `w[N]` = N × 10,080, `m[N]` = N × 43,200, `y[N]` = N × 525,600. Integer from 1 to 5,256,000 (10 years) |
| `sort=date`, `sort=…:r:FROM:TO` | `after_date`, `before_date` | Calendar dates as `YYYY-MM-DD`. Results are not re-sorted by date. Do not combine with `recency_minutes` |
| `gl` | `location` | Country code, such as `US` or `JP` |
| `lr` | `language` | Drop the `lang_` prefix: `lang_ja` becomes `ja` |
| `hl` | `language` | Closest match. `hl` sets Google's interface language; `language` sets result language |
| `cr` | `location` | Closest match. `location` geo-targets results rather than filtering by country of origin |
| `exactTerms`, `excludeTerms`, `orTerms`, `hq` | none | No parameters. Query operators are not documented, so test any you add to `query` before relying on them |
| `fileType` | none | No parameter. Test before relying on a `filetype:` operator in `query` |
| `searchType=image`, `imgSize`, `imgType`, `imgColorType`, `imgDominantColor` | none | TinySearch does not return image results. Keep a separate image source if you need one |
| `safe` | none | Filter results in your own code if you need to |
| `filter` | none | Duplicate filtering is not configurable. Deduplicate by `url` if you need to |
| `rights`, `linkSite`, `lowRange`, `highRange`, `c2coff` | none | No equivalent |
| none | `domain_type` | `web` (default), `news` or `research_paper` |
| none | `pub_year_min`, `pub_year_max` | Publication-year bounds for `domain_type=research_paper` |
| none | `purpose` | An optional sentence (up to 2,000 characters) on why you are searching, used as extra signal for ranking |

### Move your engine's site list

If your engine searches a fixed list of sites, open it in the Programmable Search control panel, copy the patterns under **Sites to search** and **Sites to exclude**, and send their domains as `include_domains` and `exclude_domains`. Both take domains, not URL patterns. A domain also matched its subdomains when we tested on November 29, 2026, so `*.example.com/*` becomes `example.com`. A path pattern such as `example.com/docs/*` has no direct equivalent: filter `results[].url` in your code.

## Response fields

| Google field | TinySearch field | Notes |
| - | - | - |
| `items[]` | `results[]` | |
| `items[].title` | `results[].title` | Plain text. There is no `htmlTitle` |
| `items[].link`, `items[].formattedUrl` | `results[].url` | |
| `items[].displayLink` | `results[].site_name` | |
| `items[].snippet` | `results[].snippet` | Can include line breaks and markdown. There is no `htmlSnippet` |
| array index | `results[].position` | 1-based within the page |
| `items[].pagemap`, `items[].mime`, `items[].fileFormat`, `items[].cacheId` | none | For a page's title, description, author and published date, fetch it with [TinyFetch](https://docs.tinyfish.ai/tinyfetch.md) |
| `queries.request[0].searchTerms` | `query` | |
| `queries.request[0].startIndex` | `page` | `startIndex = page × 10 + 1` |
| `queries.nextPage` | none | Request `page + 1`. Stop at `page=10`, or when a page returns fewer than 10 results |
| `searchInformation.totalResults` | none | `total_results` counts the results on this page, not an estimate of all matches |
| `searchInformation.searchTime` | none | Time the call on your side |
| `spelling.correctedQuery` | none | No spelling suggestions |
| none | `results[].date` | On news results and some web results |
| none | `results[].publisher` | On news results |
| none | `authors`, `venue`, `year`, `cited_by_count`, `pdf_url` | On research-paper results |

## Errors and limits

Google wraps errors as `{"error": {"code", "message", "errors": [...], "status"}}`. TinySearch returns `{"error": {"code", "message", "details"}}`. Branch on the HTTP status and `error.details`, not on the message text.

| Status | `error.code` | When | What to do |
| - | - | - | - |
| 400 | `INVALID_INPUT` | Missing `query` or a bad parameter value | Fix the request. Do not retry |
| 401 | `MISSING_API_KEY`, `INVALID_API_KEY` | The `X-API-Key` header is absent or not valid | Check the header and the key |
| 402 | `INSUFFICIENT_CREDITS` | The free daily allowance is used up and the wallet is at zero or below | Add funds, or wait for the reset at 00:00 UTC. Do not retry on a timer |
| 403 | | The upstream service refused the request | Do not retry blindly |
| 404 | | TinySearch is not available | Check the endpoint. Contact support if it persists |
| 429 | `RATE_LIMIT_EXCEEDED` | The per-minute limit was hit | Wait for `Retry-After`, then retry |
| 429 | `RATE_LIMIT_EXCEEDED` with `details.reason: "free_allowance_exhausted"` | The free daily allowance is used up and wallet spending is off | Do not retry with short backoff. Wait for 00:00 UTC |
| 500, 503 | | Server or rate-limit service unavailable | Retry with exponential backoff |

Successful responses and 429s carry `X-RateLimit-Limit` and `X-RateLimit-Remaining`. Per-minute 429s also carry `Retry-After`, and responses have an `X-Request-ID` to quote to support. The full list is in [Error codes](https://docs.tinyfish.ai/error-codes.md#rate_limit_exceeded).

The Python SDK retries transient errors for you and raises at once on the daily allowance. Set the retry count instead of adding your own loop:

```python theme={null}
from tinyfish import TinyFish

client = TinyFish(max_retries=5)
```

Upgrade when you need more capacity. The free tier gives you 30 requests a minute and 500 an hour, about 12,000 a day, counted across all requests. Search Packs raise that to as much as 1,200 a minute, with no contract. Need a Search Pack or custom limits? [Talk to us](https://www.tinyfish.ai/google-custom-search/book-a-switch-call?utm_source=docs\&utm_medium=migration-guide\&utm_campaign=google-custom-search-switch-2026q4).

## A Google-shaped adapter

If many call sites read Google's response shape, wrap TinySearch in a function that returns it. Move call sites over at your own pace, then delete the wrapper. The adapter raises on any Google parameter TinySearch has no equivalent for, so you find those in testing rather than in production. It also raises when a request fails, so a failure never looks like a search with no results.

```python google_compat.py theme={null}
"""A Google Custom Search-shaped wrapper around TinySearch.

Code that reads items[].link keeps working while you migrate call sites.
Requires Python 3.9+ and `pip install requests`.
"""
from __future__ import annotations

import os
import re
import time

import requests

TINYSEARCH_URL = "https://api.search.tinyfish.ai"

# Google's dateRestrict units, in minutes. Months and years are approximations.
_MINUTES = {"d": 1_440, "w": 10_080, "m": 43_200, "y": 525_600}
_SUPPORTED = {"cx", "key", "siteSearch", "siteSearchFilter", "dateRestrict", "gl", "hl", "lr", "start", "num"}


class TinySearchError(Exception):
    def __init__(self, status: int, code: str | None, message: str,
                 details: dict | None = None, retry_after: str | None = None):
        super().__init__(f"{status} {code or ''} {message}".strip())
        self.status, self.code, self.details, self.retry_after = status, code, details or {}, retry_after


def to_tinysearch_params(q: str, **google) -> tuple[dict, int, int, int]:
    """Translate Google cse.list parameters. Returns (params, offset, num, start)."""
    unsupported = sorted(set(google) - _SUPPORTED)
    if unsupported:
        raise ValueError("No TinySearch parameter for: " + ", ".join(unsupported))

    params: dict = {"query": q}
    if google.get("siteSearch"):
        field = "exclude_domains" if google.get("siteSearchFilter") == "e" else "include_domains"
        params[field] = google["siteSearch"]
    if google.get("dateRestrict"):
        match = re.fullmatch(r"([dwmy])(\d+)", google["dateRestrict"])
        if not match:
            raise ValueError(f"Unrecognised dateRestrict: {google['dateRestrict']}")
        params["recency_minutes"] = min(_MINUTES[match[1]] * int(match[2]), 5_256_000)
    if google.get("gl"):
        params["location"] = google["gl"].upper()
    language = google.get("lr") or google.get("hl")  # lr filters documents; hl is UI language
    if language:
        params["language"] = language.removeprefix("lang_")

    start = int(google.get("start", 1))
    page, offset = divmod(start - 1, 10)
    if page > 10:
        raise ValueError("TinySearch pages stop at page=10, results 101 to 110")
    params["page"] = page
    return params, offset, int(google.get("num", 10)), start


def search(q: str, api_key: str | None = None, timeout: float = 30, **google) -> dict:
    """One TinySearch call, returned in the Google response shape most code reads."""
    params, offset, num, start = to_tinysearch_params(q, **google)
    resp = requests.get(
        TINYSEARCH_URL,
        params=params,
        headers={"X-API-Key": api_key or os.environ["TINYFISH_API_KEY"]},
        timeout=timeout,
    )
    if resp.status_code != 200:
        try:
            error = resp.json().get("error", {})
        except ValueError:
            error = {}
        raise TinySearchError(resp.status_code, error.get("code"), error.get("message", resp.text),
                              error.get("details"), resp.headers.get("Retry-After"))

    results = resp.json()["results"][offset:offset + num]
    items = [
        {
            "kind": "customsearch#result",
            "title": r["title"],
            "link": r["url"],
            "displayLink": r["site_name"],
            "snippet": r.get("snippet", ""),
        }
        for r in results
    ]
    # No equivalent for searchInformation.totalResults, spelling or pagemap.
    return {
        "kind": "customsearch#search",
        "queries": {"request": [{"searchTerms": q, "startIndex": start, "count": len(items)}]},
        "items": items,
    }


def search_with_retry(q: str, retries: int = 4, **kwargs) -> dict:
    """Retries per-minute limits and server errors; never the daily allowance."""
    for attempt in range(retries + 1):
        try:
            return search(q, **kwargs)
        except TinySearchError as err:
            daily_cap = err.details.get("reason") == "free_allowance_exhausted"
            if err.status not in (429, 500, 503) or daily_cap or attempt == retries:
                raise
            time.sleep(float(err.retry_after) if err.retry_after else min(2 ** attempt, 30))
    raise AssertionError("unreachable")
```

```typescript googleCompat.ts theme={null}
// A Google Custom Search-shaped wrapper around TinySearch (Node 18+, Deno, Bun).
const TINYSEARCH_URL = "https://api.search.tinyfish.ai";
const MINUTES: Record<string, number> = { d: 1_440, w: 10_080, m: 43_200, y: 525_600 };
const SUPPORTED = new Set(["cx", "key", "siteSearch", "siteSearchFilter", "dateRestrict", "gl", "hl", "lr", "start", "num"]);

export type GoogleParams = Partial<Record<
  "cx" | "key" | "siteSearch" | "siteSearchFilter" | "dateRestrict" | "gl" | "hl" | "lr",
  string
>> & { start?: number; num?: number; [other: string]: unknown };

export class TinySearchError extends Error {
  constructor(
    public status: number,
    public code: string | undefined,
    message: string,
    public details: Record<string, unknown> = {},
    public retryAfter: string | null = null,
  ) {
    super(`${status} ${code ?? ""} ${message}`.trim());
  }
}

export function toTinySearchParams(q: string, google: GoogleParams = {}) {
  const unsupported = Object.keys(google).filter((k) => !SUPPORTED.has(k)).sort();
  if (unsupported.length) throw new Error(`No TinySearch parameter for: ${unsupported.join(", ")}`);

  const params: Record<string, string> = { query: q };
  if (google.siteSearch) {
    params[google.siteSearchFilter === "e" ? "exclude_domains" : "include_domains"] = google.siteSearch;
  }
  if (google.dateRestrict) {
    const m = /^([dwmy])(\d+)$/.exec(google.dateRestrict);
    if (!m) throw new Error(`Unrecognised dateRestrict: ${google.dateRestrict}`);
    params.recency_minutes = String(Math.min(MINUTES[m[1]] * Number(m[2]), 5_256_000));
  }
  if (google.gl) params.location = google.gl.toUpperCase();
  const language = google.lr ?? google.hl; // lr filters documents; hl is UI language
  if (language) params.language = language.replace(/^lang_/, "");

  const start = google.start ?? 1;
  const page = Math.floor((start - 1) / 10);
  if (page > 10) throw new Error("TinySearch pages stop at page=10, results 101 to 110");
  params.page = String(page);
  return { params, offset: (start - 1) % 10, num: google.num ?? 10, start };
}

export async function search(q: string, google: GoogleParams = {}, apiKey = process.env.TINYFISH_API_KEY) {
  const { params, offset, num, start } = toTinySearchParams(q, google);
  const res = await fetch(`${TINYSEARCH_URL}?${new URLSearchParams(params)}`, {
    headers: { "X-API-Key": apiKey ?? "" },
  });
  if (!res.ok) {
    const body = await res.json().catch(() => ({}));
    const error = body?.error ?? {};
    throw new TinySearchError(res.status, error.code, error.message ?? res.statusText, error.details ?? {},
      res.headers.get("Retry-After"));
  }
  const data = await res.json();
  const items = data.results.slice(offset, offset + num).map((r: any) => ({
    kind: "customsearch#result",
    title: r.title,
    link: r.url,
    displayLink: r.site_name,
    snippet: r.snippet ?? "",
  }));
  // No equivalent for searchInformation.totalResults, spelling or pagemap.
  return {
    kind: "customsearch#search",
    queries: { request: [{ searchTerms: q, startIndex: start, count: items.length }] },
    items,
  };
}

export async function searchWithRetry(q: string, google: GoogleParams = {}, retries = 4) {
  for (let attempt = 0; ; attempt++) {
    try {
      return await search(q, google);
    } catch (err) {
      const dailyCap = err instanceof TinySearchError && err.details.reason === "free_allowance_exhausted";
      const retryable = err instanceof TinySearchError && [429, 500, 503].includes(err.status) && !dailyCap;
      if (!retryable || attempt >= retries) throw err;
      const seconds = err.retryAfter ? Number(err.retryAfter) : Math.min(2 ** attempt, 30);
      await new Promise((resolve) => setTimeout(resolve, seconds * 1000));
    }
  }
}
```

Usage stays close to Google's:

```python theme={null}
from google_compat import search_with_retry

res = search_with_retry("data retention regulations", siteSearch="law.cornell.edu", dateRestrict="y1")
for item in res["items"]:
    print(item["title"], item["link"])
```

## What has no equivalent

Check these against the parameters and fields your code uses before you start.

| Google feature | In TinySearch | What to do |
| - | - | - |
| Image search (`searchType=image`, `img*`) | Not available | Keep a separate image source if you depend on it |
| Page size (`num`) | Up to 10 results a page | Slice the list in your code |
| Phrase and term operators (`exactTerms`, `excludeTerms`, `orTerms`, `fileType`) | No parameters | Use `include_domains` and `exclude_domains` for sites. Other operators in `query` are not documented, so test any you rely on |
| Sort by date (`sort=date`) | No sort parameter | Narrow with `recency_minutes`, or `after_date` and `before_date` |
| Result-count estimate, spelling suggestion, HTML-highlighted fields, `pagemap` | Not in the response | Compute what you need. Fetch the page with TinyFetch for its title, description, author and published date |
| Engine configuration (site lists, refinements, promotions, synonyms) | No engines | Keep your site list in code or config and send it as `include_domains` |
| SafeSearch, license and duplicate filters | No parameters | Filter in your own code if you need to |

## What TinySearch adds

* **News search.** `domain_type=news` returns recent articles with `publisher` and `date` on each result. The date is relative text, such as `9 hours ago`, and news snippets can be empty.
* **Research-paper search.** `domain_type=research_paper` returns `authors`, `venue`, `year`, `cited_by_count` and `pdf_url`, and takes `pub_year_min` and `pub_year_max`.
* **Calendar date windows.** `after_date` and `before_date` take plain `YYYY-MM-DD` dates. Google's `dateRestrict` only counts back from today.
* **Several sites in one request.** `include_domains` and `exclude_domains` take comma-separated lists. Google's `siteSearch` takes one site.
* **Search intent.** `purpose` takes a sentence on why you are searching, used as extra signal for ranking. Leave it out and search behaves as before.
* **Page content from the same key.** Google returns links and snippets only. [TinyFetch](https://docs.tinyfish.ai/tinyfetch.md) takes up to 10 URLs per request, renders JavaScript-heavy pages in a real browser, and returns clean Markdown, HTML or JSON, with one result or one error per URL.

```python Search, then read the top results theme={null}
from tinyfish import TinyFish

client = TinyFish()
found = client.search.query(query="data retention requirements for payment providers")
urls = [r.url for r in found.results[:3]]

pages = client.fetch.get_contents(urls=urls)
for page in pages.results:
    print(page.title, len(page.text or ""))
for error in pages.errors:
    print("Failed:", error.url, error.error)
```

## Test before you switch

Different engines rank differently, so test on your own traffic while your Google access still works.

1. Take 50 to 200 real queries from your logs, including your hardest ones.
2. Run each through both APIs with the same filters.
3. Compare:
   * **Relevance:** have someone who knows the domain label the top results for 20 to 30 queries. This is the real signal.
   * **Overlap:** how many top-10 URLs both APIs return. Use it to find queries worth reading by hand.
   * **Latency:** time both calls from your own servers, at p50 and p95.
   * **Downstream outcome:** if search feeds a model or an assistant, compare the final answers.
4. Agree the pass mark before you look at the numbers.

Compare against the results your engine returns today, not against google.com. Google's help center says engine results are "unlikely to match those returned by Google Web Search". Run a handful of queries through each API twice as well, so you know how much results move on their own before you judge the difference between them.

```python overlap.py theme={null}
def overlap_at_k(google_urls: list[str], tiny_urls: list[str], k: int = 10) -> float:
    """Share of Google's top-k URLs that TinySearch also returns."""
    g, t = set(google_urls[:k]), set(tiny_urls[:k])
    return len(g & t) / max(len(g), 1)
```

For live traffic, send each production query to TinySearch as well, keep serving Google's results, and log both. Switch over once the comparison meets your pass mark.

## Cutover checklist

* [ ] Every call site to `customsearch/v1` is listed, with the parameters it sends and the fields it reads
* [ ] Nothing depends on image search, `num`, query operators or `sort` without a workaround
* [ ] A TinyFish API key exists for each environment, stored as a secret and sent only in the header
* [ ] Requests per minute at peak fit your limit, or you have a Search Pack or custom limit
* [ ] Retries follow the [errors table](#errors-and-limits), including the daily allowance case
* [ ] The side-by-side test met the pass mark you agreed
* [ ] The switch sits behind a feature flag, with a rollback plan
* [ ] Usage is monitored with the dashboard or the [runs API](https://docs.tinyfish.ai/tinysearch/api/runs.md)
* [ ] The Google key and engine ID are removed before January 1, 2027

## Migrate with a coding agent

Paste this prompt into Claude Code, Cursor, Codex or another coding agent at the root of your repository:

```text Prompt theme={null}
Migrate this codebase from the Google Custom Search JSON API to TinySearch.

Read https://docs.tinyfish.ai/tinysearch/how-to/migrate-from-google-custom-search.md first and follow it.

1. Find every call to customsearch/v1, cse().list or the Google customsearch client, and every place that reads the Google key or engine ID (cx). List them before changing anything.
2. Replace each call with TinySearch: GET https://api.search.tinyfish.ai with an X-API-Key header read from the TINYFISH_API_KEY environment variable. Use the official SDK (tinyfish for Python, @tiny-fish/sdk for TypeScript) where the project already has a package manager.
3. Map parameters and response fields with the tables in the guide. Do not invent parameters. If a call uses a Google feature with no TinySearch equivalent (image search, num, exactTerms, sort), stop and list it for me.
4. Update error handling: retry per-minute 429s after Retry-After and 5xx with backoff; never retry a 429 whose error.details.reason is free_allowance_exhausted, or a 402.
5. Update tests, configuration and environment examples. Remove the Google key and cx.
6. Summarize every file changed and anything that needs a human decision.
```

To let the agent search these docs directly, add the docs MCP server at `https://docs.tinyfish.ai/mcp`. To give it TinySearch as a tool while it works, connect the TinyFish MCP server. In Claude Code:

```bash theme={null}
npx -y install-mcp@latest https://agent.tinyfish.ai/mcp --client claude-code
```

Other clients are covered in [MCP Integration](https://docs.tinyfish.ai/mcp-integration.md).

## FAQ

### When does Google turn off the Custom Search JSON API?

On January 1, 2027. Google's API page says the API is closed to new customers and that its pricing applies to existing customers "until the service discontinuation on January 1, 2027."

### What happens to API calls after January 1, 2027?

Google says existing customers have until January 1, 2027 to move, and that its pricing applies "until the service discontinuation on January 1, 2027." It has not said what the API will return after that, so plan for every call to fail and finish your switch before December 31.

### What does "This project does not have the access to Custom Search JSON API" mean?

Developers report this 403 from projects that Google no longer lets use the API, such as newly created ones. The API is closed to new customers, so the fix is to move that call to another search API.

### Will TinySearch return the same results as Google?

No. Each engine ranks differently, and Google's own help center says Programmable Search results are already "unlikely to match those returned by Google Web Search." Judge TinySearch on whether the results answer your users' questions, using the [side-by-side test](#test-before-you-switch).

### Do I need a search engine ID like `cx` with TinySearch?

No. TinySearch searches the web with no engine to set up. To limit results to particular sites, send them as `include_domains`, a comma-separated list.

### How many results can I get per query?

Up to 10 per page, and `page` runs from 0 to 10, so up to 110 results for one query. Google's API stops at 100.

### Does TinySearch support image search?

No. If your code calls Google with `searchType=image`, keep a separate image source for that part.

### Is TinySearch free to use?

Yes. The free tier gives you 30 requests a minute and 500 an hour, up to 12,000 a day, reset at 00:00 UTC. Beyond that, requests need a positive wallet balance.

### How do I get a higher rate limit?

Search Packs raise your limit to as much as 1,200 requests a minute, with no contract. For a Search Pack or custom limits, [talk to us](https://www.tinyfish.ai/google-custom-search/book-a-switch-call?utm_source=docs\&utm_medium=migration-guide\&utm_campaign=google-custom-search-switch-2026q4). A per-minute 429 also includes `details.upgrade_url`, where you can request a higher limit.

### Can I search in Japanese or for a specific country?

Yes. Set `language` (for example `ja`) and `location` (for example `JP`). If you set only one, TinySearch fills in the usual pairing: `language=ja` resolves to `location=JP`.

### How do I get the full content of a result?

Pass its URL to [TinyFetch](https://docs.tinyfish.ai/tinyfetch.md), up to 10 URLs per request. It returns the page as Markdown, HTML or JSON.

### How do I monitor usage after the switch?

Use the dashboard, or the [runs API](https://docs.tinyfish.ai/tinysearch/api/runs.md) (`GET https://api.search.tinyfish.ai/usage`), which filters by time window and by status.

## Related

> [card] [TinySearch API reference](https://docs.tinyfish.ai/tinysearch/reference)
>
> Every parameter and response field

> [card] [How-to guides](https://docs.tinyfish.ai/tinysearch/how-to)
>
> Country and language, site filters, date windows and research papers

> [card] [Error codes](https://docs.tinyfish.ai/error-codes.md)
>
> Every error code, retry rules and rate-limit headers

> [card] [Book a switch call](https://www.tinyfish.ai/google-custom-search/book-a-switch-call?utm_source=docs\&utm_medium=migration-guide\&utm_campaign=google-custom-search-switch-2026q4)
>
> Search Packs, custom limits and help with your move


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.