DEV Community

Mastel
Mastel

Posted on

Your first SERP API call: get a key and fetch Google results as JSON (curl, Python, Node)

If you want Google search results inside a script, scraping HTML directly is the slow way to learn about CAPTCHAs and broken CSS selectors. A cleaner starting point is to grab a serp api key and call a JSON search endpoint.

Below is the shortest path from getting a key to printing structured organic results in curl, Python, and Node.js, plus the small environment-variable habits that keep keys out of your git history.

1. Put the key in an environment variable first

Before writing any request code, store your key in an env var instead of pasting it into a source file.

macOS / Linux:

export SERPBASE_API_KEY="your_api_key_here"
Enter fullscreen mode Exit fullscreen mode

Windows (PowerShell):

$env:SERPBASE_API_KEY = "your_api_key_here"
Enter fullscreen mode Exit fullscreen mode

If you use a local .env file during development, add .env to .gitignore immediately. Two extra rules worth following:

  • Send the key in the X-API-Key header, never in the URL. Putting a key in a query string (?api_key=...) leaks it into proxy logs, reverse-proxy access logs, and browser history. SerpBase refuses keys in URL query parameters for this exact reason.
  • Create separate keys per environment (local dev vs. production). If a laptop or CI log leaks a key, you can revoke that one key without breaking production.

You can check that your key works without spending any search credits by calling /account/credits:

curl -s "https://api.serpbase.dev/account/credits" \
  -H "X-API-Key: $SERPBASE_API_KEY"
Enter fullscreen mode Exit fullscreen mode

2. Fetch Google results as JSON

All three examples below hit POST https://api.serpbase.dev/google/search with a JSON body (q, gl, hl) and read organic[].

curl

curl -s -X POST "https://api.serpbase.dev/google/search" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: $SERPBASE_API_KEY" \
  -d '{
    "q": "python asyncio tutorial",
    "gl": "us",
    "hl": "en"
  }' | jq '.organic[:5] | map({position, title, link})'
Enter fullscreen mode Exit fullscreen mode

Python (requests)

import os
import requests

resp = requests.post(
    "https://api.serpbase.dev/google/search",
    headers={
        "X-API-Key": os.environ["SERPBASE_API_KEY"],
        "Content-Type": "application/json",
    },
    json={
        "q": "python asyncio tutorial",
        "gl": "us",
        "hl": "en",
    },
    timeout=30,
)
resp.raise_for_status()
data = resp.json()

if data.get("status") != 0:
    raise RuntimeError(
        f"API error status={data.get('status')} request_id={data.get('request_id')}"
    )

for item in data.get("organic", [])[:5]:
    print(f"#{item['position']} {item['title']}\n   {item['link']}")
Enter fullscreen mode Exit fullscreen mode

Node.js (built-in fetch, Node 18+)

const res = await fetch("https://api.serpbase.dev/google/search", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "X-API-Key": process.env.SERPBASE_API_KEY,
  },
  body: JSON.stringify({
    q: "python asyncio tutorial",
    gl: "us",
    hl: "en",
  }),
});

if (!res.ok) {
  throw new Error(`HTTP ${res.status}`);
}

const data = await res.json();
if (data.status !== 0) {
  throw new Error(`API error status=${data.status} id=${data.request_id}`);
}

for (const item of (data.organic ?? []).slice(0, 5)) {
  console.log(`#${item.position} ${item.title}\n   ${item.link}`);
}
Enter fullscreen mode Exit fullscreen mode

3. What to check in the response

  • status: 0 means success. Always check data.status === 0 even when the HTTP status is 200. If you hit your rate limit, the API returns status: 1029 along with a Retry-After header and does not charge credits.
  • organic: array of organic search results (position, rank, title, link, snippet, and date when Google displays one).
  • X-RateLimit-Limit / X-RateLimit-Remaining: returned on every response so your worker can pace requests cleanly instead of guessing.

Full details on creating, renaming, and revoking keys—plus QPS tiers and rate-limit headers—are in the SerpBase API keys & rate limits docs. Full disclosure: I work on SerpBase; new accounts start with 500 free credits so you can test all three snippets above right away.

Top comments (2)

Collapse
 
shivam_e4e7992c2aaa237191 profile image
Shivam •

Honestly, this is the kind of tutorial I prefer. Straight to the point, actual working examples im multiple languages, and swcurity tips included instead of being an afterthought.

One thing I'd be curious about is how SerpBase handles Google result changes and inconsistent responses. That's usually where these APIs become interesting in real-world projects, not just in the first successful API call. 😁

Collapse
 
mastel_liggin_c1ae9b6af78 profile image
Mastel •

Glad you liked it! Security stuff usually gets skipped in quickstarts, so I wanted to put it right up front.

Yeah, that's the real pain with Google. They tweak layouts constantly, so we handle it on a few layers. On /google/search, the top-level fields (status, request_id, credits_charged) stay the same, and optional modules like ai_overview or people_also_ask just get omitted when Google doesn't show them. Checking status === 0 first and reading fields defensively (like data.organic ?? []) handles most of the day-to-day drift.

When Google throws a block, an empty page, or a weird layout, SerpBase retries upstream automatically (within a 30s cap). If it still can't get a clean parse, it returns a 1500-1504 error with X-SerpBase-Retryable: true instead of handing back broken JSON, and failed calls are auto-refunded so your own retry loop won't waste credits.

If Google rolls out something brand new and you want to see what actually came back, you can also pass "format": "raw" to grab the cleaned HTML directly.