Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ The commands below use `python` from that environment.
These tests cover response parsing, image uploads and extraction with simulated responses, timeouts, exceptions, the async client, documentation syntax, and the example runner:

```sh
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
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_parameter_reuse.py tests/test_async_client.py tests/test_docs_examples.py tests/test_docs_example_runner.py -k 'not live' -q
```

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.
Expand Down
2 changes: 1 addition & 1 deletion docs/user_guide/client-usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ params = {
results = client.search(params)
```

You can combine a dictionary with keyword arguments. The client adds the keyword arguments to the dictionary and replaces existing values with the same name:
You can combine a dictionary with keyword arguments. Keyword arguments override matching search parameters for this request only. The client leaves your dictionary unchanged, so you can reuse it for another search:

```python
params = {"engine": "google", "q": "coffee"}
Expand Down
9 changes: 2 additions & 7 deletions docs/user_guide/request-options.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ The client sends the arguments to two places:
- `timeout`, `proxies`, `verify`, `stream`, and `cert` are passed to `requests`.
- All remaining keyword arguments are sent to SerpApi as API parameters.

If you pass a parameter dictionary and keyword arguments together, the search parameters in the keyword arguments update your dictionary:
If you pass a parameter dictionary and keyword arguments together, keyword arguments override matching parameters for that request without changing the dictionary:

```python
params = {"engine": "google", "q": "coffee"}
Expand All @@ -131,9 +131,4 @@ results = client.search(params, location="Austin, Texas", timeout=10)

In this example, `location` is added to the SerpApi request parameters, while `timeout` is passed to `requests`.

When you want to keep the original dictionary unchanged, pass a copy:

```python
params = {"engine": "google", "q": "coffee"}
results = client.search(params.copy(), location="Austin, Texas")
```
For searches, a per-call `api_key` overrides the client's key, which in turn overrides a key in `client.session.params`. Pass `api_key=None` to omit the key for that search.
65 changes: 15 additions & 50 deletions serpapi/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ def search(self, params: dict = None, **kwargs):
Returns a ``serpapi.SerpResults`` object for JSON responses, or text
when ``output="html"`` or ``output="md"`` is requested. Prefer passing SerpApi engine
parameters as keyword arguments. A parameter dictionary is also accepted
when your code already has parameters in a mapping.
when your code already has parameters in a mapping. The caller's mapping
is not modified.


:param params: Optional mapping of SerpApi search parameters such as ``engine``, ``q``, ``location``, and ``output``.
Expand All @@ -44,21 +45,12 @@ def search(self, params: dict = None, **kwargs):

**Learn more**: https://serpapi.com/search-api
"""
if params is None:
params = {}

# These are arguments that should be passed to the underlying requests.request call.
request_kwargs = {}
for key in ["timeout", "proxies", "verify", "stream", "cert"]:
if key in kwargs:
request_kwargs[key] = kwargs.pop(key)

if kwargs:
params.update(kwargs)
request_kwargs = _pop_request_options(kwargs)
params = dict(params if params is not None else {}, **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.
Expand Down Expand Up @@ -94,17 +86,8 @@ def search_archive(self, params: dict = None, **kwargs):

**Learn more**: https://serpapi.com/search-archive-api
"""
if params is None:
params = {}

# These are arguments that should be passed to the underlying requests.request call.
request_kwargs = {}
for key in ["timeout", "proxies", "verify", "stream", "cert"]:
if key in kwargs:
request_kwargs[key] = kwargs.pop(key)

if kwargs:
params.update(kwargs)
request_kwargs = _pop_request_options(kwargs)
params = dict(params if params is not None else {}, **kwargs)

try:
search_id = params["search_id"]
Expand All @@ -114,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.
Expand All @@ -137,7 +120,7 @@ def upload_image(self, image, **kwargs):
request_kwargs[key] = kwargs.pop(key)

data = kwargs
if "api_key" not in data:
if self.api_key is not None and "api_key" not in data:
data["api_key"] = self.api_key

image_file = None
Expand Down Expand Up @@ -172,17 +155,8 @@ def locations(self, params: dict = None, **kwargs):

**Learn more**: https://serpapi.com/locations-api
"""
if params is None:
params = {}

# These are arguments that should be passed to the underlying requests.request call.
request_kwargs = {}
for key in ["timeout", "proxies", "verify", "stream", "cert"]:
if key in kwargs:
request_kwargs[key] = kwargs.pop(key)

if kwargs:
params.update(kwargs)
request_kwargs = _pop_request_options(kwargs)
params = dict(params if params is not None else {}, **kwargs)

r = self.request(
"GET",
Expand All @@ -202,17 +176,8 @@ def account(self, params: dict = None, **kwargs):
**Learn more**: https://serpapi.com/account-api
"""

if params is None:
params = {}

# These are arguments that should be passed to the underlying requests.request call.
request_kwargs = {}
for key in ["timeout", "proxies", "verify", "stream", "cert"]:
if key in kwargs:
request_kwargs[key] = kwargs.pop(key)

if kwargs:
params.update(kwargs)
request_kwargs = _pop_request_options(kwargs)
params = dict(params if params is not None else {}, **kwargs)

r = self.request("GET", "/account.json", params=params, assert_200=True, **request_kwargs)
return r.json()
Expand Down Expand Up @@ -315,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``.
Expand Down Expand Up @@ -350,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``.
Expand Down
24 changes: 19 additions & 5 deletions serpapi/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,9 @@ def __init__(self, *, api_key=None, timeout=None):
self.session = requests.Session()

def request(self, method, path, params, *, assert_200=True, **kwargs):
# 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
if "api_key" not in params and not api_key_in_data:
params["api_key"] = self.api_key
params = _sync_query_params(
params, kwargs.get("data"), self.api_key, getattr(self.session, "params", None)
)

# Build the URL, as needed.
if not path.startswith("http"):
Expand Down Expand Up @@ -481,6 +479,22 @@ def _form_has_api_key(data):
return False


def _sync_query_params(params, data, api_key, defaults):
form_key = _form_has_api_key(data)
if api_key is not None and not form_key and not _has_api_key(params):
params = {**params, "api_key": api_key}
Comment on lines +484 to +485

# Requests merges session defaults into mappings by exact key. A None value
# suppresses that spelling without putting it in the URL or changing the session.
if isinstance(defaults, Mapping) and _has_api_key(defaults):
query = params or {}
if isinstance(query, Mapping) and (form_key or _has_api_key(query)):
suppress = {k: None for k in ("api_key", b"api_key") if k in defaults and k not in query}
if suppress:
return {**query, **suppress}
return params


def _with_query_defaults(url, defaults, params, api_key_in_data):
# Explicit None suppresses a default even though it isn't in the encoded URL.
specified = set(url.params).union(params)
Expand Down
47 changes: 38 additions & 9 deletions serpapi/models.py
Original file line number Diff line number Diff line change
@@ -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):
Expand Down Expand Up @@ -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.
Expand All @@ -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):
Expand All @@ -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.
Expand Down Expand Up @@ -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.
Expand Down
Loading