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
Install
pip install requestsKeep the key out of your code
Create a key in the dashboard and export it as an environment variable.
Shellexport BESTSERP_API_KEY=bsa_your_keySearch 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.pyimport 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"])Other result types
Change the endpoint and read the matching list: images, news, videos, shopping or places (for both /places and /maps).
Pythonnews = 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"]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
| Status | Code | Meaning | Credits |
|---|---|---|---|
| 202 | - | Not finished within timeout (or async: true). Poll pollUrl. | Reserved |
| 400 | invalid_request | Malformed body or a parameter out of range. | No |
| 400 | unknown_parameter | A field the API does not know (typo?). | No |
| 400 | unsupported_parameter | A known field that this endpoint does not support yet (e.g. location). | No |
| 401 | missing_api_key / invalid_api_key | No key, or the key is wrong or revoked. | No |
| 402 | insufficient_credits | Your balance is too low for this request. | No |
| 403 | account_suspended | The account is suspended. | No |
| 404 | not_found | Unknown requestId, or it belongs to another account. | - |
| 429 | rate_limited | Too many requests this minute. See Retry-After. | No |
| 502 | search_failed | The search could not be completed (blocked or timed out). | Refunded |
| 503 | busy | No capacity right now. Retry after Retry-After seconds. | Refunded |
Frequently asked questions
Is there an official Python SDK?
Can I use httpx or aiohttp for async code?
Why do I sometimes get 202?
How do I avoid paying twice for the same query?
Start with 3,000 free searches
No credit card. Sign in with Google, create a key, send your first request.