Skip to content

Commit 1084e05

Browse files
authored
feat: improve facet functions (#377)
- add the /facets/ prefix that is now required - add a `sort_by` parameter to allow sorting products with respect to a field
1 parent 38fbf5a commit 1084e05

1 file changed

Lines changed: 15 additions & 4 deletions

File tree

openfoodfacts/api.py

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -95,10 +95,15 @@ def __init__(self, api_config: APIConfig):
9595
)
9696

9797
def get(self, facet_name: Union[Facet, str]) -> JSONType:
98+
"""Return all possible values for a given facet.
99+
100+
:param facet_name: the facet name, e.g. "label"
101+
:return: the API response containing all possible values for the facet
102+
"""
98103
facet = Facet.from_str_or_enum(facet_name)
99104
facet_plural = facet.value.replace("_", "-")
100105
resp = send_get_request(
101-
url=f"{self.base_url}/{facet_plural}",
106+
url=f"{self.base_url}/facets/{facet_plural}",
102107
params={"json": "1"},
103108
api_config=self.api_config,
104109
auth=get_http_auth(self.api_config.environment),
@@ -113,6 +118,7 @@ def get_products(
113118
page: int = 1,
114119
page_size: int = 25,
115120
fields: Optional[List[str]] = None,
121+
sort_by: Optional[str] = None,
116122
) -> JSONType:
117123
"""Return products for a given facet value.
118124
@@ -122,16 +128,21 @@ def get_products(
122128
:param page_size: the number of items per page, defaults to 25
123129
:param fields: a list of fields to return. If None, all fields are
124130
returned.
131+
:param sort_by: the sorting key, defaults to None (no sorting)
132+
possible values (not exhaustive) are: "popularity",
133+
"last_modified_t", "created_t".
125134
:return: the API response
126135
"""
127136
facet = Facet.from_str_or_enum(facet_name)
128-
facet_singular = facet.name.replace("_", "-")
129-
params: JSONType = {"page": page, "page_size": page_size}
137+
facet_plural = facet.value.replace("_", "-")
138+
params: JSONType = {"page": page, "page_size": page_size, "json": "1"}
130139
if fields is not None:
131140
params["fields"] = ",".join(fields)
141+
if sort_by is not None:
142+
params["sort_by"] = sort_by
132143

133144
resp = send_get_request(
134-
url=f"{self.base_url}/{facet_singular}/{facet_value}.json",
145+
url=f"{self.base_url}/facets/{facet_plural}/{facet_value}",
135146
params=params,
136147
api_config=self.api_config,
137148
auth=get_http_auth(self.api_config.environment),

0 commit comments

Comments
 (0)