Google Search API Tutorial in Python: Requests and Results
Senior Web Scraping Engineer
TL;DR:
- Scrapeless Google Search API returns structured search data to Python. Submit
q,gl, andhlin an authenticated JSON request. - HTTP 200 and HTTP 201 require different handling. Read a completed result directly; retain a pending task ID and retrieve that existing task.
- A successful HTTP response still needs a data check. Validate
organic_resultsbefore using the rows. - Preserving the response makes later analysis easier. Save the JSON before selecting titles, snippets, or links.
Introduction: Make a Search Result Usable in Python
A search request is only useful to an application when the application can distinguish completed data from a task that is still running. A quick script that prints response.text gets you started, but it leaves those states mixed together.
This Google Search API Python tutorial builds a small client for Scrapeless Google Search API. You will configure a query, submit it, handle a pending task, and save a response that another script can inspect. The example uses ordinary web search. Images, Local, Videos, and Shopping have different result sections and need their own validation.
The code talks to Scrapeless; it is not Google's Custom Search JSON API or Search Console API. Your application receives a search snapshot rather than your site's traffic reports. If you already work with the broader Scrapeless actor request model, the request envelope will look familiar.
Prerequisites
You need Python, the requests package, and a Scrapeless API key with access to the service. Use a virtual environment for the project and install Requests with python -m pip install requests. Set SCRAPELESS_API_KEY in your process environment before running the script. Keep the key out of source files, notebooks that you share, and response logs.
The local environment variable is a convention chosen for this script. The HTTP authentication header is x-api-token. They have different jobs: Python reads the variable, then sends its value in the header to the API endpoint.
Save the complete program below as google_search.py and run it with python google_search.py. The program creates serp.json in the working directory. Use a separate directory for each experiment if you want to preserve previous responses.
Configure q, gl, and hl
The q parameter supplies the search query, gl selects the search country, and hl selects the search language. These controls belong inside input, alongside the actor name in the surrounding request object.
| Field | Example | What to Check |
|---|---|---|
actor |
scraper.google.search |
Keep the actor at the top level |
input.q |
coffee |
Preserve the exact query you intend to compare |
input.gl |
us |
Record the requested country with the result |
input.hl |
en |
Record the requested language separately |
Start with this small input. Adding location and search filters immediately makes it harder to identify which parameter changed an output. Keep the current Google Search parameters available when you expand the request.
Send the body with Requests' json= argument. It serializes the Python object as JSON and sets the appropriate content type. JSON objects and arrays are distinct structures in the JSON data format; a response that parses successfully is not automatically the object shape your application expects.
Send a Request and Retrieve a Pending Task
The client submits one search task, then checks the result endpoint only if that task is still being processed. A completed response is returned to the caller as a Python dictionary.
The Google Search quickstart uses POST /api/v1/scraper/request. For this API, HTTP 201 means processing is in progress and includes taskId. The task result workflow retrieves that ID with GET /api/v1/scraper/result/{taskId}.
This is an application-specific interpretation of the status code. The general HTTP semantics specification defines status classes, while the service contract tells your client how to handle a pending task.
The program limits result checks to ten, with a two-second interval. Those are example client settings, not service limits or a promised completion time. Network timeouts apply separately to each request. If the task remains pending, the exception includes its ID so an operator can retain it.
python
import json
import os
import time
from pathlib import Path
from urllib.parse import quote
import requests
BASE = "https://api.scrapeless.com/api/v1/scraper"
def google_search(query):
headers = {"x-api-token": os.environ["SCRAPELESS_API_KEY"]}
response = requests.post(
BASE + "/request", headers=headers,
json={"actor": "scraper.google.search", "input": query},
timeout=(10, 60), allow_redirects=False,
)
task_id = None
for poll in range(11):
response.raise_for_status()
if response.status_code not in (200, 201):
raise RuntimeError(f"Unexpected HTTP status: {response.status_code}")
data = response.json()
if not isinstance(data, dict):
raise ValueError("Expected a JSON object")
if response.status_code == 200:
return data
if task_id is None:
task_id = data.get("taskId")
if not isinstance(task_id, str) or not task_id:
raise ValueError("Pending response has no taskId")
if poll == 10:
raise TimeoutError(f"Task still pending; retain taskId={task_id}")
time.sleep(2)
response = requests.get(
BASE + "/result/" + quote(task_id, safe=""),
headers=headers, timeout=(10, 30), allow_redirects=False,
)
def organic_rows(data):
rows = data.get("organic_results")
if not isinstance(rows, list):
raise ValueError("organic_results is missing or is not an array")
if not all(isinstance(row, dict) for row in rows):
raise ValueError("organic_results contains a non-object item")
return rows
if __name__ == "__main__":
query = {"q": "coffee", "gl": "us", "hl": "en"}
try:
result = google_search(query)
Path("serp.json").write_text(
json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8"
)
rows = organic_rows(result)
print(f"Saved serp.json; organic rows: {len(rows)}")
for row in rows:
print(row.get("position"), row.get("title"), row.get("link"))
except requests.HTTPError as exc:
raise SystemExit(f"HTTP request failed: {exc.response.status_code}")
except requests.RequestException:
raise SystemExit("Network request did not complete")
except (ValueError, RuntimeError, TimeoutError, KeyError) as exc:
raise SystemExit(str(exc))
The first raise_for_status() catches HTTP error responses. The explicit status check also rejects unexpected non-error statuses. Parsing JSON comes after those checks, and the result validator runs after the API says the task is complete. Each stage answers a different question.
Start Scraping with Scrapeless
Power up your web scraping and automation workflow with Scrapeless!
Sign up today and get $5 in free credit — no credit card required.Claim your free credit now in the Scrapeless Dashboard.
Read organic_results Without Losing the Original Response
The organic_results array contains the organic result records in the completed response. Read fields such as position, title, snippet, and link from each record, while retaining the original object for inspection.
The baseline coffee request used while preparing this tutorial returned HTTP 200 and eight organic records with gl=us and hl=en. That count describes one response. A later request for the same query can contain a different number of rows or a different arrangement of search features.
The program saves the JSON before validating the organic array. This matters when a completed response has an unexpected shape: you can inspect what arrived instead of losing it when validation raises an exception. Python's JSON encoding and decoding interface supports keeping non-ASCII text readable through ensure_ascii=False.
Treat three cases separately. An empty array is an observed collection with no organic items. An absent key has no such guarantee. A value of the wrong type is a schema problem. The script accepts the first case and stops on the other two rather than silently replacing them with an empty list.
Returned links also need context. A direct-looking URL is a destination candidate; a Google intermediary requires further handling before you treat it as a target website. This first tutorial prints the returned value without claiming that the final destination was verified.
Handle Failures at the Right Layer
An exception should identify the failed stage without exposing the authentication header or turning a failed request into a valid-looking empty result.
| Observation | Meaning for This Client | Next Inspection |
|---|---|---|
| Missing environment variable | Authentication was not configured locally | Check the process environment |
| HTTP 400 | The API rejected the request | Check input names, types, and combinations |
| HTTP 429 | The service reports a request limit | Check request frequency and account quota |
| Other HTTP error | No completed result was accepted | Keep status and request context for investigation |
| Invalid JSON | The body could not be parsed | Inspect the response in a controlled diagnostic log |
| Missing organic array | The payload does not match this consumer | Inspect the saved JSON and requested search mode |
| Pending-task limit reached | Completion was not observed by this client | Retain the task ID and mark the job incomplete |
The sample deliberately avoids printing whole request headers or server error bodies. In a larger service, write structured diagnostics with the query configuration, status, and task ID when available. Record a failed run separately from completed observations so downstream reports cannot mistake failure for absence.
Conclusion: Keep the First Client Small
A useful Google Search API Python client has a clear path: submit a query, retrieve the existing task if necessary, preserve the response, and validate the fields your application consumes. Once that path works, add one input dimension at a time.
Use the Google Search API product details to choose the service and the current pricing to plan repeated collection. Keep request configuration beside every saved response before building a larger dataset.
Build Your Search Data Workflow
Join developers working with search data in our community: Discord · Telegram.
Create a Scrapeless account and apply this tutorial to a small query set before scheduling a larger collection.
FAQ
Q: Can Python call Google Search API without an SDK?
Yes. The example uses Requests and the documented HTTP endpoint. It does not require an AI agent or a framework-specific SDK.
Q: Does HTTP 201 contain the final search result?
For this API, HTTP 201 indicates a pending task. Retain taskId and retrieve that task through the result endpoint.
Q: Does gl=us prove that every result is American?
No. The country is a search input, not a nationality label for every returned page. Local accuracy needs a separate validation method.
Q: Should an absent organic_results key become an empty list?
No. An absent key and an explicitly empty array are different observations. Check the response shape before reporting that no organic records were returned.
Q: Do you need to configure a separate proxy?
This basic request needs no separate proxy configuration. The API handles retrieval; consult the parameter contract before adding transport or location settings.
Q: Does the script verify the content behind every result link?
No. It collects a search snapshot. Destination verification and page-content validation are separate steps.
At Scrapeless, we only access publicly available data while strictly complying with applicable laws, regulations, and website privacy policies. The content in this blog is for demonstration purposes only and does not involve any illegal or infringing activities. We make no guarantees and disclaim all liability for the use of information from this blog or third-party links. Before engaging in any scraping activities, consult your legal advisor and review the target website's terms of service or obtain the necessary permissions.



