Environment variables keep secrets out of your source code. Read the API key with os.environ["SERPAPI_KEY"]. Python raises KeyError if the variable is missing.
Run a Google search and access the structured results:
The results variable contains a dict-like SerpResults object. Read fields with results["organic_results"] or .
results.get("organic_results", [])
This example runs a search for "coffee" on Google. See the Playground to generate your own code.
For Windows setup and instructions to save and run the example, see the getting-started guide.
Error handling
HTTP failures raise serpapi.HTTPError. Connection failures raise serpapi.HTTPConnectionError, and read timeouts raise serpapi.TimeoutError. See the status and error codes documentation for the meaning of each HTTP status.
import os
import serpapi
# A default timeout can be set here.
client = serpapi.Client(api_key=os.environ["SERPAPI_KEY"], timeout=10)
try:
results = client.search({
"engine": "google",
"q": "coffee",
})
except serpapi.TimeoutError:
raise RuntimeError("The request timed out.") from None
except serpapi.HTTPConnectionError:
raise RuntimeError("Could not connect to SerpApi.") from None
except serpapi.HTTPError as e:
raise RuntimeError(f"HTTP {e.status_code}: {e.error or 'Request failed'}") from None
if "error" in results:
raise RuntimeError(results["error"])
A successful HTTP response can still contain an error field, such as when a search returns no results. Check it before reading result fields. See Errors and timeouts for more examples.
Features
Asynchronous searches for submitting jobs and retrieving completed results from the Search Archive API.
asyncio support with serpapi.AsyncClient for running searches at the same time with await.
Persistent connections and connection pooling for reusing HTTP connections across searches.
Search results as a dict-like SerpResults object by default, token-efficient Markdown with "output": "md", or raw search-engine HTML with "output": "html".
Content extraction with client.extract() for reading pages, discovering URLs, and crawling websites.
Configurable HTTP timeouts established by setting timeout in the client.
Migrating from google-search-results
If you use the legacy google-search-results package, follow the migration guide to update your code. Both packages use import serpapi, so install only one in your environment.
Connection and read timeout in seconds. No timeout is set by default.
Asynchronous searches
Searches wait for their results by default. Use {"async": True} to submit a search job on SerpApi and retrieve its results later from the Search Archive API.
SerpApi's async parameter is separate from Python asyncio. serpapi.Client methods are synchronous: each call blocks until its HTTP response arrives. To use await, see Async client.
Note:async is a reserved keyword in Python 3.7+, so pass it inside the parameters dictionary ({"async": True}) rather than as a keyword argument.
Submit a search and check its status later:
submitted = client.search({
"engine": "google",
"q": "coffee",
"async": True,
})
search_id = submitted["search_metadata"]["id"]
# Retrieve later; the search may still be processing.
results = client.search_archive(search_id=search_id)
print(results["search_metadata"]["status"])
If the search is still processing, retrieve it again later. See the async search guide for polling with HTTP timeouts and a deadline.
Async client
serpapi.AsyncClient has the same SDK methods and API parameters as serpapi.Client, for programs that use asyncio, with some transport differences. Call its request methods with await. It requires Python 3.11 or later and the async extra:
pip install "serpapi[async]"
Run several searches at the same time with asyncio.gather():
asyncio.gather() returns the results in the order of the searches. async with closes the client's connections when the block ends. To fetch more pages, use await results.next_page() or async for page in results.yield_pages(). See Migrating from Sync to Async for a before-and-after example, or the async client guide for limiting concurrent searches.
Examples
Here are some examples of our most popular APIs. You can find the full list of supported engines and parameters in our documentation.
Google Shopping
Scrape Google Shopping results with product names, prices, ratings, and merchant information.