Skip to main content

SerpApi Python Library

Package serpapi-python

Integrate search data into your AI workflow, RAG / fine-tuning, or Python application using this official SerpApi Python SDK.

SerpApi supports Google, Google Maps, Google Shopping, Baidu, Yandex, Yahoo, eBay, app stores, and more.

See the full Python SDK documentation for setup, usage guides, and API reference.

Installation

Python 3.6 or later is required.

To install the serpapi package, simply run the following command inside your Python virtual environment:

pip install serpapi

To use serpapi.AsyncClient with asyncio, install the async extra instead. It requires Python 3.11 or later:

pip install "serpapi[async]"

Without this extra, creating an AsyncClient raises an ImportError that includes the installation command. The synchronous Client works without it.

Quickstart

Create a SerpApi account to get your API key, then store it in an environment variable:

export SERPAPI_KEY="your_api_key"

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:

import os

import serpapi

client = serpapi.Client(api_key=os.environ["SERPAPI_KEY"])
results = client.search({
    "engine": "google",
    "q": "coffee"
})

print(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".
  • SDK methods for the Image API, Location API, Search Archive API, and Account API.
  • 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.

Response formats

Output Use it for Returns
json (default) Reading fields, filtering, or storing results Dict-like SerpResults
md Passing content directly to an LLM Markdown str
html Inspecting or processing raw HTML HTML str

Omit output or set output="json" for JSON:

results = client.search({
    "engine": "google",
    "q": "coffee"
})

Use results.as_dict() when another library needs a plain dict, including before calling json.dumps():

data = results.as_dict()

Set output="md" for Markdown:

markdown = client.search({
    "engine": "google",
    "q": "coffee",
    "output": "md"
})

Set output="html" for HTML:

raw_html = client.search({
    "engine": "google",
    "q": "coffee",
    "output": "html"
})

Archived results are also available as Markdown with client.search_archive(search_id=search_id, output="md").

Learn more about SerpApi Markdown Output.

Configuration

Option Default Description
api_key None Your SerpApi API key.
timeout None 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():

import asyncio
import os

import serpapi


async def main():
    async with serpapi.AsyncClient(api_key=os.environ["SERPAPI_KEY"], timeout=20) as client:
        google, bing = await asyncio.gather(
            client.search({"engine": "google", "q": "coffee"}),
            client.search({"engine": "bing", "q": "coffee"}),
        )

    print("Google:", len(google.get("organic_results", [])), "results")
    print("Bing:", len(bing.get("organic_results", [])), "results")


asyncio.run(main())

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.

import os

import serpapi

client = serpapi.Client(api_key=os.environ["SERPAPI_KEY"])
results = client.search({
    "engine": "google_shopping",
    "q": "Macbook M4"
})
shopping_results = results["shopping_results"]
print(shopping_results)

See documentation

Google Shopping Light

A light variant engine called google_shopping_light is also available for faster, lower-cost shopping searches.

Google Images

Scrape Google Images search results, including image URLs, thumbnails, titles, and source pages.

import os

import serpapi

client = serpapi.Client(api_key=os.environ["SERPAPI_KEY"])
results = client.search({
    "engine": "google_images",
    "q": "coffee",
})
print(results)

See documentation

Google Images Light

A light variant engine called google_images_light is also available for faster, lower-cost image searches.

Extract API

Extract page content from a public URL as Markdown for an LLM:

import os

import serpapi

client = serpapi.Client(api_key=os.environ["SERPAPI_KEY"], timeout=60)
markdown = client.extract(url="https://serpapi.com/", output="md")
print(markdown)

Omit output or set output="json" for a dict-like SerpResults object with structured page data and Markdown. Use output="html" for HTML as a string.

For URL discovery and crawling, see Map Mode and Crawl Mode in the Python guide.

See documentation

Google Lens with image URL or upload

Google Lens accepts either a publicly accessible image URL or an uploaded image. To search by URL, pass the URL directly:

import os

import serpapi

client = serpapi.Client(api_key=os.environ["SERPAPI_KEY"])
results = client.search({
    "engine": "google_lens",
    "url": "https://i.imgur.com/HBrB8p0.png",
})
print(results)

To search a local image, place a file named image.png in your working directory, upload it, and pass its temporary image_id to Google Lens:

upload = client.upload_image("image.png")
results = client.search({
    "engine": "google_lens",
    "image_id": upload["image_id"],
})

Uploaded images can be JPG/JPEG, PNG, or WebP files up to 500 KB. The returned image_id expires after 10 minutes.

See Image API documentation · See Google Lens image upload documentation

Track search interest over time and compare the popularity of search terms.

import os

import serpapi

client = serpapi.Client(api_key=os.environ["SERPAPI_KEY"])
results = client.search({
    "engine": "google_trends",
    "q": "coffee",
    "data_type": "TIMESERIES"
})
interest_over_time = results["interest_over_time"]
print(interest_over_time)

See documentation

Google Flights

Search flight routes, schedules, prices, and booking options.

Note: The google_flights engine does not use q. Specify route and date parameters such as departure_id, arrival_id, outbound_date, and return_date.

import os
from datetime import date, timedelta

import serpapi

client = serpapi.Client(api_key=os.environ["SERPAPI_KEY"])
outbounding = date.today() + timedelta(days=30)
returning = outbounding + timedelta(weeks=2)

results = client.search({
    "engine": "google_flights",
    "departure_id": "LAX",
    "arrival_id": "AUS",
    "outbound_date": outbounding.isoformat(),
    "return_date": returning.isoformat()
})
flights = results.get("best_flights") or results.get("other_flights", [])
print(flights)

See documentation

Google AI Mode API

The Google AI Mode API returns AI-generated answers with structured text blocks, references, images, products, and more.

import os

import serpapi

client = serpapi.Client(api_key=os.environ["SERPAPI_KEY"])
results = client.search({
    "engine": "google_ai_mode",
    "q": "best coffee maker"
})
text_blocks = results["text_blocks"]
print(text_blocks)

See documentation

Scrape Bing web search results, including organic results, ads, related searches, and more.

import os

import serpapi

client = serpapi.Client(api_key=os.environ["SERPAPI_KEY"])
results = client.search({
    "engine": "bing",
    "q": "coffee"
})
print(results)

See documentation

Scrape DuckDuckGo search results, including organic results, ads, knowledge graphs, and related searches.

import os

import serpapi

client = serpapi.Client(api_key=os.environ["SERPAPI_KEY"])
results = client.search({
    "engine": "duckduckgo",
    "q": "coffee",
})
print(results)

See documentation

Scrape Baidu search results, including organic results, answer boxes, and related searches.

import os

import serpapi

client = serpapi.Client(api_key=os.environ["SERPAPI_KEY"])
results = client.search({
    "engine": "baidu",
    "q": "coffee",
})
print(results)

See documentation

Scrape Amazon product search results, including product names, prices, ratings, reviews, and availability.

Note: The amazon engine uses the k parameter for a keyword search, not q.

import os

import serpapi

client = serpapi.Client(api_key=os.environ["SERPAPI_KEY"])
results = client.search({
    "engine": "amazon",
    "k": "Coffee",
    "amazon_domain": "amazon.com"
})
organic_results = results["organic_results"]
print(organic_results)

See documentation

More resources

Playground

Build and test your request in the Playground, then generate Python code.

For agents

License

MIT License.

Contributing

Contributions are welcome. Make sure to read our contributing guide.

© 2026 SerpApi

Metadata

Release files for serpapi 1.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for serpapi 1.3.0
File Size Uploaded Provenance Actions
serpapi-1.3.0.tar.gz 109.5 kB With provenance Details for serpapi-1.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for serpapi 1.3.0
File Interpreter ABI Platform Actions
serpapi-1.3.0-py3-none-any.whl Python 3 none any Details for serpapi-1.3.0-py3-none-any.whl

Total release size: 131.2 kB

Release files / serpapi-1.3.0.tar.gz

Download URL serpapi-1.3.0.tar.gz
Size 109.5 kB
Tags Source
SHA-256 checksum
How to use checksums
4346639000d2cbd97ec6b2538ab74cc66a794f62e51763640c2d487d4950302f
BLAKE2b-256 checksum
How to use checksums
f2d1b0d351519bb4f110acf558d7b83d8711000bcab6cc7977f03ecb27b92ee4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 25, 2026.

Transparency log

Release files / serpapi-1.3.0-py3-none-any.whl

Download URL serpapi-1.3.0-py3-none-any.whl
Size 21.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
814f74443676fffb88ca3312f321aebd4691e1d71d2e20c47e7d29fb2abfd5fa
BLAKE2b-256 checksum
How to use checksums
90186f479f64b79c3d9c5c3ab2dc143357a779dd1ce4a2ea6bf8fb73a9dffa30
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 25, 2026.

Transparency log

Security for serpapi 1.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for serpapi-1.3.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 25, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page