Google SERP API in Python

To get Google results in Python, POST a JSON body with your query to a BestSERP endpoint such as /search using the requests library, with your API key in the X-API-KEY header. The response is JSON: read organic for web results. If it answers 202, poll /requests/{requestId} until the result is ready.

Last updated:

Key takeaways

  • No SDK to install: Python's standard HTTP client is enough.
  • Send the key in the X-API-KEY header, never in a URL or in browser code.
  • 202 means the search is still running: poll GET /requests/{requestId}.
  • 60 searches per minute per account by default; 429 and 503 are not charged.

Step by step

  1. Install

    pip install requests
  2. Keep the key out of your code

    Create a key in the dashboard and export it as an environment variable.

    Shell
    export BESTSERP_API_KEY=bsa_your_key
  3. Search and wait for the result

    This function handles the three outcomes: 200 with results, 202 while the search is still running, and an error with its code.

    search.py
    import os
    import time
    
    import requests
    
    API = "https://api.bestserp.com"
    HEADERS = {"X-API-KEY": os.environ["BESTSERP_API_KEY"]}
    
    
    class SearchError(Exception):
        pass
    
    
    def search(endpoint: str = "search", **body) -> dict:
        r = requests.post(f"{API}/{endpoint}", headers=HEADERS, json={"timeout": 120, **body}, timeout=130)
        while r.status_code == 202:  # still running: poll the request
            time.sleep(2)
            r = requests.get(f"{API}/requests/{r.json()['requestId']}", headers=HEADERS, timeout=30)
        if r.status_code != 200:
            error = r.json().get("error", {})
            raise SearchError(f"{r.status_code} {error.get('code')}: {error.get('message')}")
        return r.json()
    
    
    if __name__ == "__main__":
        data = search("search", q="best running shoes", gl="us", hl="en")
        for item in data.get("organic", []):
            print(item["position"], item["title"], item["link"])
        print("credits used:", data["credits"])
  4. Other result types

    Change the endpoint and read the matching list: images, news, videos, shopping or places (for both /places and /maps).

    Python
    news = search("news", q="electric vehicles", gl="gb", hl="en", tbs="qdr:d")["news"]
    products = search("shopping", q="mechanical keyboard", gl="us")["shopping"]
    places = search("maps", q="pho restaurant hanoi", gl="vn", hl="vi")["places"]
  5. Retry what is worth retrying

    Retry 429 (rate limited) and 503 (busy) after the Retry-After header; those searches are not charged. Fix 400 and 401 errors in your request instead of retrying.

Status codes to handle

What the search endpoints answer, and whether the request costs credits.
StatusCodeMeaningCredits
202-Not finished within timeout (or async: true). Poll pollUrl.Reserved
400invalid_requestMalformed body or a parameter out of range.No
400unknown_parameterA field the API does not know (typo?).No
400unsupported_parameterA known field that this endpoint does not support yet (e.g. location).No
401missing_api_key / invalid_api_keyNo key, or the key is wrong or revoked.No
402insufficient_creditsYour balance is too low for this request.No
403account_suspendedThe account is suspended.No
404not_foundUnknown requestId, or it belongs to another account.-
429rate_limitedToo many requests this minute. See Retry-After.No
502search_failedThe search could not be completed (blocked or timed out).Refunded
503busyNo capacity right now. Retry after Retry-After seconds.Refunded

Frequently asked questions

Is there an official Python SDK?
Not yet. The API is plain HTTPS and JSON, so requests or httpx is all you need; the function on this page covers waiting and errors.
Can I use httpx or aiohttp for async code?
Yes. Send the same POST with any HTTP client. For many searches in parallel, keep under your rate limit (60 per minute by default).
Why do I sometimes get 202?
The search took longer than the timeout you set (60 seconds by default, up to 120). Poll GET /requests/{requestId} until it returns 200.
How do I avoid paying twice for the same query?
Identical requests within an hour (5 minutes for news) may be served from cache, at the normal price. Cache results on your side if you reuse them often.

Start with 3,000 free searches

No credit card. Sign in with Google, create a key, send your first request.