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 (0)