From 81bd7cb0e2deb74fb194d13c3560a936fd1989eb Mon Sep 17 00:00:00 2001 From: Kayvan Zahiri <123409429+Kayvan-Zahiri@users.noreply.github.com> Date: Sun, 18 Oct 2026 10:48:31 -0700 Subject: [PATCH 1/2] Preserve caller parameters and per-client API keys --- serpapi/core.py | 12 ++---- serpapi/http.py | 3 ++ tests/test_parameter_reuse.py | 79 +++++++++++++++++++++++++++++++++++ 3 files changed, 86 insertions(+), 8 deletions(-) create mode 100644 tests/test_parameter_reuse.py diff --git a/serpapi/core.py b/serpapi/core.py index f24e089..be245f3 100644 --- a/serpapi/core.py +++ b/serpapi/core.py @@ -39,8 +39,7 @@ def search(self, params: dict = None, **kwargs): **Learn more**: https://serpapi.com/search-api """ - if params is None: - params = {} + params = dict(params) if params is not None else {} # These are arguments that should be passed to the underlying requests.request call. request_kwargs = {} @@ -63,8 +62,7 @@ def search_archive(self, params: dict = None, **kwargs): **Learn more**: https://serpapi.com/search-archive-api """ - if params is None: - params = {} + params = dict(params) if params is not None else {} # These are arguments that should be passed to the underlying requests.request call. request_kwargs = {} @@ -141,8 +139,7 @@ def locations(self, params: dict = None, **kwargs): **Learn more**: https://serpapi.com/locations-api """ - if params is None: - params = {} + params = dict(params) if params is not None else {} # These are arguments that should be passed to the underlying requests.request call. request_kwargs = {} @@ -171,8 +168,7 @@ def account(self, params: dict = None, **kwargs): **Learn more**: https://serpapi.com/account-api """ - if params is None: - params = {} + params = dict(params) if params is not None else {} # These are arguments that should be passed to the underlying requests.request call. request_kwargs = {} diff --git a/serpapi/http.py b/serpapi/http.py index 4ea1a33..c6afd81 100644 --- a/serpapi/http.py +++ b/serpapi/http.py @@ -22,6 +22,9 @@ def __init__(self, *, api_key=None, timeout=None): self.session = requests.Session() def request(self, method, path, params, *, assert_200=True, **kwargs): + # Keep API key injection local to this request. + params = dict(params) + # Inject the API Key into the params. request_data = kwargs.get("data") api_key_in_data = isinstance(request_data, dict) and "api_key" in request_data diff --git a/tests/test_parameter_reuse.py b/tests/test_parameter_reuse.py new file mode 100644 index 0000000..8842b54 --- /dev/null +++ b/tests/test_parameter_reuse.py @@ -0,0 +1,79 @@ +import copy +from urllib.parse import parse_qs, urlsplit + +import pytest +import requests + +from serpapi import Client + + +PARAMS = { + "search": {"q": "coffee"}, + "search_archive": {"search_id": "example-search"}, + "locations": {"q": "Austin"}, + "account": {}, +} + + +def capture_requests(monkeypatch, client): + sent = [] + + def send(request, **kwargs): + sent.append(request) + response = requests.Response() + response.status_code = 200 + response.headers["Content-Type"] = "application/json" + response._content = b'{}' + response.request = request + return response + + monkeypatch.setattr(client.session, "send", send) + return sent + + +@pytest.mark.parametrize("method", list(PARAMS)) +@pytest.mark.parametrize("explicit_key", [False, True]) +def test_reused_params_keep_each_clients_key(monkeypatch, method, explicit_key): + first = Client(api_key="client-one") + second = Client(api_key="client-two") + first_sent = capture_requests(monkeypatch, first) + second_sent = capture_requests(monkeypatch, second) + params = dict(PARAMS[method]) + if explicit_key: + params["api_key"] = "caller-key" + original = copy.deepcopy(params) + getattr(first, method)(params) + getattr(second, method)(params) + expected = ["caller-key", "caller-key"] if explicit_key else ["client-one", "client-two"] + actual = [parse_qs(urlsplit(sent[0].url).query)["api_key"][0] for sent in (first_sent, second_sent)] + assert actual == expected + assert params == original + + +@pytest.mark.parametrize("method,override", [ + ("search", {"q": "tea"}), + ("search_archive", {"output": "json"}), + ("locations", {"limit": 2}), + ("account", {"api_key": "caller-key"}), +]) +def test_keyword_overrides_do_not_mutate_params(monkeypatch, method, override): + client = Client(api_key="client-key") + sent = capture_requests(monkeypatch, client) + params = dict(PARAMS[method]) + original = copy.deepcopy(params) + getattr(client, method)(params, **override) + query = parse_qs(urlsplit(sent[0].url).query) + for key, value in override.items(): + assert query[key] == [str(value)] + assert params == original + + +@pytest.mark.parametrize("explicit_key", [False, True]) +def test_direct_request_does_not_mutate_params(monkeypatch, explicit_key): + client = Client(api_key="client-key") + sent = capture_requests(monkeypatch, client) + params = {"api_key": "caller-key"} if explicit_key else {} + original = dict(params) + client.request("GET", "/search", params) + assert parse_qs(urlsplit(sent[0].url).query)["api_key"] == ["caller-key" if explicit_key else "client-key"] + assert params == original From 8e20607c872b9d01e98cb30d74f7891db75a48f2 Mon Sep 17 00:00:00 2001 From: Srujana Maddula Date: Wed, 2 Dec 2026 09:07:00 +0530 Subject: [PATCH 2/2] Reuse the search's API key and request options when paginating --- serpapi/core.py | 8 ++++---- serpapi/models.py | 47 ++++++++++++++++++++++++++++++++++++++--------- 2 files changed, 42 insertions(+), 13 deletions(-) diff --git a/serpapi/core.py b/serpapi/core.py index 4b6bbc8..f6b56fd 100644 --- a/serpapi/core.py +++ b/serpapi/core.py @@ -50,7 +50,7 @@ def search(self, params: dict = None, **kwargs): r = self.request("GET", "/search", params=params, **request_kwargs) - return SerpResults.from_http_response(r, client=self) + return SerpResults.from_http_response(r, client=self, request_options=request_kwargs) def extract(self, params: dict = None, **kwargs): """Extract content from a public URL using the Extract API. @@ -97,7 +97,7 @@ def search_archive(self, params: dict = None, **kwargs): ) r = self.request("GET", f"/searches/{ search_id }", params=params, **request_kwargs) - return SerpResults.from_http_response(r, client=self) + return SerpResults.from_http_response(r, client=self, request_options=request_kwargs) def upload_image(self, image, **kwargs): """Upload an image to SerpApi's Image API. @@ -280,7 +280,7 @@ async def search(self, params: dict = None, **kwargs): r = await self.request("GET", "/search", params=params, **request_kwargs) - return AsyncSerpResults.from_http_response(r, client=self) + return AsyncSerpResults.from_http_response(r, client=self, request_options=request_kwargs) async def extract(self, params: dict = None, **kwargs): """Extract content from a public URL using the Extract API. Use it with ``await``. @@ -315,7 +315,7 @@ async def search_archive(self, params: dict = None, **kwargs): r = await self.request( "GET", f"/searches/{ search_id }", params=params, **request_kwargs ) - return AsyncSerpResults.from_http_response(r, client=self) + return AsyncSerpResults.from_http_response(r, client=self, request_options=request_kwargs) async def upload_image(self, image, **kwargs): """Upload an image to SerpApi's Image API. Use it with ``await``. diff --git a/serpapi/models.py b/serpapi/models.py index d64a6a6..6974edd 100644 --- a/serpapi/models.py +++ b/serpapi/models.py @@ -1,11 +1,28 @@ import json from collections import UserDict +from urllib.parse import parse_qs, urlsplit from .textui import prettify_json from .utils import _response_json +_UNKNOWN = object() + + +def _sent_api_key(r): + """Return the API key in the query string of the request that produced ``r``.""" + + try: + url = r.request.url + except (AttributeError, RuntimeError): # httpx2 raises RuntimeError when no request is set. + return _UNKNOWN + if url is None: + return _UNKNOWN + keys = parse_qs(urlsplit(str(url)).query, keep_blank_values=True).get("api_key") + return keys[-1] if keys else None + + class _BaseSerpResults(UserDict): def __init__(self, data, *, client): @@ -43,12 +60,18 @@ def next_page_url(self): if serpapi_pagination: return serpapi_pagination.get("next") + def _next_page_params(self): + # Next page URLs omit the key, so resend the one this page was fetched with. + api_key = getattr(self, "_api_key", _UNKNOWN) + return {} if api_key is _UNKNOWN else {"api_key": api_key} + @classmethod - def from_http_response(cls, r, *, client=None): + def from_http_response(cls, r, *, client=None, request_options=None): """Construct results from an HTTP response. :param r: The HTTP response to parse. :param client: The client that sent the request. + :param request_options: HTTP options, such as ``timeout`` or ``proxies``, to reuse for later pages. An instance of this class is returned if the response is a valid JSON object. Otherwise, the raw text (as a properly decoded unicode string) is returned. @@ -58,9 +81,12 @@ def from_http_response(cls, r, *, client=None): return r.text try: - return cls(_response_json(r), client=client) + results = cls(_response_json(r), client=client) except ValueError: return r.text + results._api_key = _sent_api_key(r) + results._request_options = dict(request_options or {}) + return results class SerpResults(_BaseSerpResults): @@ -74,11 +100,11 @@ def next_page(self): """Return the next page of results, if any.""" if self.next_page_url: - # Include support for the API key, as it is not included in the next page URL. - params = {"api_key": self.client.api_key} - - r = self.client.request("GET", path=self.next_page_url, params=params) - return SerpResults.from_http_response(r, client=self.client) + options = getattr(self, "_request_options", {}) + r = self.client.request( + "GET", path=self.next_page_url, params=self._next_page_params(), **options + ) + return SerpResults.from_http_response(r, client=self.client, request_options=options) def yield_pages(self, max_pages=1_000): """A generator that ``yield`` s the next ``n`` pages of search results, if any. @@ -111,8 +137,11 @@ async def next_page(self): """Return the next page of results, if any. Use it with ``await``.""" if self.next_page_url: - r = await self.client.request("GET", path=self.next_page_url, params={}) - return AsyncSerpResults.from_http_response(r, client=self.client) + options = getattr(self, "_request_options", {}) + r = await self.client.request( + "GET", path=self.next_page_url, params=self._next_page_params(), **options + ) + return AsyncSerpResults.from_http_response(r, client=self.client, request_options=options) async def yield_pages(self, max_pages=1_000): """An asynchronous generator that ``yield`` s the next ``n`` pages of search results, if any.