Launch pricing: 78% of pool capacity allocated. Rates rise as it fills. Lock in today's rate →
Skip to content

How to use a Google Search API in Python (with full code)

By SerpWiz · · 3 min read

This guide gets live Google results into Python in a few minutes, then builds it into something you can run in production: paging, retries, CSV export and Google Maps. It uses the SerpWiz Google Search API and the requests library.

1. Get an API key

Create a free account (1,000 free queries a month, no card), then create a key under API keys in the dashboard. Keep it out of your code:

pip install requests
export SERPWIZ_API_KEY="sw_live_..."

2. Your first search

import os
import requests

r = requests.get(
    "https://api.serpwiz.com/v1/google/search",
    params={"q": "best crm for startups", "gl": "us", "hl": "en"},
    headers={"X-API-Key": os.environ["SERPWIZ_API_KEY"]},
    timeout=60,
)
r.raise_for_status()
for result in r.json()["results"]:
    print(result["position"], result["title"], result["url"])

Each search returns one page of Google: up to 10 organic results, plus ads, top_stories, knowledge_panel and related_keywords. gl sets the country and hl the language.

3. A reusable function with retries

Searches occasionally fail for a moment. Failed requests are free, so just retry them. The API sends a Retry-After header with 429, 502 and 503 responses:

import os
import time
import requests

API = "https://api.serpwiz.com/v1"
KEY = os.environ["SERPWIZ_API_KEY"]

def search(q, page=1, gl="us", hl="en", attempts=3):
    for _ in range(attempts):
        r = requests.get(f"{API}/google/search",
                         params={"q": q, "page": page, "gl": gl, "hl": hl},
                         headers={"X-API-Key": KEY}, timeout=60)
        if r.status_code in (429, 502, 503):
            time.sleep(int(r.headers.get("Retry-After", "1")))
            continue
        if not r.ok:
            raise RuntimeError(r.json()["error"]["message"])
        return r.json()
    raise RuntimeError(f"Gave up after {attempts} attempts")

4. Page through the top 100

Google shows 10 results per page, so the top 100 takes up to 10 requests. Stop early when there's no next page:

def top_results(q, pages=10, **kw):
    rows = []
    for page in range(1, pages + 1):
        data = search(q, page=page, **kw)
        for x in data["results"]:
            rows.append({"rank": len(rows) + 1, "title": x["title"], "url": x["url"], "snippet": x.get("description", "")})
        if not data.get("next_page"):
            break
    return rows

5. Save to CSV

import csv

rows = top_results("best crm for startups", pages=3)
with open("results.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.DictWriter(f, fieldnames=["rank", "title", "url", "snippet"])
    writer.writeheader()
    writer.writerows(rows)
print(f"Saved {len(rows)} results")

6. Find where a site ranks

from urllib.parse import urlparse

def rank_of(domain, q, **kw):
    for row in top_results(q, **kw):
        host = urlparse(row["url"]).hostname or ""
        if host == domain or host.endswith("." + domain):
            return row["rank"]
    return None

print(rank_of("hubspot.com", "best crm for startups"))

For a quick check without code, try the free Google rank checker.

7. Google Maps places

The same key works for the Google Maps API, which returns up to 200 places per search with address, phone, website, rating and hours:

r = requests.get(f"{API}/google/maps",
                 params={"q": "dentists in Miami", "num": 20},
                 headers={"X-API-Key": KEY}, timeout=60)
for p in r.json()["results"]:
    print(p["title"], p.get("phone"), p.get("rating"), p.get("website"))

What it costs

Every search above is 1 query: $0.15 per 1,000 on monthly plans, $0.1125 with a year prepaid. Checking the top 100 for 1,000 keywords once costs at most 10,000 queries, $10 on the smallest plan. Failed requests are never charged.

Next: the API reference for every parameter, or Node.js and PHP versions of this guide.

More from the blog

This post as Markdown: /blog/google-search-api-python.md