Skip to content

Commit ad31c02

Browse files
Add async support via optional extra (#50)
* feat: add AsyncClient via optional async extra Add serpapi.AsyncClient and AsyncSerpResults, backed by httpx2 through the optional serpapi[async] extra on Python 3.11+. The synchronous Client stays on requests. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * CI: set up Python with uv in the test matrices ubuntu-latest is now Ubuntu 26.04, where actions/setup-python has no Python 3.8 or 3.9. uv downloads its own builds of every version in the matrix. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * fix: clear AsyncClient close state when the caller is cancelled Finish aclose() bookkeeping in a done callback, so a cancelled caller no longer leaves closed sessions referenced or an unretrieved task exception. Declare anyio in the test extra, since the async tests use its pytest plugin. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * docs: say AsyncClient ignores the stream option The AsyncClient method docstrings said stream is passed to the underlying HTTP request. The async transport discards it, as the user guide already states. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * test: handle shielded close errors on Python 3.14 Assert the expected background close failure and suppress only its matching event-loop diagnostic after caller cancellation. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * Fix async client request handling and response decoding Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * Preserve async session parameters and hooks Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * Fix async proxy routing and API key precedence Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * Match sync errors for invalid async redirects An invalid redirect Location now raises requests' InvalidURL, or InvalidSchema for a non-HTTP(S) scheme, instead of returning the 3xx body as results. An empty Location ends redirect handling, and followed hops no longer keep a stale next_request. Require httpx2>=2.16.1, which no longer raises from send() for these targets. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * Reuse custom async TLS contexts across pools A custom CA bundle or client certificate was loaded into a new SSL context for every pool, so rotating proxies reloaded it on the event loop, and past the 16-pool cache it was reloaded on every request. Cache contexts per verify/cert setting, up to 16, and share them across proxy and temporary pools. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * Use public httpx2 API for async auth and cap httpx2 below 3 AsyncClient called httpx2's private AsyncClient._build_request_auth to select auth once for a whole redirect chain. Select it with a helper that uses only public httpx2 API and picks the same auth as httpx2 for every auth form. Cap httpx2 below version 3 in the async and test extras, and say in the docs that the async extra installs httpx2 version 2. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent 0cf2e2f commit ad31c02

25 files changed

Lines changed: 2626 additions & 55 deletions

‎.github/workflows/ci.yml‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,14 +21,14 @@ jobs:
2121
- name: Checkout repository
2222
uses: actions/checkout@v6
2323

24-
- name: Set up Python ${{ matrix.python-version }}
25-
uses: actions/setup-python@v6
24+
- name: Set up uv with Python ${{ matrix.python-version }}
25+
uses: astral-sh/setup-uv@v7
2626
with:
2727
python-version: ${{ matrix.python-version }}
28-
28+
activate-environment: true
2929

3030
- name: Install dependencies
31-
run: pip install -e .[test]
31+
run: uv pip install -e '.[test]'
3232

3333
- name: Run tests
3434
run: pytest tests --ignore-glob='tests/test_docs_*.py' -k "not example"

‎.github/workflows/release.yml‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,12 +30,13 @@ jobs:
3030
echo "Release must run against a tag, got '${{ github.ref }}'" >&2
3131
exit 1
3232
33-
- uses: actions/setup-python@v6
33+
- uses: astral-sh/setup-uv@v7
3434
with:
3535
python-version: ${{ matrix.python-version }}
36+
activate-environment: true
3637

3738
- name: Install dependencies
38-
run: pip install -e .[test]
39+
run: uv pip install -e '.[test]'
3940

4041
- name: Run tests
4142
run: pytest --ignore=tests/test_docs_publishing.py -k "not example"

‎CONTRIBUTING.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,14 +31,16 @@ The commands below use `python` from that environment.
3131

3232
### Checks that need no API key
3333

34-
These tests cover response parsing, image uploads and extraction with simulated responses, timeouts, exceptions, documentation syntax, and the example runner:
34+
These tests cover response parsing, image uploads and extraction with simulated responses, timeouts, exceptions, the async client, documentation syntax, and the example runner:
3535

3636
```sh
37-
python -m pytest tests/test_output_formats.py tests/test_image_upload.py tests/test_extract.py tests/test_timeout.py tests/test_exceptions.py tests/test_docs_examples.py tests/test_docs_example_runner.py -k 'not live' -q
37+
python -m pytest tests/test_output_formats.py tests/test_image_upload.py tests/test_extract.py tests/test_timeout.py tests/test_exceptions.py tests/test_async_client.py tests/test_docs_examples.py tests/test_docs_example_runner.py -k 'not live' -q
3838
```
3939

4040
The file list limits this command to tests that make no external requests. Applying `-k 'not live'` to the entire suite is not enough to run offline: some SDK integration tests do not have `live` in their names.
4141

42+
The async client tests need Python 3.11 or newer, where the `test` extra installs httpx2. On older versions, pytest skips them.
43+
4244
### SDK integration tests
4345

4446
Set `API_KEY` in your shell or editor's run configuration before running integration tests. Documentation examples also accept `SERPAPI_KEY`, but the shared SDK fixtures require `API_KEY`. If you already have `SERPAPI_KEY` set, copy it to `API_KEY` in the same shell:
@@ -67,7 +69,7 @@ Both commands make real SerpApi requests. The full suite can use more searches t
6769

6870
The tests discover Python code blocks in the README and all Markdown pages under `docs/`. They run each page as a separate script against SerpApi, including the multiprocessing example's worker processes. The Lens upload examples use the repository's PNG icon as `image.png`. Each page has a five-minute limit, and HTTP errors or JSON responses containing an `error` fail the check even if the example catches the exception.
6971

70-
With `SERPAPI_KEY` or `API_KEY` set in your environment, run:
72+
With `SERPAPI_KEY` or `API_KEY` set in your environment, run the following command with Python 3.11 or newer, because the README and the async client guide use `serpapi.AsyncClient`:
7173

7274
```sh
7375
python -m pytest tests/test_docs_examples.py --require-docs-key -q

‎README.md‎

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,14 @@ To install the `serpapi` package, simply run the following command inside your P
1717
pip install serpapi
1818
```
1919

20+
To use `serpapi.AsyncClient` with `asyncio`, install the `async` extra instead. It requires Python 3.11 or later:
21+
22+
```bash
23+
pip install "serpapi[async]"
24+
```
25+
26+
Without this extra, creating an `AsyncClient` raises an `ImportError` that includes the installation command. The synchronous `Client` works without it.
27+
2028
## Quickstart
2129

2230
[Create a SerpApi account](https://serpapi.com/users/sign_up?plan=free) to get your API key, then store it in an environment variable:
@@ -82,6 +90,7 @@ A successful HTTP response can still contain an `error` field, such as when a se
8290
## Features
8391

8492
- **Asynchronous searches** for submitting jobs and retrieving completed results from the Search Archive API.
93+
- **asyncio support** with `serpapi.AsyncClient` for running searches at the same time with `await`.
8594
- **Persistent connections and connection pooling** for reusing HTTP connections across searches.
8695
- Search results as a dict-like **SerpResults** object by default, token-efficient **Markdown** with `"output": "md"`, or raw **search-engine HTML** with `"output": "html"`.
8796
- SDK methods for the [Image API](https://serpapi.com/image-api), [Location API](https://serpapi.com/locations-api), [Search Archive API](https://serpapi.com/search-archive-api), and [Account API](https://serpapi.com/account-api).
@@ -151,7 +160,7 @@ Learn more about [SerpApi Markdown Output](https://serpapi.com/markdown-output).
151160

152161
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.
153162

154-
SerpApi's `async` parameter is separate from Python `asyncio`. The SDK methods are synchronous: each call blocks until its HTTP response arrives and cannot be used with `await`.
163+
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](#async-client).
155164

156165
> **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.
157166
@@ -172,6 +181,39 @@ print(results["search_metadata"]["status"])
172181

173182
If the search is still processing, retrieve it again later. See the [async search guide](https://serpapi-python.readthedocs.io/en/latest/user_guide/async-search-archive.html) for polling with HTTP timeouts and a deadline.
174183

184+
## Async client
185+
186+
`serpapi.AsyncClient` has the same SDK methods and API parameters as `serpapi.Client`, for programs that use `asyncio`, with some [transport differences](https://serpapi-python.readthedocs.io/en/latest/user_guide/async-client.html#differences-from-client). Call its request methods with `await`. It requires Python 3.11 or later and the `async` extra:
187+
188+
```bash
189+
pip install "serpapi[async]"
190+
```
191+
192+
Run several searches at the same time with `asyncio.gather()`:
193+
194+
```python
195+
import asyncio
196+
import os
197+
198+
import serpapi
199+
200+
201+
async def main():
202+
async with serpapi.AsyncClient(api_key=os.environ["SERPAPI_KEY"], timeout=20) as client:
203+
google, bing = await asyncio.gather(
204+
client.search({"engine": "google", "q": "coffee"}),
205+
client.search({"engine": "bing", "q": "coffee"}),
206+
)
207+
208+
print("Google:", len(google.get("organic_results", [])), "results")
209+
print("Bing:", len(bing.get("organic_results", [])), "results")
210+
211+
212+
asyncio.run(main())
213+
```
214+
215+
`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](https://serpapi-python.readthedocs.io/en/latest/user_guide/async-client.html#migrating-from-sync-to-async) for a before-and-after example, or the [async client guide](https://serpapi-python.readthedocs.io/en/latest/user_guide/async-client.html) for limiting concurrent searches.
216+
175217
## Examples
176218

177219
Here are some examples of our most popular APIs. You can find the full list of supported engines and parameters in our [documentation](https://serpapi.com/search-engine-apis).

‎docs/conf.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
autodoc_default_options = {
2121
"members": True,
2222
"imported-members": True,
23-
"exclude-members": "HTTPClient, from_http_response",
23+
"exclude-members": "HTTPClient, AsyncHTTPClient, from_http_response",
2424
}
2525

2626
html_theme = "sphinx_rtd_theme"

‎docs/index.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ uv add serpapi
3535

3636
::::
3737

38-
The package requires Python 3.6 or newer.
38+
The package requires Python 3.6 or newer. To send requests with `asyncio` and `await`, install `serpapi[async]` on Python 3.11 or newer and use [`serpapi.AsyncClient`](user_guide/async-client.md).
3939

4040
## First Request
4141

@@ -95,6 +95,7 @@ Use the same search parameter names as the [SerpApi API documentation](https://s
9595
- [Parameters and Engines](user_guide/parameters-and-engines.md) explains search parameters and how to test them in the [SerpApi Playground](https://serpapi.com/playground).
9696
- For scripts that collect results, see [pagination](user_guide/pagination.md), [timeouts and errors](user_guide/errors-and-timeouts.md), [request options](user_guide/request-options.md), and [account and locations](user_guide/account-and-locations.md).
9797
- For searches you retrieve later, selected response fields, and data retention settings, see [Async Search Archive](user_guide/async-search-archive.md), [JSON Restrictor](user_guide/json-restrictor.md), and [Zero Trace](user_guide/zero-trace.md).
98+
- [Async Client](user_guide/async-client.md) covers `serpapi.AsyncClient`, which runs searches at the same time with `asyncio` and `await`.
9899
- [Examples](examples/index.md) includes searches for web pages, AI answers, local businesses, products, travel, finance, trends, jobs, media, apps, and research.
99100

100101
```{toctree}
@@ -134,6 +135,7 @@ user_guide/migrating-from-google-search-results
134135
:caption: Advanced Usage
135136
136137
user_guide/async-search-archive
138+
user_guide/async-client
137139
user_guide/threading
138140
user_guide/multiprocessing
139141
user_guide/zero-trace

‎docs/reference.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,11 @@ Look up the arguments, return values, and exceptions for the functions and class
66
.. automodule:: serpapi
77
:member-order: groupwise
88
```
9+
10+
```{eval-rst}
11+
.. automethod:: serpapi.AsyncClient.aclose
12+
.. automethod:: serpapi.SerpResults.as_dict
13+
.. autoattribute:: serpapi.SerpResults.next_page_url
14+
.. automethod:: serpapi.AsyncSerpResults.as_dict
15+
.. autoattribute:: serpapi.AsyncSerpResults.next_page_url
16+
```

0 commit comments

Comments
 (0)