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.
57 changes: 11 additions & 46 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,17 +45,8 @@ 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)

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 Down Expand Up @@ -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
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
158 changes: 158 additions & 0 deletions tests/test_parameter_reuse.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
import copy
from collections import UserDict
from io import BytesIO
from types import SimpleNamespace
from unittest.mock import patch
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)
client.session.trust_env = False
options = dict(timeout=4, verify="ca.pem", cert="client.pem", stream=True,
proxies={"https": "http://proxy.invalid"})
with patch.object(client.session, "send", wraps=client.session.send) as send:
getattr(client, method)(params, **override, **options)
assert all(send.call_args[1][key] == value for key, value in options.items())
query = parse_qs(urlsplit(sent[0].url).query)
assert set(options).isdisjoint(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


def test_session_wrapper_without_params(monkeypatch):
client = Client(api_key="client-key")
sent = capture_requests(monkeypatch, client)
client.session = SimpleNamespace(request=client.session.request)

client.search(q="coffee")

assert parse_qs(urlsplit(sent[0].url).query) == {"q": ["coffee"], "api_key": ["client-key"]}


def test_form_key_preserves_repeated_query_fields(monkeypatch):
client = Client(api_key="client-key")
sent = capture_requests(monkeypatch, client)
client.request("POST", "/example", [("tag", "coffee"), ("tag", "tea")],
data={"api_key": "form-key"})
assert parse_qs(urlsplit(sent[0].url).query) == {"tag": ["coffee", "tea"]}


@pytest.mark.parametrize("constructor,overrides,expected", [
(None, {}, ["session-key"]),
("client-key", {}, ["client-key"]),
("client-key", {"api_key": "caller-key"}, ["caller-key"]),
("client-key", {"api_key": None}, []),
(None, {b"api_key": "caller-key"}, ["caller-key"]),
(None, {b"api_key": None}, []),
])
def test_query_key_precedence(monkeypatch, constructor, overrides, expected):
client = Client(api_key=constructor)
client.session.params = {"api_key": "session-key"}
sent = capture_requests(monkeypatch, client)
params = dict(overrides, q="coffee")
original = params.copy()
client.search(params)
assert parse_qs(urlsplit(sent[0].url).query).get("api_key", []) == expected
assert params == original
assert client.session.params == {"api_key": "session-key"}


@pytest.mark.parametrize("data", [
UserDict({"api_key": "form-key"}), [(b"api_key", "form-key")],
])
def test_form_key_suppresses_only_session_key(monkeypatch, data):
client = Client()
client.session.params = {"api_key": "session-key", "hl": "en"}
sent = capture_requests(monkeypatch, client)
client.request("POST", "/example", {}, data=data)
assert parse_qs(urlsplit(sent[0].url).query) == {"hl": ["en"]}
assert parse_qs(sent[0].body) == {"api_key": ["form-key"]}
assert client.session.params == {"api_key": "session-key", "hl": "en"}


@pytest.mark.parametrize("constructor,overrides,query_keys,form_key", [
(None, {}, ["session-key"], None),
("client-key", {}, [], "client-key"),
(None, {"api_key": "form-key"}, [], "form-key"),
("client-key", {"api_key": None}, [], None),
])
def test_upload_key_precedence(monkeypatch, constructor, overrides, query_keys, form_key):
client = Client(api_key=constructor)
client.session.params = {"api_key": "session-key"}
sent = capture_requests(monkeypatch, client)
client.upload_image(BytesIO(b"image"), **overrides)
assert parse_qs(urlsplit(sent[0].url).query).get("api_key", []) == query_keys
if form_key is None:
assert b'name="api_key"' not in sent[0].body
else:
assert b'name="api_key"\r\n\r\n' + form_key.encode() + b'\r\n' in sent[0].body
Loading