SerpApi Python Client
The official Python client for SerpApi.com, allowing users to access structured search results from various engines like Google, Bing, Baidu, and more. Currently at version 1.0.2, the library is actively maintained with frequent updates and bug fixes, reflecting continuous development and responsiveness to API changes.
Warnings
- breaking The `serpapi` package (current official client) is distinct from the older `google-search-results` package, which sometimes used `from serpapi import GoogleSearch`. Code written for the legacy package will not work directly with the new `serpapi` client.
- gotcha Incorrect API key handling (hardcoding or not setting environment variable) is a common cause of `Unauthorized` (401) or `Bad Request` (400) errors.
- breaking Version 1.0.0 removed the 'redundant engine' parameter for Google searches and changed `yield_pages` to start from the first page, potentially altering expected behavior or requiring adjustments for pagination logic.
- gotcha Prior to v1.0.0, `serpapi.HTTPError` instances might have been missing essential status code and error messages, making debugging API request failures difficult.
Install
-
pip install serpapi
Imports
- Client
from serpapi import Client
- GoogleSearch
from google_search_results import GoogleSearch
Quickstart
import os
from serpapi import Client
# Ensure SERPAPI_KEY is set as an environment variable
# Example (bash): export SERPAPI_KEY='your_private_api_key'
api_key = os.environ.get('SERPAPI_KEY', '')
if not api_key:
print("Error: SERPAPI_KEY environment variable not set.")
else:
client = Client(api_key=api_key)
try:
results = client.search({
"engine": "google",
"q": "Coffee",
"location": "Austin, Texas, United States",
"hl": "en",
"gl": "us"
})
print(results.get("organic_results", [])[0].get("title"))
except Exception as e:
print(f"An error occurred: {e}")