Skip to content

Commit 5230ad3

Browse files
authored
feat: add search-a-licious endpoint support (#482)
1 parent 1864259 commit 5230ad3

2 files changed

Lines changed: 35 additions & 0 deletions

File tree

src/openfoodfacts/api.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,7 @@ def __init__(self, api_config: APIConfig):
222222
environment=api_config.environment,
223223
country_code=self.api_config.country.name,
224224
)
225+
self.base_search_url = URLBuilder.search(self.api_config.environment)
225226

226227
def get(
227228
self,
@@ -309,6 +310,35 @@ def text_search(
309310
)
310311
return typing.cast(requests.Response, r).json()
311312

313+
def search(
314+
self,
315+
query: str,
316+
page: int = 1,
317+
page_size: int = 24,
318+
sort_by: Optional[str] = None,
319+
) -> JSONType:
320+
"""Search products using the search-a-licious endpoint.
321+
322+
.. warning::
323+
This feature is in alpha. The search-a-licious API may
324+
change without notice.
325+
326+
:param query: the search query
327+
:param page: page number (starts at 1), defaults to 1
328+
:param page_size: number of results per page, defaults to 24
329+
:param sort_by: field to sort by, optional
330+
:return: search results dict with a 'hits' key containing products
331+
"""
332+
params: dict = {"q": query, "page": page, "page_size": page_size}
333+
if sort_by is not None:
334+
params["sort_by"] = sort_by
335+
resp = http_session.get(
336+
f"{self.base_search_url}/search",
337+
params=params,
338+
)
339+
resp.raise_for_status()
340+
return typing.cast(JSONType, resp.json())
341+
312342
def update(self, body: Dict[str, Any]):
313343
"""Create a new product or update an existing one."""
314344
if not body.get("code"):

src/openfoodfacts/utils/__init__.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,11 @@ def country(flavor: Flavor, environment: Environment, country_code: str) -> str:
127127
base_domain=flavor.get_base_domain(),
128128
)
129129

130+
@staticmethod
131+
def search(environment: Environment) -> str:
132+
domain = "net" if environment == Environment.net else "org"
133+
return f"https://search.openfoodfacts.{domain}"
134+
130135

131136
def jsonl_iter(jsonl_path: Union[str, Path]) -> Iterable[Dict]:
132137
"""Iterate over elements of a JSONL file.

0 commit comments

Comments
 (0)