From 4f3aeafefecb33c9591e0e3bf62096b9fd1a28c0 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 07:16:44 +0000 Subject: [PATCH 1/4] feat: add Store search method, deprecate `search` and `sort_by` in listing `GET /v2/store` answers a request with `search` differently from one without it. A search returns the best matches as a single page of at most 100 Actors, ordered by relevance. It ignores `offset`, and reports the number of Actors returned as `total`. `store().iterate(search=...)` therefore requested the same page again and again, since the iterator stops only at a page with no rows. `StoreCollectionClient.search()` now covers the search: - one request with the query, `limit` and the `category`, `username`, `pricing_model` and `include_unrunnable_actors` filters, and no `offset` - returns a `StoreSearchResult` with `items` and the `limit` the API applied; `total` and `offset` of the response are left out, as they don't mean what they mean on a listing page - an empty query raises `ValueError`, as the API answers it with the listing The `search` and `sort_by` arguments of `list()` and `iterate()` are deprecated, each with a `DeprecationWarning`, for removal in v4. The API ignores `sort_by`. Until then, `iterate(search=...)` makes a single request and yields that one page, and `list(search=...)` works as before. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_017ocuAGtCcLFHtTvqReATBj --- docs/02_concepts/08_pagination.mdx | 2 +- .../_resource_clients/store_collection.py | 301 +++++++++++++++--- tests/integration/test_store.py | 64 +++- tests/unit/test_store_collection_params.py | 234 +++++++++++++- 4 files changed, 552 insertions(+), 49 deletions(-) diff --git a/docs/02_concepts/08_pagination.mdx b/docs/02_concepts/08_pagination.mdx index 99b343df6..980ed51ab 100644 --- a/docs/02_concepts/08_pagination.mdx +++ b/docs/02_concepts/08_pagination.mdx @@ -27,7 +27,7 @@ Most methods named `list` or `list_something` in the Apify client return a page On `DatasetItemsPage`, `count` reports how many dataset rows the API scanned for the page. Filters drop items from a page and `unwind` multiplies them, so a page can hold fewer or more items than `count`. -Some methods paginate differently. For example, `RequestQueueClient.list_requests` returns a cursor-based `ListOfRequests` without the `total`, `offset`, and `count` fields. To fetch the next page, pass its `next_cursor` value back as the `cursor` parameter. Other examples include `list_keys` and `list_head`. Regardless, the primary results are always stored under the `items` field, and the `limit` field can be used to control the number of results returned. +Some methods paginate differently. For example, `RequestQueueClient.list_requests` returns a cursor-based `ListOfRequests` without the `total`, `offset`, and `count` fields. To fetch the next page, pass its `next_cursor` value back as the `cursor` parameter. Other examples include `list_keys` and `list_head`. `StoreCollectionClient.search` doesn't paginate at all: it returns the Actors that match a query best, 100 at most, as a `StoreSearchResult` without the `total`, `offset`, and `count` fields, and there is no next page. Regardless, the primary results are always stored under the `items` field, and the `limit` field can be used to control the number of results returned. The following example shows how to fetch all items from a dataset using pagination: diff --git a/src/apify_client/_resource_clients/store_collection.py b/src/apify_client/_resource_clients/store_collection.py index 4a3462d4f..b9906ac8a 100644 --- a/src/apify_client/_resource_clients/store_collection.py +++ b/src/apify_client/_resource_clients/store_collection.py @@ -1,5 +1,7 @@ from __future__ import annotations +import warnings +from dataclasses import dataclass from typing import TYPE_CHECKING, Any from apify_client._docs import docs_group @@ -9,18 +11,77 @@ from apify_client._utils.http import validate_response if TYPE_CHECKING: - from collections.abc import AsyncIterator, Iterator + from collections.abc import AsyncIterator, Awaitable, Callable, Iterator from apify_client._models import StoreActor from apify_client.types import Timeout +@docs_group('Other') +@dataclass +class StoreSearchResult: + """The single page of Actors returned by the `search` method. + + The API answers a store search with one page of the best matches. It reports the number of Actors returned as + the total and zero as the offset, whatever the query matches, so this class has no `total`, `offset` or `count`. + """ + + items: list[StoreActor] + """The Actors matching the query, best match first.""" + + limit: int + """The maximum number of Actors the API allowed in this result. + + It is the requested `limit`, or the API's maximum when no limit or a larger one was requested. With as many + `items` as this, more Actors may match the query than were returned. + """ + + +def _warn_about_deprecated_arguments(*, search: str | None, sort_by: str | None) -> None: + """Emit a `DeprecationWarning` for each deprecated argument that is set, pointing at the caller of the method.""" + if search is not None: + warnings.warn( + 'The `search` argument is deprecated and will be removed in v4. Use the `search` method instead.', + DeprecationWarning, + stacklevel=4, + ) + if sort_by is not None: + warnings.warn( + 'The `sort_by` argument is deprecated and will be removed in v4. The API ignores it.', + DeprecationWarning, + stacklevel=4, + ) + + +def _validate_search_query(search: str) -> None: + """Reject an empty query, which the API answers with the store listing. + + Raises: + ValueError: If `search` is empty. + """ + if not search: + raise ValueError('`search` must not be empty. To go through the store without a query, use `list`.') + + +def _iterate_page(get_page: Callable[[], ListOfStoreActors]) -> Iterator[StoreActor]: + """Yield the Actors of the single page that `get_page` returns.""" + page = get_page() + yield from page.items + + +async def _iterate_page_async(get_page: Callable[[], Awaitable[ListOfStoreActors]]) -> AsyncIterator[StoreActor]: + """Yield the Actors of the single page that `get_page` returns.""" + page = await get_page() + for item in page.items: + yield item + + @docs_group('Resource clients') class StoreCollectionClient(ResourceClient): """Sub-client for the Apify store collection. - Provides methods to browse the Apify store, e.g. list available Actors. Obtain an instance via an appropriate - method on the `ApifyClient` class. + Provides methods to browse the Apify store, e.g. list available Actors or search them. Obtain an instance via an + appropriate method on the `ApifyClient` class. """ def __init__( @@ -47,17 +108,17 @@ def list( include_unrunnable_actors: bool | None = None, timeout: Timeout = 'medium', ) -> ListOfStoreActors: - """List Actors in Apify store. + """List Actors in Apify store, ordered by their position in the store. https://docs.apify.com/api/v2/#/reference/store/store-actors-collection/get-list-of-actors-in-store Args: limit: How many Actors to list. offset: What Actor to include as first when retrieving the list. - search: String to search by. The search runs on the following fields: title, name, description, username, - readme. - sort_by: Deprecated. The API ignores this argument. Results are ordered by relevance when `search` is used, - and by Store position otherwise. + search: Deprecated. Use the `search` method. With this argument, the API returns the best matches as a + single page of at most 100 Actors, ignores `offset`, and reports the number of Actors returned as + `total`. + sort_by: Deprecated. The API ignores this argument. category: Filter by this category. username: Filter by this username. pricing_model: Filter by this pricing model. @@ -69,18 +130,18 @@ def list( Returns: The list of available Actors matching the specified filters. """ - result = self._list( - timeout=timeout, + _warn_about_deprecated_arguments(search=search, sort_by=sort_by) + return self._list_actors( limit=limit, offset=offset, search=search, - sortBy=sort_by, + sort_by=sort_by, category=category, username=username, - pricingModel=pricing_model, - includeUnrunnableActors=include_unrunnable_actors, + pricing_model=pricing_model, + include_unrunnable_actors=include_unrunnable_actors, + timeout=timeout, ) - return validate_response(ListOfStoreActorsResponse, result).data def iterate( self, @@ -96,7 +157,7 @@ def iterate( chunk_size: int | None = None, timeout: Timeout = 'medium', ) -> Iterator[StoreActor]: - """Iterate over Actors in Apify store. + """Iterate over Actors in Apify store, ordered by their position in the store. Simple `list` does only one API call, possibly not listing all items matching the criteria. This method returns an iterator that is capable of making multiple API calls to retrieve all items matching the criteria. @@ -106,10 +167,9 @@ def iterate( Args: limit: How many Actors to list. offset: What Actor to include as first when retrieving the list. - search: String to search by. The search runs on the following fields: title, name, description, username, - readme. - sort_by: Deprecated. The API ignores this argument. Results are ordered by relevance when `search` is used, - and by Store position otherwise. + search: Deprecated. Use the `search` method. With this argument, the iterator makes a single API call and + yields the best matches, at most 100 Actors, as the API has no further page of a search. + sort_by: Deprecated. The API ignores this argument. category: Filter by this category. username: Filter by this username. pricing_model: Filter by this pricing model. @@ -122,9 +182,10 @@ def iterate( Yields: The Actors in the store matching the specified filters. """ + _warn_about_deprecated_arguments(search=search, sort_by=sort_by) def _callback(*, limit: int | None = None, offset: int | None = None) -> ListOfStoreActors: - return self.list( + return self._list_actors( limit=limit, offset=offset, search=search, @@ -136,15 +197,96 @@ def _callback(*, limit: int | None = None, offset: int | None = None) -> ListOfS timeout=timeout, ) + if search: + # The API ignores `offset` for a search, so asking for another page would return the same Actors again. + return _iterate_page(lambda: _callback(limit=limit, offset=offset)) + return get_items_iterator(_callback, limit=limit, offset=offset, chunk_size=chunk_size) + def search( + self, + search: str, + *, + limit: int | None = None, + category: str | None = None, + username: str | None = None, + pricing_model: str | None = None, + include_unrunnable_actors: bool | None = None, + timeout: Timeout = 'medium', + ) -> StoreSearchResult: + """Search Apify store and return the Actors that match the query best, ordered by relevance. + + The API answers a search with a single page of at most 100 Actors. There is no next page and no way to skip + results, and the API does not report how many Actors match the query in total. A result holding as many + Actors as its `limit` can therefore be cut off: narrow it down with a more specific query or with the + `category`, `username` and `pricing_model` filters. To go through the whole store, use `list` or `iterate`. + + https://docs.apify.com/api/v2/#/reference/store/store-actors-collection/get-list-of-actors-in-store + + Args: + search: Text to search for. It can't be empty. + limit: How many Actors to return. The API returns at most 100 Actors for a search, which is also the + default, and reduces a larger value to 100. + category: Filter by this category. + username: Filter by this username. + pricing_model: Filter by this pricing model. + include_unrunnable_actors: Whether to include Actors that are not safe to run automatically, such as + Actors whose developers have not passed KYC, or full-permission Actors without a large user base. + By default, they are excluded. + timeout: Timeout for the API HTTP request. + + Returns: + The matching Actors, best match first, and the limit the API applied. + + Raises: + ValueError: If `search` is empty. + """ + _validate_search_query(search) + page = self._list_actors( + limit=limit, + search=search, + category=category, + username=username, + pricing_model=pricing_model, + include_unrunnable_actors=include_unrunnable_actors, + timeout=timeout, + ) + return StoreSearchResult(items=page.items, limit=page.limit) + + def _list_actors( + self, + *, + limit: int | None = None, + offset: int | None = None, + search: str | None = None, + sort_by: str | None = None, + category: str | None = None, + username: str | None = None, + pricing_model: str | None = None, + include_unrunnable_actors: bool | None = None, + timeout: Timeout, + ) -> ListOfStoreActors: + """Request one page of store Actors, which the API fills by search when `search` is set.""" + result = self._list( + timeout=timeout, + limit=limit, + offset=offset, + search=search, + sortBy=sort_by, + category=category, + username=username, + pricingModel=pricing_model, + includeUnrunnableActors=include_unrunnable_actors, + ) + return validate_response(ListOfStoreActorsResponse, result).data + @docs_group('Resource clients') class StoreCollectionClientAsync(ResourceClientAsync): """Sub-client for the Apify store collection. - Provides methods to browse the Apify store, e.g. list available Actors. Obtain an instance via an appropriate - method on the `ApifyClientAsync` class. + Provides methods to browse the Apify store, e.g. list available Actors or search them. Obtain an instance via an + appropriate method on the `ApifyClientAsync` class. """ def __init__( @@ -171,17 +313,17 @@ async def list( include_unrunnable_actors: bool | None = None, timeout: Timeout = 'medium', ) -> ListOfStoreActors: - """List Actors in Apify store. + """List Actors in Apify store, ordered by their position in the store. https://docs.apify.com/api/v2/#/reference/store/store-actors-collection/get-list-of-actors-in-store Args: limit: How many Actors to list. offset: What Actor to include as first when retrieving the list. - search: String to search by. The search runs on the following fields: title, name, description, username, - readme. - sort_by: Deprecated. The API ignores this argument. Results are ordered by relevance when `search` is used, - and by Store position otherwise. + search: Deprecated. Use the `search` method. With this argument, the API returns the best matches as a + single page of at most 100 Actors, ignores `offset`, and reports the number of Actors returned as + `total`. + sort_by: Deprecated. The API ignores this argument. category: Filter by this category. username: Filter by this username. pricing_model: Filter by this pricing model. @@ -193,18 +335,18 @@ async def list( Returns: The list of available Actors matching the specified filters. """ - result = await self._list( - timeout=timeout, + _warn_about_deprecated_arguments(search=search, sort_by=sort_by) + return await self._list_actors( limit=limit, offset=offset, search=search, - sortBy=sort_by, + sort_by=sort_by, category=category, username=username, - pricingModel=pricing_model, - includeUnrunnableActors=include_unrunnable_actors, + pricing_model=pricing_model, + include_unrunnable_actors=include_unrunnable_actors, + timeout=timeout, ) - return validate_response(ListOfStoreActorsResponse, result).data def iterate( self, @@ -220,7 +362,7 @@ def iterate( chunk_size: int | None = None, timeout: Timeout = 'medium', ) -> AsyncIterator[StoreActor]: - """Iterate over Actors in Apify store. + """Iterate over Actors in Apify store, ordered by their position in the store. Simple `list` does only one API call, possibly not listing all items matching the criteria. This method returns an iterator that is capable of making multiple API calls to retrieve all items matching the criteria. @@ -230,10 +372,9 @@ def iterate( Args: limit: How many Actors to list. offset: What Actor to include as first when retrieving the list. - search: String to search by. The search runs on the following fields: title, name, description, username, - readme. - sort_by: Deprecated. The API ignores this argument. Results are ordered by relevance when `search` is used, - and by Store position otherwise. + search: Deprecated. Use the `search` method. With this argument, the iterator makes a single API call and + yields the best matches, at most 100 Actors, as the API has no further page of a search. + sort_by: Deprecated. The API ignores this argument. category: Filter by this category. username: Filter by this username. pricing_model: Filter by this pricing model. @@ -246,9 +387,10 @@ def iterate( Yields: The Actors in the store matching the specified filters. """ + _warn_about_deprecated_arguments(search=search, sort_by=sort_by) async def _callback(*, limit: int | None = None, offset: int | None = None) -> ListOfStoreActors: - return await self.list( + return await self._list_actors( limit=limit, offset=offset, search=search, @@ -260,4 +402,85 @@ async def _callback(*, limit: int | None = None, offset: int | None = None) -> L timeout=timeout, ) + if search: + # The API ignores `offset` for a search, so asking for another page would return the same Actors again. + return _iterate_page_async(lambda: _callback(limit=limit, offset=offset)) + return get_items_iterator_async(_callback, limit=limit, offset=offset, chunk_size=chunk_size) + + async def search( + self, + search: str, + *, + limit: int | None = None, + category: str | None = None, + username: str | None = None, + pricing_model: str | None = None, + include_unrunnable_actors: bool | None = None, + timeout: Timeout = 'medium', + ) -> StoreSearchResult: + """Search Apify store and return the Actors that match the query best, ordered by relevance. + + The API answers a search with a single page of at most 100 Actors. There is no next page and no way to skip + results, and the API does not report how many Actors match the query in total. A result holding as many + Actors as its `limit` can therefore be cut off: narrow it down with a more specific query or with the + `category`, `username` and `pricing_model` filters. To go through the whole store, use `list` or `iterate`. + + https://docs.apify.com/api/v2/#/reference/store/store-actors-collection/get-list-of-actors-in-store + + Args: + search: Text to search for. It can't be empty. + limit: How many Actors to return. The API returns at most 100 Actors for a search, which is also the + default, and reduces a larger value to 100. + category: Filter by this category. + username: Filter by this username. + pricing_model: Filter by this pricing model. + include_unrunnable_actors: Whether to include Actors that are not safe to run automatically, such as + Actors whose developers have not passed KYC, or full-permission Actors without a large user base. + By default, they are excluded. + timeout: Timeout for the API HTTP request. + + Returns: + The matching Actors, best match first, and the limit the API applied. + + Raises: + ValueError: If `search` is empty. + """ + _validate_search_query(search) + page = await self._list_actors( + limit=limit, + search=search, + category=category, + username=username, + pricing_model=pricing_model, + include_unrunnable_actors=include_unrunnable_actors, + timeout=timeout, + ) + return StoreSearchResult(items=page.items, limit=page.limit) + + async def _list_actors( + self, + *, + limit: int | None = None, + offset: int | None = None, + search: str | None = None, + sort_by: str | None = None, + category: str | None = None, + username: str | None = None, + pricing_model: str | None = None, + include_unrunnable_actors: bool | None = None, + timeout: Timeout, + ) -> ListOfStoreActors: + """Request one page of store Actors, which the API fills by search when `search` is set.""" + result = await self._list( + timeout=timeout, + limit=limit, + offset=offset, + search=search, + sortBy=sort_by, + category=category, + username=username, + pricingModel=pricing_model, + includeUnrunnableActors=include_unrunnable_actors, + ) + return validate_response(ListOfStoreActorsResponse, result).data diff --git a/tests/integration/test_store.py b/tests/integration/test_store.py index 696e5bab2..32e09d801 100644 --- a/tests/integration/test_store.py +++ b/tests/integration/test_store.py @@ -9,6 +9,7 @@ from .._utils import maybe_await from apify_client._models import ListOfStoreActors, StoreActor +from apify_client._resource_clients.store_collection import StoreSearchResult if TYPE_CHECKING: from apify_client import ApifyClient, ApifyClientAsync @@ -22,12 +23,62 @@ async def test_store_list(client: ApifyClient | ApifyClientAsync) -> None: assert len(actors_list.items) > 0 # Store always has actors -async def test_store_list_with_search(client: ApifyClient | ApifyClientAsync) -> None: - """Test listing store with search filter.""" - store_page = await maybe_await(client.store().list(limit=5, search='web scraper')) +async def test_store_search(client: ApifyClient | ApifyClientAsync) -> None: + """Test that a store search returns the best matches as one page.""" + result = await maybe_await(client.store().search('web scraper', limit=5)) + assert isinstance(result, StoreSearchResult) + # The public store holds thousands of scrapers, so the page is always full. + assert len(result.items) == 5 + assert result.limit == 5 + for actor in result.items: + assert isinstance(actor, StoreActor) + + +async def test_store_search_returns_at_most_100_actors(client: ApifyClient | ApifyClientAsync) -> None: + """Test that a store search returns at most 100 Actors, whatever limit it is asked for.""" + default_result = await maybe_await(client.store().search('scraper')) + large_result = await maybe_await(client.store().search('scraper', limit=1000)) + assert default_result.limit == 100 + assert len(default_result.items) == 100 + assert large_result.limit == 100 + assert len(large_result.items) == 100 + + +async def test_store_search_without_matches(client: ApifyClient | ApifyClientAsync) -> None: + """Test that a store search returns nothing for a query that matches no Actor.""" + result = await maybe_await(client.store().search('qzxjvkwpqzxjvkwp')) + assert result.items == [] + + +async def test_store_search_filter_by_username(client: ApifyClient | ApifyClientAsync) -> None: + """Test a store search filtered by a known username (apify).""" + result = await maybe_await(client.store().search('scraper', limit=10, username='apify')) + assert len(result.items) > 0 + for actor in result.items: + assert actor.username == 'apify' + + +async def test_store_list_with_deprecated_search(client: ApifyClient | ApifyClientAsync) -> None: + """Test that the store listing still accepts the deprecated `search` and returns the search page.""" + with pytest.warns(DeprecationWarning, match='`search` argument is deprecated'): + store_page = await maybe_await(client.store().list(limit=5, search='web scraper')) assert isinstance(store_page, ListOfStoreActors) - assert store_page.items is not None - assert isinstance(store_page.items, list) + assert len(store_page.items) == 5 + + +async def test_store_iterate_with_deprecated_search(client: ApifyClient | ApifyClientAsync, *, is_async: bool) -> None: + """Test that iterating with the deprecated `search` ends after the single page the API has for a search.""" + with pytest.warns(DeprecationWarning, match='`search` argument is deprecated'): + iterator = client.store().iterate(search='scraper') + if is_async: + assert isinstance(iterator, AsyncIterator) + collected = [actor async for actor in iterator] + else: + assert isinstance(iterator, Iterator) + collected = list(iterator) + + assert len(collected) == 100 + assert len({actor.id for actor in collected}) == 100 async def test_store_list_pagination(client: ApifyClient | ApifyClientAsync) -> None: @@ -73,7 +124,8 @@ async def test_store_list_accepts_sort_by(client: ApifyClient | ApifyClientAsync The API accepts `sortBy` for compatibility but ignores it, so the order is not asserted. """ - page = await maybe_await(client.store().list(limit=10, sort_by='popularity')) + with pytest.warns(DeprecationWarning, match='`sort_by` argument is deprecated'): + page = await maybe_await(client.store().list(limit=10, sort_by='popularity')) assert isinstance(page, ListOfStoreActors) assert len(page.items) > 0 diff --git a/tests/unit/test_store_collection_params.py b/tests/unit/test_store_collection_params.py index d660bcac7..296137fce 100644 --- a/tests/unit/test_store_collection_params.py +++ b/tests/unit/test_store_collection_params.py @@ -1,11 +1,13 @@ from __future__ import annotations import json -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any import pytest from werkzeug import Request, Response +from apify_client._resource_clients.store_collection import StoreSearchResult + if TYPE_CHECKING: from collections.abc import Callable @@ -28,11 +30,35 @@ } } +_STORE_ACTORS = [ + { + 'id': f'actor-id-{index}', + 'title': f'Actor {index}', + 'name': f'actor-{index}', + 'username': 'jane', + 'stats': {'totalUsers': 1, 'actorReviewRating': 0, 'actorReviewCount': 0}, + } + for index in range(2) +] + +# The API answers a search with the same full page whatever `offset` it is sent, and reports the number of Actors +# returned as `total`. +_SEARCH_RESPONSE = { + 'data': { + 'total': 2, + 'offset': 0, + 'limit': 2, + 'desc': False, + 'count': 2, + 'items': _STORE_ACTORS, + } +} + -def capture(captured: list[Request]) -> Callable[[Request], Response]: +def capture(captured: list[Request], response: dict[str, Any] = _STORE_RESPONSE) -> Callable[[Request], Response]: def handler(request: Request) -> Response: captured.append(request) - return Response(json.dumps(_STORE_RESPONSE), status=200, mimetype='application/json') + return Response(json.dumps(response), status=200, mimetype='application/json') return handler @@ -84,3 +110,205 @@ async def test_iterate_sends_include_unrunnable_actors_async( assert actors == [] assert len(captured) == 1 assert captured[0].args.get('includeUnrunnableActors') == 'true' + + +def test_search_sends_query_and_filters(httpserver: HTTPServer, sync_client: ApifyClient) -> None: + """`search` sends one request with the query, the limit and the filters, and no offset.""" + captured: list[Request] = [] + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_handler(capture(captured, _SEARCH_RESPONSE)) + + sync_client.store().search( + 'web scraper', + limit=2, + category='AI', + username='jane', + pricing_model='FREE', + include_unrunnable_actors=True, + ) + + assert len(captured) == 1 + assert captured[0].args.to_dict() == { + 'search': 'web scraper', + 'limit': '2', + 'category': 'AI', + 'username': 'jane', + 'pricingModel': 'FREE', + 'includeUnrunnableActors': 'true', + } + + +async def test_search_sends_query_and_filters_async(httpserver: HTTPServer, async_client: ApifyClientAsync) -> None: + """Async `search` sends one request with the query, the limit and the filters, and no offset.""" + captured: list[Request] = [] + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_handler(capture(captured, _SEARCH_RESPONSE)) + + await async_client.store().search( + 'web scraper', + limit=2, + category='AI', + username='jane', + pricing_model='FREE', + include_unrunnable_actors=True, + ) + + assert len(captured) == 1 + assert captured[0].args.to_dict() == { + 'search': 'web scraper', + 'limit': '2', + 'category': 'AI', + 'username': 'jane', + 'pricingModel': 'FREE', + 'includeUnrunnableActors': 'true', + } + + +def test_search_returns_items_and_applied_limit(httpserver: HTTPServer, sync_client: ApifyClient) -> None: + """`search` returns the Actors and the limit the API applied, without the listing fields.""" + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_json(_SEARCH_RESPONSE) + + result = sync_client.store().search(search='web scraper') + + assert isinstance(result, StoreSearchResult) + assert [actor.id for actor in result.items] == ['actor-id-0', 'actor-id-1'] + assert result.limit == 2 + assert not hasattr(result, 'total') + assert not hasattr(result, 'offset') + + +async def test_search_returns_items_and_applied_limit_async( + httpserver: HTTPServer, async_client: ApifyClientAsync +) -> None: + """Async `search` returns the Actors and the limit the API applied, without the listing fields.""" + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_json(_SEARCH_RESPONSE) + + result = await async_client.store().search(search='web scraper') + + assert isinstance(result, StoreSearchResult) + assert [actor.id for actor in result.items] == ['actor-id-0', 'actor-id-1'] + assert result.limit == 2 + assert not hasattr(result, 'total') + assert not hasattr(result, 'offset') + + +def test_search_rejects_empty_query(httpserver: HTTPServer, sync_client: ApifyClient) -> None: + """`search` raises for an empty query without sending a request.""" + captured: list[Request] = [] + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_handler(capture(captured)) + + with pytest.raises(ValueError, match='must not be empty'): + sync_client.store().search('') + + assert captured == [] + + +async def test_search_rejects_empty_query_async(httpserver: HTTPServer, async_client: ApifyClientAsync) -> None: + """Async `search` raises for an empty query without sending a request.""" + captured: list[Request] = [] + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_handler(capture(captured)) + + with pytest.raises(ValueError, match='must not be empty'): + await async_client.store().search('') + + assert captured == [] + + +@pytest.mark.parametrize( + ('search', 'sort_by', 'message'), + [ + pytest.param('web scraper', None, '`search` argument is deprecated', id='search'), + pytest.param(None, 'popularity', '`sort_by` argument is deprecated', id='sort_by'), + ], +) +def test_list_warns_about_deprecated_argument( + httpserver: HTTPServer, sync_client: ApifyClient, search: str | None, sort_by: str | None, message: str +) -> None: + """`list` warns about a deprecated argument at the caller's line and still sends it.""" + captured: list[Request] = [] + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_handler(capture(captured)) + + with pytest.warns(DeprecationWarning, match=message) as record: + sync_client.store().list(search=search, sort_by=sort_by) + + assert [warning.filename for warning in record] == [__file__] + assert len(captured) == 1 + assert captured[0].args.get('search') == search + assert captured[0].args.get('sortBy') == sort_by + + +@pytest.mark.parametrize( + ('search', 'sort_by', 'message'), + [ + pytest.param('web scraper', None, '`search` argument is deprecated', id='search'), + pytest.param(None, 'popularity', '`sort_by` argument is deprecated', id='sort_by'), + ], +) +async def test_list_warns_about_deprecated_argument_async( + httpserver: HTTPServer, async_client: ApifyClientAsync, search: str | None, sort_by: str | None, message: str +) -> None: + """Async `list` warns about a deprecated argument at the caller's line and still sends it.""" + captured: list[Request] = [] + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_handler(capture(captured)) + + with pytest.warns(DeprecationWarning, match=message) as record: + await async_client.store().list(search=search, sort_by=sort_by) + + assert [warning.filename for warning in record] == [__file__] + assert len(captured) == 1 + assert captured[0].args.get('search') == search + assert captured[0].args.get('sortBy') == sort_by + + +def test_iterate_with_search_requests_a_single_page(httpserver: HTTPServer, sync_client: ApifyClient) -> None: + """`iterate` with the deprecated `search` warns once and yields the single page the API has for a search.""" + captured: list[Request] = [] + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_handler(capture(captured, _SEARCH_RESPONSE)) + + with pytest.warns(DeprecationWarning, match='`search` argument is deprecated') as record: + actors = list(sync_client.store().iterate(search='web scraper')) + + assert [warning.filename for warning in record] == [__file__] + assert [actor.id for actor in actors] == ['actor-id-0', 'actor-id-1'] + assert len(captured) == 1 + + +async def test_iterate_with_search_requests_a_single_page_async( + httpserver: HTTPServer, async_client: ApifyClientAsync +) -> None: + """Async `iterate` with the deprecated `search` warns once and yields the single page the API has for a search.""" + captured: list[Request] = [] + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_handler(capture(captured, _SEARCH_RESPONSE)) + + with pytest.warns(DeprecationWarning, match='`search` argument is deprecated') as record: + actors = [actor async for actor in async_client.store().iterate(search='web scraper')] + + assert [warning.filename for warning in record] == [__file__] + assert [actor.id for actor in actors] == ['actor-id-0', 'actor-id-1'] + assert len(captured) == 1 + + +def test_iterate_with_sort_by_warns_and_still_pages(httpserver: HTTPServer, sync_client: ApifyClient) -> None: + """`iterate` warns about the deprecated `sort_by` at the caller's line and pages as it does without it.""" + captured: list[Request] = [] + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_handler(capture(captured)) + + with pytest.warns(DeprecationWarning, match='`sort_by` argument is deprecated') as record: + actors = list(sync_client.store().iterate(sort_by='popularity')) + + assert [warning.filename for warning in record] == [__file__] + assert actors == [] + assert len(captured) == 1 + + +async def test_iterate_with_sort_by_warns_and_still_pages_async( + httpserver: HTTPServer, async_client: ApifyClientAsync +) -> None: + """Async `iterate` warns about the deprecated `sort_by` at the caller's line and pages as it does without it.""" + captured: list[Request] = [] + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_handler(capture(captured)) + + with pytest.warns(DeprecationWarning, match='`sort_by` argument is deprecated') as record: + actors = [actor async for actor in async_client.store().iterate(sort_by='popularity')] + + assert [warning.filename for warning in record] == [__file__] + assert actors == [] + assert len(captured) == 1 From cdfca69c2d4f00be39b254b68816fa3592f74f64 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 08:18:36 +0000 Subject: [PATCH 2/4] test: drop Store search checks that don't test the client Remove the integration test for a query without matches, which asserts what the API returns for it, and the `hasattr` assertions on the search result, which a dataclass can't fail. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_017ocuAGtCcLFHtTvqReATBj --- tests/integration/test_store.py | 6 ------ tests/unit/test_store_collection_params.py | 8 ++------ 2 files changed, 2 insertions(+), 12 deletions(-) diff --git a/tests/integration/test_store.py b/tests/integration/test_store.py index 32e09d801..d46213a64 100644 --- a/tests/integration/test_store.py +++ b/tests/integration/test_store.py @@ -44,12 +44,6 @@ async def test_store_search_returns_at_most_100_actors(client: ApifyClient | Api assert len(large_result.items) == 100 -async def test_store_search_without_matches(client: ApifyClient | ApifyClientAsync) -> None: - """Test that a store search returns nothing for a query that matches no Actor.""" - result = await maybe_await(client.store().search('qzxjvkwpqzxjvkwp')) - assert result.items == [] - - async def test_store_search_filter_by_username(client: ApifyClient | ApifyClientAsync) -> None: """Test a store search filtered by a known username (apify).""" result = await maybe_await(client.store().search('scraper', limit=10, username='apify')) diff --git a/tests/unit/test_store_collection_params.py b/tests/unit/test_store_collection_params.py index 296137fce..384fb530a 100644 --- a/tests/unit/test_store_collection_params.py +++ b/tests/unit/test_store_collection_params.py @@ -163,7 +163,7 @@ async def test_search_sends_query_and_filters_async(httpserver: HTTPServer, asyn def test_search_returns_items_and_applied_limit(httpserver: HTTPServer, sync_client: ApifyClient) -> None: - """`search` returns the Actors and the limit the API applied, without the listing fields.""" + """`search` returns the Actors and the limit the API applied.""" httpserver.expect_request(_STORE_PATH, method='GET').respond_with_json(_SEARCH_RESPONSE) result = sync_client.store().search(search='web scraper') @@ -171,14 +171,12 @@ def test_search_returns_items_and_applied_limit(httpserver: HTTPServer, sync_cli assert isinstance(result, StoreSearchResult) assert [actor.id for actor in result.items] == ['actor-id-0', 'actor-id-1'] assert result.limit == 2 - assert not hasattr(result, 'total') - assert not hasattr(result, 'offset') async def test_search_returns_items_and_applied_limit_async( httpserver: HTTPServer, async_client: ApifyClientAsync ) -> None: - """Async `search` returns the Actors and the limit the API applied, without the listing fields.""" + """Async `search` returns the Actors and the limit the API applied.""" httpserver.expect_request(_STORE_PATH, method='GET').respond_with_json(_SEARCH_RESPONSE) result = await async_client.store().search(search='web scraper') @@ -186,8 +184,6 @@ async def test_search_returns_items_and_applied_limit_async( assert isinstance(result, StoreSearchResult) assert [actor.id for actor in result.items] == ['actor-id-0', 'actor-id-1'] assert result.limit == 2 - assert not hasattr(result, 'total') - assert not hasattr(result, 'offset') def test_search_rejects_empty_query(httpserver: HTTPServer, sync_client: ApifyClient) -> None: From ceac546bdf4e9cb38d49414a484f213a532c7048 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 09:22:01 +0000 Subject: [PATCH 3/4] fix: address review of the Store search split - Every page request of `iterate` sets the log context again, as it did when the callback went through the wrapped `list`. A client call between two pages no longer leaves its method name and resource ID on the next page request. - An empty `search` gets no deprecation warning, since it is not a search and the `search` method rejects it. - `StoreActor` is imported at runtime, so the annotations of `StoreSearchResult` resolve. - The `iterate` docstring says that `offset` and `chunk_size` have no effect with the deprecated `search`, the helper explains its `stacklevel`, and the docstrings write Apify Store as a proper noun. - Tests: the single-page test fails fast on a regression, the `sort_by` test proves a second page is requested, and the integration tests no longer expect exact item counts from the live search. - Docs: a "Search Apify Store" section with sync and async examples. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_017ocuAGtCcLFHtTvqReATBj --- docs/02_concepts/08_pagination.mdx | 30 ++++- .../02_concepts/code/08_store_search_async.py | 17 +++ docs/02_concepts/code/08_store_search_sync.py | 21 ++++ .../_resource_clients/store_collection.py | 68 ++++++----- tests/integration/test_store.py | 14 +-- tests/unit/test_store_collection_params.py | 107 +++++++++++++++--- 6 files changed, 203 insertions(+), 54 deletions(-) create mode 100644 docs/02_concepts/code/08_store_search_async.py create mode 100644 docs/02_concepts/code/08_store_search_sync.py diff --git a/docs/02_concepts/08_pagination.mdx b/docs/02_concepts/08_pagination.mdx index 980ed51ab..460e0fe40 100644 --- a/docs/02_concepts/08_pagination.mdx +++ b/docs/02_concepts/08_pagination.mdx @@ -16,6 +16,8 @@ import IterateItemsAsyncExample from '!!raw-loader!./code/08_iterate_items_async import IterateItemsSyncExample from '!!raw-loader!./code/08_iterate_items_sync.py'; import IterateCollectionAsyncExample from '!!raw-loader!./code/08_iterate_collection_async.py'; import IterateCollectionSyncExample from '!!raw-loader!./code/08_iterate_collection_sync.py'; +import StoreSearchAsyncExample from '!!raw-loader!./code/08_store_search_async.py'; +import StoreSearchSyncExample from '!!raw-loader!./code/08_store_search_sync.py'; Most methods named `list` or `list_something` in the Apify client return a page model — a [Pydantic](https://docs.pydantic.dev/latest/) model such as `ListOfActors` or `ListOfDatasets`. Unstructured dataset items use the `DatasetItemsPage` dataclass instead. All page models share a consistent interface for working with paginated data and expose the following fields: @@ -27,7 +29,7 @@ Most methods named `list` or `list_something` in the Apify client return a page On `DatasetItemsPage`, `count` reports how many dataset rows the API scanned for the page. Filters drop items from a page and `unwind` multiplies them, so a page can hold fewer or more items than `count`. -Some methods paginate differently. For example, `RequestQueueClient.list_requests` returns a cursor-based `ListOfRequests` without the `total`, `offset`, and `count` fields. To fetch the next page, pass its `next_cursor` value back as the `cursor` parameter. Other examples include `list_keys` and `list_head`. `StoreCollectionClient.search` doesn't paginate at all: it returns the Actors that match a query best, 100 at most, as a `StoreSearchResult` without the `total`, `offset`, and `count` fields, and there is no next page. Regardless, the primary results are always stored under the `items` field, and the `limit` field can be used to control the number of results returned. +Some methods paginate differently. For example, `RequestQueueClient.list_requests` returns a cursor-based `ListOfRequests` without the `total`, `offset`, and `count` fields. To fetch the next page, pass its `next_cursor` value back as the `cursor` parameter. Other examples include `list_keys` and `list_head`. `StoreCollectionClient.search` doesn't paginate at all. For details, see [Search Apify Store](#search-apify-store). Regardless, the primary results are always stored under the `items` field, and the `limit` field can be used to control the number of results returned. The following example shows how to fetch all items from a dataset using pagination: @@ -89,3 +91,29 @@ The next example uses `iterate_items` on a dataset client to stream items past a To read the items of a run that's still going, use `RunClient.iterate_dataset_items`. Its `offset` and `limit` also count dataset rows. For details, see [Retrieve Actor data](/api/client/python/docs/guides/retrieve-actor-data#read-items-while-the-run-is-going). + +## Search Apify Store + +`StoreCollectionClient.list` and `StoreCollectionClient.iterate` go through all Actors in [Apify Store](https://apify.com/store), page by page, in Store order. To find Actors by a text query, use `StoreCollectionClient.search` instead. + +A search isn't paginated. The API returns the Actors that match the query best as a single page of at most 100 Actors, ordered by relevance. There is no next page and no `offset`, and the API doesn't report how many Actors match in total. The method therefore returns a `StoreSearchResult` with two fields: + +- `items` - The matching Actors, best match first. +- `limit` - The limit the API applied. It's the `limit` you passed, or 100 if you passed more or none. + +When `items` holds as many Actors as `limit`, more Actors may match than were returned. To narrow the result, use a more specific query or the `category`, `username`, and `pricing_model` filters. + + + + + {StoreSearchAsyncExample} + + + + + {StoreSearchSyncExample} + + + + +The `search` and `sort_by` arguments of `list` and `iterate` are deprecated and will be removed in v4. The API ignores `sort_by`, and `search` moved to the `search` method. diff --git a/docs/02_concepts/code/08_store_search_async.py b/docs/02_concepts/code/08_store_search_async.py new file mode 100644 index 000000000..538544f84 --- /dev/null +++ b/docs/02_concepts/code/08_store_search_async.py @@ -0,0 +1,17 @@ +from apify_client import ApifyClientAsync + +TOKEN = 'MY-APIFY-TOKEN' + + +async def main() -> None: + apify_client = ApifyClientAsync(TOKEN) + + # Search returns the best matches as a single page of at most 100 Actors. + result = await apify_client.store().search('instagram posts', limit=10) + + for actor in result.items: + print(f'{actor.username}/{actor.name}') + + # With as many Actors as the applied limit, more Actors may match the query. + if len(result.items) == result.limit: + print('The result may be cut off. Narrow the search with a filter.') diff --git a/docs/02_concepts/code/08_store_search_sync.py b/docs/02_concepts/code/08_store_search_sync.py new file mode 100644 index 000000000..a756e3004 --- /dev/null +++ b/docs/02_concepts/code/08_store_search_sync.py @@ -0,0 +1,21 @@ +from apify_client import ApifyClient + +TOKEN = 'MY-APIFY-TOKEN' + + +def main() -> None: + apify_client = ApifyClient(TOKEN) + + # Search returns the best matches as a single page of at most 100 Actors. + result = apify_client.store().search('instagram posts', limit=10) + + for actor in result.items: + print(f'{actor.username}/{actor.name}') + + # With as many Actors as the applied limit, more Actors may match the query. + if len(result.items) == result.limit: + print('The result may be cut off. Narrow the search with a filter.') + + +if __name__ == '__main__': + main() diff --git a/src/apify_client/_resource_clients/store_collection.py b/src/apify_client/_resource_clients/store_collection.py index b9906ac8a..421b38bf6 100644 --- a/src/apify_client/_resource_clients/store_collection.py +++ b/src/apify_client/_resource_clients/store_collection.py @@ -5,7 +5,8 @@ from typing import TYPE_CHECKING, Any from apify_client._docs import docs_group -from apify_client._models import ListOfStoreActors, ListOfStoreActorsResponse +from apify_client._logging import _set_client_details +from apify_client._models import ListOfStoreActors, ListOfStoreActorsResponse, StoreActor from apify_client._pagination import get_items_iterator, get_items_iterator_async from apify_client._resource_clients._resource_client import ResourceClient, ResourceClientAsync from apify_client._utils.http import validate_response @@ -13,7 +14,6 @@ if TYPE_CHECKING: from collections.abc import AsyncIterator, Awaitable, Callable, Iterator - from apify_client._models import StoreActor from apify_client.types import Timeout @@ -22,8 +22,8 @@ class StoreSearchResult: """The single page of Actors returned by the `search` method. - The API answers a store search with one page of the best matches. It reports the number of Actors returned as - the total and zero as the offset, whatever the query matches, so this class has no `total`, `offset` or `count`. + The API answers an Apify Store search with one page of the best matches. It reports the number of Actors returned + as the total and zero as the offset, whatever the query matches, so this class has no `total`, `offset` or `count`. """ items: list[StoreActor] @@ -38,29 +38,35 @@ class StoreSearchResult: def _warn_about_deprecated_arguments(*, search: str | None, sort_by: str | None) -> None: - """Emit a `DeprecationWarning` for each deprecated argument that is set, pointing at the caller of the method.""" - if search is not None: + """Emit a `DeprecationWarning` for each deprecated argument that is set, pointing at the caller of the method. + + An empty `search` is not a search, so it gets no warning: the API answers it with the Store listing, and the + `search` method rejects it. + """ + # The frames up to the caller are this helper, the public method and its `WithLogDetailsClient` wrapper. + stacklevel = 4 + if search: warnings.warn( 'The `search` argument is deprecated and will be removed in v4. Use the `search` method instead.', DeprecationWarning, - stacklevel=4, + stacklevel=stacklevel, ) if sort_by is not None: warnings.warn( 'The `sort_by` argument is deprecated and will be removed in v4. The API ignores it.', DeprecationWarning, - stacklevel=4, + stacklevel=stacklevel, ) def _validate_search_query(search: str) -> None: - """Reject an empty query, which the API answers with the store listing. + """Reject an empty query, which the API answers with the Store listing. Raises: ValueError: If `search` is empty. """ if not search: - raise ValueError('`search` must not be empty. To go through the store without a query, use `list`.') + raise ValueError('`search` must not be empty. To go through the Store without a query, use `list`.') def _iterate_page(get_page: Callable[[], ListOfStoreActors]) -> Iterator[StoreActor]: @@ -78,9 +84,9 @@ async def _iterate_page_async(get_page: Callable[[], Awaitable[ListOfStoreActors @docs_group('Resource clients') class StoreCollectionClient(ResourceClient): - """Sub-client for the Apify store collection. + """Sub-client for the Apify Store collection. - Provides methods to browse the Apify store, e.g. list available Actors or search them. Obtain an instance via an + Provides methods to browse the Apify Store, e.g. list available Actors or search them. Obtain an instance via an appropriate method on the `ApifyClient` class. """ @@ -108,7 +114,7 @@ def list( include_unrunnable_actors: bool | None = None, timeout: Timeout = 'medium', ) -> ListOfStoreActors: - """List Actors in Apify store, ordered by their position in the store. + """List Actors in Apify Store, ordered by their position in the Store. https://docs.apify.com/api/v2/#/reference/store/store-actors-collection/get-list-of-actors-in-store @@ -157,7 +163,7 @@ def iterate( chunk_size: int | None = None, timeout: Timeout = 'medium', ) -> Iterator[StoreActor]: - """Iterate over Actors in Apify store, ordered by their position in the store. + """Iterate over Actors in Apify Store, ordered by their position in the Store. Simple `list` does only one API call, possibly not listing all items matching the criteria. This method returns an iterator that is capable of making multiple API calls to retrieve all items matching the criteria. @@ -168,7 +174,8 @@ def iterate( limit: How many Actors to list. offset: What Actor to include as first when retrieving the list. search: Deprecated. Use the `search` method. With this argument, the iterator makes a single API call and - yields the best matches, at most 100 Actors, as the API has no further page of a search. + yields the best matches, at most 100 Actors, as the API has no further page of a search. `offset` and + `chunk_size` have no effect then. sort_by: Deprecated. The API ignores this argument. category: Filter by this category. username: Filter by this username. @@ -180,11 +187,13 @@ def iterate( timeout: Timeout for the API HTTP request. Yields: - The Actors in the store matching the specified filters. + The Actors in the Store matching the specified filters. """ _warn_about_deprecated_arguments(search=search, sort_by=sort_by) def _callback(*, limit: int | None = None, offset: int | None = None) -> ListOfStoreActors: + # Another client call between two pages overwrites the log context, so every page request sets it again. + _set_client_details(StoreCollectionClient.list, self) return self._list_actors( limit=limit, offset=offset, @@ -214,12 +223,12 @@ def search( include_unrunnable_actors: bool | None = None, timeout: Timeout = 'medium', ) -> StoreSearchResult: - """Search Apify store and return the Actors that match the query best, ordered by relevance. + """Search Apify Store and return the Actors that match the query best, ordered by relevance. The API answers a search with a single page of at most 100 Actors. There is no next page and no way to skip results, and the API does not report how many Actors match the query in total. A result holding as many Actors as its `limit` can therefore be cut off: narrow it down with a more specific query or with the - `category`, `username` and `pricing_model` filters. To go through the whole store, use `list` or `iterate`. + `category`, `username` and `pricing_model` filters. To go through the whole Store, use `list` or `iterate`. https://docs.apify.com/api/v2/#/reference/store/store-actors-collection/get-list-of-actors-in-store @@ -266,7 +275,7 @@ def _list_actors( include_unrunnable_actors: bool | None = None, timeout: Timeout, ) -> ListOfStoreActors: - """Request one page of store Actors, which the API fills by search when `search` is set.""" + """Request one page of Store Actors, which the API fills by search when `search` is set.""" result = self._list( timeout=timeout, limit=limit, @@ -283,9 +292,9 @@ def _list_actors( @docs_group('Resource clients') class StoreCollectionClientAsync(ResourceClientAsync): - """Sub-client for the Apify store collection. + """Sub-client for the Apify Store collection. - Provides methods to browse the Apify store, e.g. list available Actors or search them. Obtain an instance via an + Provides methods to browse the Apify Store, e.g. list available Actors or search them. Obtain an instance via an appropriate method on the `ApifyClientAsync` class. """ @@ -313,7 +322,7 @@ async def list( include_unrunnable_actors: bool | None = None, timeout: Timeout = 'medium', ) -> ListOfStoreActors: - """List Actors in Apify store, ordered by their position in the store. + """List Actors in Apify Store, ordered by their position in the Store. https://docs.apify.com/api/v2/#/reference/store/store-actors-collection/get-list-of-actors-in-store @@ -362,7 +371,7 @@ def iterate( chunk_size: int | None = None, timeout: Timeout = 'medium', ) -> AsyncIterator[StoreActor]: - """Iterate over Actors in Apify store, ordered by their position in the store. + """Iterate over Actors in Apify Store, ordered by their position in the Store. Simple `list` does only one API call, possibly not listing all items matching the criteria. This method returns an iterator that is capable of making multiple API calls to retrieve all items matching the criteria. @@ -373,7 +382,8 @@ def iterate( limit: How many Actors to list. offset: What Actor to include as first when retrieving the list. search: Deprecated. Use the `search` method. With this argument, the iterator makes a single API call and - yields the best matches, at most 100 Actors, as the API has no further page of a search. + yields the best matches, at most 100 Actors, as the API has no further page of a search. `offset` and + `chunk_size` have no effect then. sort_by: Deprecated. The API ignores this argument. category: Filter by this category. username: Filter by this username. @@ -385,11 +395,13 @@ def iterate( timeout: Timeout for the API HTTP request. Yields: - The Actors in the store matching the specified filters. + The Actors in the Store matching the specified filters. """ _warn_about_deprecated_arguments(search=search, sort_by=sort_by) async def _callback(*, limit: int | None = None, offset: int | None = None) -> ListOfStoreActors: + # Another client call between two pages overwrites the log context, so every page request sets it again. + _set_client_details(StoreCollectionClientAsync.list, self) return await self._list_actors( limit=limit, offset=offset, @@ -419,12 +431,12 @@ async def search( include_unrunnable_actors: bool | None = None, timeout: Timeout = 'medium', ) -> StoreSearchResult: - """Search Apify store and return the Actors that match the query best, ordered by relevance. + """Search Apify Store and return the Actors that match the query best, ordered by relevance. The API answers a search with a single page of at most 100 Actors. There is no next page and no way to skip results, and the API does not report how many Actors match the query in total. A result holding as many Actors as its `limit` can therefore be cut off: narrow it down with a more specific query or with the - `category`, `username` and `pricing_model` filters. To go through the whole store, use `list` or `iterate`. + `category`, `username` and `pricing_model` filters. To go through the whole Store, use `list` or `iterate`. https://docs.apify.com/api/v2/#/reference/store/store-actors-collection/get-list-of-actors-in-store @@ -471,7 +483,7 @@ async def _list_actors( include_unrunnable_actors: bool | None = None, timeout: Timeout, ) -> ListOfStoreActors: - """Request one page of store Actors, which the API fills by search when `search` is set.""" + """Request one page of Store Actors, which the API fills by search when `search` is set.""" result = await self._list( timeout=timeout, limit=limit, diff --git a/tests/integration/test_store.py b/tests/integration/test_store.py index d46213a64..3134892cc 100644 --- a/tests/integration/test_store.py +++ b/tests/integration/test_store.py @@ -27,8 +27,7 @@ async def test_store_search(client: ApifyClient | ApifyClientAsync) -> None: """Test that a store search returns the best matches as one page.""" result = await maybe_await(client.store().search('web scraper', limit=5)) assert isinstance(result, StoreSearchResult) - # The public store holds thousands of scrapers, so the page is always full. - assert len(result.items) == 5 + assert 0 < len(result.items) <= 5 assert result.limit == 5 for actor in result.items: assert isinstance(actor, StoreActor) @@ -39,9 +38,9 @@ async def test_store_search_returns_at_most_100_actors(client: ApifyClient | Api default_result = await maybe_await(client.store().search('scraper')) large_result = await maybe_await(client.store().search('scraper', limit=1000)) assert default_result.limit == 100 - assert len(default_result.items) == 100 + assert 0 < len(default_result.items) <= 100 assert large_result.limit == 100 - assert len(large_result.items) == 100 + assert 0 < len(large_result.items) <= 100 async def test_store_search_filter_by_username(client: ApifyClient | ApifyClientAsync) -> None: @@ -57,7 +56,7 @@ async def test_store_list_with_deprecated_search(client: ApifyClient | ApifyClie with pytest.warns(DeprecationWarning, match='`search` argument is deprecated'): store_page = await maybe_await(client.store().list(limit=5, search='web scraper')) assert isinstance(store_page, ListOfStoreActors) - assert len(store_page.items) == 5 + assert 0 < len(store_page.items) <= 5 async def test_store_iterate_with_deprecated_search(client: ApifyClient | ApifyClientAsync, *, is_async: bool) -> None: @@ -71,8 +70,9 @@ async def test_store_iterate_with_deprecated_search(client: ApifyClient | ApifyC assert isinstance(iterator, Iterator) collected = list(iterator) - assert len(collected) == 100 - assert len({actor.id for actor in collected}) == 100 + assert 0 < len(collected) <= 100 + actor_ids = {actor.id for actor in collected} + assert len(actor_ids) == len(collected) async def test_store_list_pagination(client: ApifyClient | ApifyClientAsync) -> None: diff --git a/tests/unit/test_store_collection_params.py b/tests/unit/test_store_collection_params.py index 384fb530a..b828217f4 100644 --- a/tests/unit/test_store_collection_params.py +++ b/tests/unit/test_store_collection_params.py @@ -1,11 +1,14 @@ from __future__ import annotations import json +import logging +import warnings from typing import TYPE_CHECKING, Any import pytest from werkzeug import Request, Response +from apify_client._logging import logger_name from apify_client._resource_clients.store_collection import StoreSearchResult if TYPE_CHECKING: @@ -41,9 +44,9 @@ for index in range(2) ] -# The API answers a search with the same full page whatever `offset` it is sent, and reports the number of Actors -# returned as `total`. -_SEARCH_RESPONSE = { +# A full page of two Actors, served for every request. The API answers a search this way: with the same page +# whatever `offset` it is sent, and with the number of Actors returned as `total`. +_FULL_PAGE_RESPONSE = { 'data': { 'total': 2, 'offset': 0, @@ -115,7 +118,7 @@ async def test_iterate_sends_include_unrunnable_actors_async( def test_search_sends_query_and_filters(httpserver: HTTPServer, sync_client: ApifyClient) -> None: """`search` sends one request with the query, the limit and the filters, and no offset.""" captured: list[Request] = [] - httpserver.expect_request(_STORE_PATH, method='GET').respond_with_handler(capture(captured, _SEARCH_RESPONSE)) + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_handler(capture(captured, _FULL_PAGE_RESPONSE)) sync_client.store().search( 'web scraper', @@ -140,7 +143,7 @@ def test_search_sends_query_and_filters(httpserver: HTTPServer, sync_client: Api async def test_search_sends_query_and_filters_async(httpserver: HTTPServer, async_client: ApifyClientAsync) -> None: """Async `search` sends one request with the query, the limit and the filters, and no offset.""" captured: list[Request] = [] - httpserver.expect_request(_STORE_PATH, method='GET').respond_with_handler(capture(captured, _SEARCH_RESPONSE)) + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_handler(capture(captured, _FULL_PAGE_RESPONSE)) await async_client.store().search( 'web scraper', @@ -164,7 +167,7 @@ async def test_search_sends_query_and_filters_async(httpserver: HTTPServer, asyn def test_search_returns_items_and_applied_limit(httpserver: HTTPServer, sync_client: ApifyClient) -> None: """`search` returns the Actors and the limit the API applied.""" - httpserver.expect_request(_STORE_PATH, method='GET').respond_with_json(_SEARCH_RESPONSE) + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_json(_FULL_PAGE_RESPONSE) result = sync_client.store().search(search='web scraper') @@ -177,7 +180,7 @@ async def test_search_returns_items_and_applied_limit_async( httpserver: HTTPServer, async_client: ApifyClientAsync ) -> None: """Async `search` returns the Actors and the limit the API applied.""" - httpserver.expect_request(_STORE_PATH, method='GET').respond_with_json(_SEARCH_RESPONSE) + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_json(_FULL_PAGE_RESPONSE) result = await async_client.store().search(search='web scraper') @@ -257,10 +260,11 @@ async def test_list_warns_about_deprecated_argument_async( def test_iterate_with_search_requests_a_single_page(httpserver: HTTPServer, sync_client: ApifyClient) -> None: """`iterate` with the deprecated `search` warns once and yields the single page the API has for a search.""" captured: list[Request] = [] - httpserver.expect_request(_STORE_PATH, method='GET').respond_with_handler(capture(captured, _SEARCH_RESPONSE)) + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_handler(capture(captured, _FULL_PAGE_RESPONSE)) + # The limit leaves room for a second page, so an iterator that pages a search sends two requests. with pytest.warns(DeprecationWarning, match='`search` argument is deprecated') as record: - actors = list(sync_client.store().iterate(search='web scraper')) + actors = list(sync_client.store().iterate(search='web scraper', limit=4)) assert [warning.filename for warning in record] == [__file__] assert [actor.id for actor in actors] == ['actor-id-0', 'actor-id-1'] @@ -272,10 +276,11 @@ async def test_iterate_with_search_requests_a_single_page_async( ) -> None: """Async `iterate` with the deprecated `search` warns once and yields the single page the API has for a search.""" captured: list[Request] = [] - httpserver.expect_request(_STORE_PATH, method='GET').respond_with_handler(capture(captured, _SEARCH_RESPONSE)) + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_handler(capture(captured, _FULL_PAGE_RESPONSE)) + # The limit leaves room for a second page, so an iterator that pages a search sends two requests. with pytest.warns(DeprecationWarning, match='`search` argument is deprecated') as record: - actors = [actor async for actor in async_client.store().iterate(search='web scraper')] + actors = [actor async for actor in async_client.store().iterate(search='web scraper', limit=4)] assert [warning.filename for warning in record] == [__file__] assert [actor.id for actor in actors] == ['actor-id-0', 'actor-id-1'] @@ -285,14 +290,14 @@ async def test_iterate_with_search_requests_a_single_page_async( def test_iterate_with_sort_by_warns_and_still_pages(httpserver: HTTPServer, sync_client: ApifyClient) -> None: """`iterate` warns about the deprecated `sort_by` at the caller's line and pages as it does without it.""" captured: list[Request] = [] - httpserver.expect_request(_STORE_PATH, method='GET').respond_with_handler(capture(captured)) + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_handler(capture(captured, _FULL_PAGE_RESPONSE)) with pytest.warns(DeprecationWarning, match='`sort_by` argument is deprecated') as record: - actors = list(sync_client.store().iterate(sort_by='popularity')) + actors = list(sync_client.store().iterate(sort_by='popularity', limit=4)) assert [warning.filename for warning in record] == [__file__] - assert actors == [] - assert len(captured) == 1 + assert len(actors) == 4 + assert [request.args.get('offset') for request in captured] == ['0', '2'] async def test_iterate_with_sort_by_warns_and_still_pages_async( @@ -300,11 +305,77 @@ async def test_iterate_with_sort_by_warns_and_still_pages_async( ) -> None: """Async `iterate` warns about the deprecated `sort_by` at the caller's line and pages as it does without it.""" captured: list[Request] = [] - httpserver.expect_request(_STORE_PATH, method='GET').respond_with_handler(capture(captured)) + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_handler(capture(captured, _FULL_PAGE_RESPONSE)) with pytest.warns(DeprecationWarning, match='`sort_by` argument is deprecated') as record: - actors = [actor async for actor in async_client.store().iterate(sort_by='popularity')] + actors = [actor async for actor in async_client.store().iterate(sort_by='popularity', limit=4)] assert [warning.filename for warning in record] == [__file__] + assert len(actors) == 4 + assert [request.args.get('offset') for request in captured] == ['0', '2'] + + +def test_empty_search_is_not_deprecated(httpserver: HTTPServer, sync_client: ApifyClient) -> None: + """`list` and `iterate` don't warn about an empty `search`, which the API answers with the listing.""" + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_json(_STORE_RESPONSE) + + with warnings.catch_warnings(): + warnings.simplefilter('error', DeprecationWarning) + sync_client.store().list(search='') + actors = list(sync_client.store().iterate(search='')) + assert actors == [] - assert len(captured) == 1 + + +async def test_empty_search_is_not_deprecated_async(httpserver: HTTPServer, async_client: ApifyClientAsync) -> None: + """Async `list` and `iterate` don't warn about an empty `search`, which the API answers with the listing.""" + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_json(_STORE_RESPONSE) + + with warnings.catch_warnings(): + warnings.simplefilter('error', DeprecationWarning) + await async_client.store().list(search='') + actors = [actor async for actor in async_client.store().iterate(search='')] + + assert actors == [] + + +def test_iterate_page_requests_keep_their_log_context( + httpserver: HTTPServer, sync_client: ApifyClient, caplog: pytest.LogCaptureFixture +) -> None: + """`iterate` logs every page request as a Store listing, also after another client call between two pages.""" + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_json(_FULL_PAGE_RESPONSE) + iterator = sync_client.store().iterate(limit=4) + + with caplog.at_level(logging.DEBUG, logger=logger_name): + next(iterator) + sync_client.store().search('web scraper') + list(iterator) + + requests = [record for record in caplog.records if record.getMessage() == 'Request successful'] + client_methods = [record.__dict__['client_method'] for record in requests] + assert client_methods == [ + 'StoreCollectionClient.list', + 'StoreCollectionClient.search', + 'StoreCollectionClient.list', + ] + + +async def test_iterate_page_requests_keep_their_log_context_async( + httpserver: HTTPServer, async_client: ApifyClientAsync, caplog: pytest.LogCaptureFixture +) -> None: + """Async `iterate` logs every page request as a Store listing, also after another client call between two pages.""" + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_json(_FULL_PAGE_RESPONSE) + iterator = async_client.store().iterate(limit=4) + + with caplog.at_level(logging.DEBUG, logger=logger_name): + await anext(iterator) + await async_client.store().search('web scraper') + _ = [actor async for actor in iterator] + + requests = [record for record in caplog.records if record.getMessage() == 'Request successful'] + client_methods = [record.__dict__['client_method'] for record in requests] + assert client_methods == [ + 'StoreCollectionClientAsync.list', + 'StoreCollectionClientAsync.search', + 'StoreCollectionClientAsync.list', + ] From 422415a84b5d079ceebed84695c54da8ef44b1c7 Mon Sep 17 00:00:00 2001 From: Vlada Dusek Date: Wed, 2 Dec 2026 12:43:04 +0100 Subject: [PATCH 4/4] docs: capitalize Apify Store in the remaining docstrings --- src/apify_client/_apify_client.py | 4 ++-- tests/integration/test_store.py | 24 ++++++++++++------------ 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/src/apify_client/_apify_client.py b/src/apify_client/_apify_client.py index 5936aa945..c7b930da7 100644 --- a/src/apify_client/_apify_client.py +++ b/src/apify_client/_apify_client.py @@ -464,7 +464,7 @@ def user(self, user_id: str | None = None) -> UserClient: return UserClient(resource_id=user_id, **self._base_kwargs) def store(self) -> StoreCollectionClient: - """Get the sub-client for the Apify Store, allowing to list Actors published in the store.""" + """Get the sub-client for the Apify Store, allowing to list and search Actors published in the Store.""" return StoreCollectionClient(**self._base_kwargs) @@ -854,5 +854,5 @@ def user(self, user_id: str | None = None) -> UserClientAsync: return UserClientAsync(resource_id=user_id, **self._base_kwargs) def store(self) -> StoreCollectionClientAsync: - """Get the sub-client for the Apify Store, allowing to list Actors published in the store.""" + """Get the sub-client for the Apify Store, allowing to list and search Actors published in the Store.""" return StoreCollectionClientAsync(**self._base_kwargs) diff --git a/tests/integration/test_store.py b/tests/integration/test_store.py index 3134892cc..576cdf0ad 100644 --- a/tests/integration/test_store.py +++ b/tests/integration/test_store.py @@ -1,4 +1,4 @@ -"""Unified tests for store (sync + async).""" +"""Unified tests for Apify Store (sync + async).""" from __future__ import annotations @@ -16,15 +16,15 @@ async def test_store_list(client: ApifyClient | ApifyClientAsync) -> None: - """Test listing public Actors in the store.""" + """Test listing public Actors in the Store.""" actors_list = await maybe_await(client.store().list(limit=10)) assert isinstance(actors_list, ListOfStoreActors) assert actors_list.items is not None - assert len(actors_list.items) > 0 # Store always has actors + assert len(actors_list.items) > 0 # Store always has Actors async def test_store_search(client: ApifyClient | ApifyClientAsync) -> None: - """Test that a store search returns the best matches as one page.""" + """Test that a Store search returns the best matches as one page.""" result = await maybe_await(client.store().search('web scraper', limit=5)) assert isinstance(result, StoreSearchResult) assert 0 < len(result.items) <= 5 @@ -34,7 +34,7 @@ async def test_store_search(client: ApifyClient | ApifyClientAsync) -> None: async def test_store_search_returns_at_most_100_actors(client: ApifyClient | ApifyClientAsync) -> None: - """Test that a store search returns at most 100 Actors, whatever limit it is asked for.""" + """Test that a Store search returns at most 100 Actors, whatever limit it is asked for.""" default_result = await maybe_await(client.store().search('scraper')) large_result = await maybe_await(client.store().search('scraper', limit=1000)) assert default_result.limit == 100 @@ -44,7 +44,7 @@ async def test_store_search_returns_at_most_100_actors(client: ApifyClient | Api async def test_store_search_filter_by_username(client: ApifyClient | ApifyClientAsync) -> None: - """Test a store search filtered by a known username (apify).""" + """Test a Store search filtered by a known username (apify).""" result = await maybe_await(client.store().search('scraper', limit=10, username='apify')) assert len(result.items) > 0 for actor in result.items: @@ -52,7 +52,7 @@ async def test_store_search_filter_by_username(client: ApifyClient | ApifyClient async def test_store_list_with_deprecated_search(client: ApifyClient | ApifyClientAsync) -> None: - """Test that the store listing still accepts the deprecated `search` and returns the search page.""" + """Test that the Store listing still accepts the deprecated `search` and returns the search page.""" with pytest.warns(DeprecationWarning, match='`search` argument is deprecated'): store_page = await maybe_await(client.store().list(limit=5, search='web scraper')) assert isinstance(store_page, ListOfStoreActors) @@ -76,7 +76,7 @@ async def test_store_iterate_with_deprecated_search(client: ApifyClient | ApifyC async def test_store_list_pagination(client: ApifyClient | ApifyClientAsync) -> None: - """Test store listing pagination.""" + """Test Store listing pagination.""" page1 = await maybe_await(client.store().list(limit=5, offset=0)) page2 = await maybe_await(client.store().list(limit=5, offset=5)) assert isinstance(page1, ListOfStoreActors) @@ -88,7 +88,7 @@ async def test_store_list_pagination(client: ApifyClient | ApifyClientAsync) -> @pytest.mark.parametrize('pricing_model', ['FREE', 'FLAT_PRICE_PER_MONTH', 'PRICE_PER_DATASET_ITEM', 'PAY_PER_EVENT']) async def test_store_list_filter_by_pricing_model(client: ApifyClient | ApifyClientAsync, pricing_model: str) -> None: - """Test listing store actors filtered by each supported pricing model. + """Test listing Store Actors filtered by each supported pricing model. This exercises both the filter parameter and the Pydantic models that parse the responses for each pricing variant. @@ -105,7 +105,7 @@ async def test_store_list_filter_by_pricing_model(client: ApifyClient | ApifyCli async def test_store_list_filter_by_username(client: ApifyClient | ApifyClientAsync) -> None: - """Test listing store actors filtered by a known username (apify).""" + """Test listing Store Actors filtered by a known username (apify).""" page = await maybe_await(client.store().list(limit=10, username='apify')) assert isinstance(page, ListOfStoreActors) assert len(page.items) > 0 @@ -114,7 +114,7 @@ async def test_store_list_filter_by_username(client: ApifyClient | ApifyClientAs async def test_store_list_accepts_sort_by(client: ApifyClient | ApifyClientAsync) -> None: - """Test that the store listing accepts the deprecated `sort_by`. + """Test that the Store listing accepts the deprecated `sort_by`. The API accepts `sortBy` for compatibility but ignores it, so the order is not asserted. """ @@ -125,7 +125,7 @@ async def test_store_list_accepts_sort_by(client: ApifyClient | ApifyClientAsync async def test_store_iterate(client: ApifyClient | ApifyClientAsync, *, is_async: bool) -> None: - """Test paginated iteration over store Actors.""" + """Test paginated iteration over Store Actors.""" iterator = client.store().iterate(limit=20) collected: list[StoreActor] = [] if is_async: