DEV Community

Petix Pleasure
Petix Pleasure

Posted on

SerpApi-compatible API: 20-line migration and three gotchas

Every note about the SerpApi-compatible endpoint says the same thing: replace https://serpapi.com/search.json with https://api.serpbase.dev/google/serpapi/search.json, keep your parameters, keep your parser. That is true, and it is enough to get a 200 back on the first call. The engine table now covers 27 engines, which is what makes the move realistic for a workload that does more than plain web search.

It is not enough for the second week. Three behaviours differ from SerpApi, and none of them raises on the happy path. One hands you a different page layout, one removes keys your code indexes into, and one reports failure with HTTP 200. All three pass a smoke test.

What actually stays the same

27 engine names carry over, each running on a native endpoint and costing what that endpoint costs (checked 2026-11-23, per-endpoint credits table in the docs). The figures are not uniform: 12 of the 27 cost 1 credit and 14 cost 2. The remaining one is Google AI Mode, priced separately on its product page. A budget built on "one credit per call" is wrong for any workload that mixes them.

engine runs on credits per request
google /google/search 1
google_news /google/news/search 1
amazon /amazon/search 2

Parameter names carry over as well: q, gl, hl, device, plus the per-engine ones such as k and amazon_domain. Requests are GET, as on SerpApi. The key goes in the X-API-Key header, which keeps it out of URLs and logs.

# before
curl "https://serpapi.com/search.json?engine=google&q=coffee&gl=us&hl=en&api_key=$SERPAPI_KEY"

# after: same query, same parameter names, key moved to the header
curl "https://api.serpbase.dev/google/serpapi/search.json?engine=google&q=coffee&gl=us&hl=en" \
  -H "X-API-Key: $SERPBASE_API_KEY"
Enter fullscreen mode Exit fullscreen mode

An engine outside that table is refused with 400 rather than mapped onto something close, which fails loudly at migration time.

Pagination is the parameter to test before you move traffic. SerpApi's google engine pages with start, an offset in multiples of ten (checked 2026-11-23). SerpBase's own google endpoint takes page, 1-based, and the compatibility page does not say how the two map, so send one second-page request and look. Billing does carry over: each page is a separate request and a separate charge (checked 2026-11-23, billing doc).

The boundary matters before you move anything. Not served: output=html except on engine=google; Maps place lookups, which go to /google/maps/detail; Trends types other than TIMESERIES; Play stores other than apps; SerpApi's account, archive and async APIs. no_cache, async and json_restrictor are accepted and have no effect, so a request that sets no_cache does not bypass a cache.

Gotcha 1: no device means phone results

From the compatibility page:

A google search that sets no device is not treated as desktop, as SerpApi does: it gets phone results, the same default as /google/search, and search_parameters then has no device field. Send device=desktop for desktop results.

SerpApi's google engine defaults to desktop (checked 2026-11-23), so migrated code usually never sends device. Here the identical request returns the phone layout, and two things follow.

The two layouts are not the same document. Some modules exist in one and not the other, so a parser written for desktop comes back with fewer sections and no error to log. position is relative to the layout it was measured in. Your history is desktop, the new rows are mobile, the series bends, and the first suspicion is the API.

You also cannot tell afterwards. When no device was sent, search_parameters has no device field at all. Code that reads search_parameters["device"] fails on exactly the requests that need checking, and code that defaults a missing value to desktop records the wrong answer.

import os, time, requests

BASE = "https://api.serpbase.dev"
KEY = os.environ["SERPBASE_API_KEY"]

# what you had on SerpApi: desktop, implicitly
old = requests.get(
    "https://serpapi.com/search.json",
    params={"engine": "google", "q": "espresso machine", "gl": "us"},
    timeout=60,
)

# the same call here returns phone results; ask for desktop
new = requests.get(
    BASE + "/google/serpapi/search.json",
    headers={"X-API-Key": KEY},
    params={"engine": "google", "q": "espresso machine", "gl": "us", "device": "desktop"},
    timeout=60,
)
print(new.json()["search_parameters"].get("device"))  # 'desktop', when the field is echoed
Enter fullscreen mode Exit fullscreen mode

The default is documented for engine=google. Read the parameter table of any other Google engine before assuming the same, and send device explicitly wherever the layout matters.

Gotcha 2: missing keys are missing, not null

Also from the compatibility page:

A field SerpBase does not produce is left out rather than filled with a guess, so check for a key before reading it.

SerpApi code in production usually carries one of three guards, and only one is correct:

  • data["knowledge_graph"]["title"] raises KeyError on the first query without a knowledge panel.
  • if data.get("knowledge_graph") is not None: leaves the branch untaken, so the feature disappears and nothing is logged. This is the one that survives code review.
  • data.get("knowledge_graph", {}) is correct, and it degrades to empty rather than raising.

Nested fields behave the same way. sitelinks exists only when a result has sitelinks, so for s in hit["sitelinks"] raises on ordinary results and passes on the query you happened to test. The failure arrives when a new keyword class enters the queue.

credits_charged is required but may be null, and null means the charge is still being settled. Code that does if credits_charged > 0 raises on that case; code that reads falsy as free counts an unsettled request as costing nothing.

A dotted-path reader handles all of it without a guard per field:

def dig(obj, path, default=None):
    for part in path.split("."):
        if not isinstance(obj, dict) or part not in obj:
            return default
        obj = obj[part]
    return obj

panel     = dig(result, "knowledge_graph.title")       # None when there is no panel
sitelinks = dig(hit, "sitelinks", [])                  # [] when the result has none
outcome   = dig(result, "search_metadata.status")      # "Error" means it ran and failed
Enter fullscreen mode Exit fullscreen mode

Before cutting traffic over, diff the key sets of both endpoints on twenty or thirty of your own queries. Values move between runs; key sets show which fields your parser was silently relying on.

keys_old = set(old.json())
keys_new = set(new.json())
print("dropped:", sorted(keys_old - keys_new))
Enter fullscreen mode Exit fullscreen mode

Gotcha 3: two error shapes, one retry policy

A refused request never ran: HTTP 400 for a bad parameter or an engine outside the table, 401 for the key, 429 for the rate limit, each with a body of {"error": ...}.

A search that ran and failed is different: HTTP 200, search_metadata.status set to "Error", and no charge.

raise_for_status() only catches the first shape. A 200 carrying Error goes into your parser, organic is missing or empty, and the pipeline records "no results": a failed call written down as a real answer. Generic retry decorators have the opposite problem: they retry 400 and 401 as though those were transient.

The policy that fits both shapes:

  • Retry 429, after waiting the number of seconds in Retry-After.
  • Retry a 200 whose search_metadata.status is "Error". Failed searches are not charged, so a resend costs nothing until one attempt succeeds.
  • Do not retry 400 or 401. Fix the request.
  • Cap attempts at three, so a retry storm cannot spend your rate limit on one query.

One naming trap: the compatible path reports the outcome in search_metadata.status, while the native endpoints put a numeric status at the top where 0 means success. Code copied between the two doc sets checks the wrong one.

For pacing, every response carries X-RateLimit-Limit and X-RateLimit-Remaining. When Remaining reads 0, the next request that second will be refused, so sleep instead of finding out. The limit is per account, not per key (checked 2026-11-23, API keys doc), so a second key splits the same budget.

Billing has one edge that looks like a bug: a request that reached the source and failed is not charged, while a request that succeeded with a "not found" answer is charged, because a confirmed absence is data. Both arrive as HTTP 200.

Timeouts are the third place where a short setting looks harmless, and here there is measured data. SerpBase timed 970,882 successful Google searches over 2–8 November 2026, out of 1,061,676 requests (published 2026-11-09). Elapsed seconds:

percentile page 1 page 2 and later
p50 1.9 4.9
p90 4.8 21.3
p95 7.0 25.6

The median makes a short timeout look safe; the tail sits on the later pages. A 5-second client timeout keeps 91.0% of first-page results and 50.7% of later ones; fifteen seconds keeps 98.8% and 79.0%. Nothing in the week took longer than 30 seconds, the slowest success was 29,999 ms, so a 60-second client timeout covers the server's own 30-second ceiling and waiting beyond it gains nothing. The sample counts only successes, covers one week on one provider, and excludes clients that hung up early.

On the request side, the Google endpoints take timeout of 1 to 30 seconds: retries start earlier to fit that budget and you get status 1504 at once, not charged. Hanging up on the client instead refunds the request but leaves you with no result and no error to act on.

The wrapper

The function is twenty lines, counting from def to the final raise. The constant above it, BASE, KEY, dig() and the imports come from the earlier snippets.

COMPAT = BASE + "/google/serpapi/search.json"

def search(engine, attempts=3, **params):
    if engine == "google":
        params.setdefault("device", "desktop")          # gotcha 1
    for n in range(attempts):
        r = requests.get(COMPAT, headers={"X-API-Key": KEY}, timeout=60,
                         params={"engine": engine, **params})
        if r.status_code == 429:                        # refused, not charged
            time.sleep(float(r.headers.get("Retry-After", 1)))
            continue
        if r.status_code >= 500:                        # server side, safe to retry
            time.sleep(1 + n)
            continue
        if r.status_code in (400, 401):                 # the request has to change
            raise ValueError(r.text or r.status_code)
        body = r.json()
        if dig(body, "search_metadata.status") == "Error":   # ran, failed, not charged
            time.sleep(1 + n)
            continue
        return body
    raise RuntimeError(f"{engine} still failing after {attempts} attempts")
Enter fullscreen mode Exit fullscreen mode

The order of the checks is the point. 429 and 5xx leave before the body is parsed, 400 and 401 raise because no amount of waiting turns a bad parameter into a good one, and only a 200 goes on to search_metadata.status. Pacing stays outside: this is one request, so it returns to whatever schedules your calls.

# constants from the earlier snippet: BASE, COMPAT, KEY, dig()
result = search("google", q="espresso machine", gl="us", hl="en")
for hit in result.get("organic", []):
    print(hit.get("position"), hit.get("link"))
Enter fullscreen mode Exit fullscreen mode

This does not make the two services identical. It puts the three differences in one place: device is pinned where the layout matters, every read goes through dig, and only the retryable shape is resent.

The compatible path also serves no more than before: a Maps place lookup still calls /google/maps/detail, Trends answers only TIMESERIES, and output=html works only on engine=google. Those are route decisions, not parameters, so a wrapper cannot smooth them over.

The same key reaches 44 callable endpoints across six categories, with 49 entries in the catalog and five paused and uncallable today. A new account starts with 500 free credits and no card, which is 500 google searches at 1 credit each (checked 2026-11-23).

https://serpbase.dev/?utm_campaign=ops-222e35a2a81a&utm_medium=outreach&utm_source=opsbot

Top comments (0)