Skip to content

AsyncClient API

AsyncClient

High-level async client for Google Play Store scraping.

This client combines async I/O (aiohttp) for network requests with Rust-powered CPU-intensive parsing for maximum performance.

Examples:

>>> import asyncio
>>> async def test_basic():
...     async with AsyncClient() as client:
...         app = await client.get_app("com.spotify.music")
...         return app.title
>>> asyncio.run(test_basic())
'Spotify: Music and Podcasts'
>>> async def test_parallel():
...     async with AsyncClient(max_concurrent=50) as client:
...         results = await client.get_apps_parallel(
...             ["com.spotify.music", "com.netflix.mediaclient"], countries=["us", "kr"]
...         )
...         return len(results)
>>> asyncio.run(test_parallel())
2

Parameters:

Name Type Description Default
max_concurrent int

Maximum concurrent HTTP requests (default: 10)

10
timeout int

Request timeout in seconds (default: 30)

30
headers dict[str, str] | None

Custom HTTP headers (default: Chrome user agent)

None
lang str

Default language code (default: "en")

'en'
Source code in python/playfast/client.py
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
class AsyncClient:
    """High-level async client for Google Play Store scraping.

    This client combines async I/O (aiohttp) for network requests with
    Rust-powered CPU-intensive parsing for maximum performance.

    Examples:
        >>> import asyncio
        >>> async def test_basic():
        ...     async with AsyncClient() as client:
        ...         app = await client.get_app("com.spotify.music")
        ...         return app.title
        >>> asyncio.run(test_basic())
        'Spotify: Music and Podcasts'

        >>> async def test_parallel():
        ...     async with AsyncClient(max_concurrent=50) as client:
        ...         results = await client.get_apps_parallel(
        ...             ["com.spotify.music", "com.netflix.mediaclient"], countries=["us", "kr"]
        ...         )
        ...         return len(results)
        >>> asyncio.run(test_parallel())
        2

    Args:
        max_concurrent: Maximum concurrent HTTP requests (default: 10)
        timeout: Request timeout in seconds (default: 30)
        headers: Custom HTTP headers (default: Chrome user agent)
        lang: Default language code (default: "en")

    """

    BASE_URL = "https://play.google.com"

    def __init__(
        self,
        max_concurrent: int = 10,
        timeout: int = 30,
        headers: dict[str, str] | None = None,
        lang: str = "en",
    ) -> None:
        """Initialize the async client."""
        self.max_concurrent = max_concurrent
        self.timeout = timeout
        self.lang = lang

        # Default headers (mimic Chrome browser)
        self._headers = headers or {
            "User-Agent": (
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
                "AppleWebKit/537.36 (KHTML, like Gecko) "
                "Chrome/131.0.0.0 Safari/537.36"
            ),
            "Accept-Language": f"{lang},en-US;q=0.9,en;q=0.8",
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
        }

        self._session: aiohttp.ClientSession | None = None
        self._semaphore = asyncio.Semaphore(max_concurrent)

    async def __aenter__(self) -> "AsyncClient":
        """Async context manager entry."""
        timeout_config = aiohttp.ClientTimeout(total=self.timeout)

        # Use default connector (already optimized by aiohttp)
        # Custom settings can add overhead for high-concurrency scenarios
        self._session = aiohttp.ClientSession(
            timeout=timeout_config,
            headers=self._headers,
        )
        return self

    async def __aexit__(self, *args: object) -> None:
        """Async context manager exit."""
        if self._session:
            await self._session.close()

    async def _fetch_html(self, url: str, params: dict[str, str] | None = None) -> str:
        """Fetch HTML from URL with rate limiting.

        Args:
            url: URL to fetch
            params: Query parameters

        Returns:
            str: HTML content

        Raises:
            NetworkError: If request fails
            RateLimitError: If rate limited

        """
        if not self._session:
            error_msg = "Client not initialized. Use 'async with AsyncClient()'"
            raise RuntimeError(error_msg)

        async with self._semaphore:  # Rate limiting
            try:
                async with self._session.get(url, params=params) as response:
                    # Check for rate limiting
                    if response.status == 429:
                        retry_after = int(response.headers.get("Retry-After", 60))
                        raise RateLimitError(retry_after)

                    # Check for not found
                    if response.status == 404:
                        raise AppNotFoundError(
                            app_id=params.get("id", "unknown") if params else "unknown"
                        )

                    # Check for other errors
                    if response.status >= 400:
                        raise NetworkError(url, response.status)

                    return await response.text()

            except TimeoutError as e:
                msg = "HTTP request"
                raise PlayfastTimeoutError(msg, self.timeout) from e
            except aiohttp.ClientError as e:
                raise NetworkError(url) from e

    async def get_app(
        self, app_id: str, lang: str | None = None, country: str = "us"
    ) -> AppInfo:
        """Get app information.

        This method performs 3 steps:
        1. Download HTML (async I/O with aiohttp)
        2. Parse HTML (CPU-intensive Rust, GIL-free)
        3. Validate with Pydantic (Python)

        Args:
            app_id: App package ID (e.g., "com.spotify.music")
            lang: Language code (default: client lang)
            country: Country code (default: "us")

        Returns:
            AppInfo: Validated app information

        Raises:
            AppNotFoundError: If app doesn't exist
            ParseError: If parsing fails
            NetworkError: If network request fails

        Examples:
            >>> import asyncio
            >>> async def test():
            ...     async with AsyncClient() as client:
            ...         app = await client.get_app("com.spotify.music")
            ...         return app.title, app.score >= 4.0
            >>> title, high_score = asyncio.run(test())
            >>> title
            'Spotify: Music and Podcasts'
            >>> high_score
            True

        """
        # Step 1: Async I/O - Download HTML
        url = f"{self.BASE_URL}/store/apps/details"
        params = {"id": app_id, "hl": lang or self.lang, "gl": country}

        html = await self._fetch_html(url, params)

        # Step 2: CPU-intensive - Parse with Rust (GIL-free)
        try:
            loop = asyncio.get_event_loop()
            rust_app = await loop.run_in_executor(None, parse_app_page, html, app_id)
        except Exception as e:
            msg = f"Failed to parse app page: {e}"
            raise ParseError(msg) from e

        # Step 3: Validation - Pydantic
        return AppInfo.from_rust(rust_app)

    async def get_apps_parallel(
        self,
        app_ids: list[str],
        countries: list[str] | None = None,
        lang: str | None = None,
    ) -> dict[str, list[AppInfo]]:
        """Get multiple apps in parallel across multiple countries.

        This method leverages true parallelism:
        - Async I/O for concurrent network requests
        - Rust parsing releases GIL for parallel CPU work

        Args:
            app_ids: List of app package IDs
            countries: List of country codes (default: ["us"])
            lang: Language code (default: client lang)

        Returns:
            dict: Country code -> list of AppInfo

        Examples:
            >>> import asyncio
            >>> async def test():
            ...     async with AsyncClient() as client:
            ...         results = await client.get_apps_parallel(
            ...             ["com.spotify.music", "com.netflix.mediaclient"], countries=["us", "kr"]
            ...         )
            ...         return sorted(results.keys()), len(results["us"])
            >>> countries, us_count = asyncio.run(test())
            >>> countries
            ['kr', 'us']
            >>> us_count
            2

        """
        countries = countries or ["us"]

        # Create tasks for all app+country combinations
        tasks: list[asyncio.Task[AppInfo]] = []
        task_metadata: list[tuple[str, str]] = []

        for country in countries:
            for app_id in app_ids:
                task = asyncio.create_task(
                    self.get_app(app_id, lang=lang, country=country)
                )
                tasks.append(task)
                task_metadata.append((country, app_id))

        # Execute all tasks in parallel
        results: list[AppInfo | BaseException] = await asyncio.gather(
            *tasks, return_exceptions=True
        )

        # Group by country
        by_country: dict[str, list[AppInfo]] = {c: [] for c in countries}

        for (country, _app_id), result in zip(task_metadata, results, strict=False):
            if isinstance(result, AppInfo):
                by_country[country].append(result)
            elif isinstance(result, Exception):
                # Log error but continue (graceful degradation)
                # In production, you might want proper logging here
                pass

        return by_country

    async def stream_reviews(
        self,
        app_id: str,
        lang: str | None = None,
        country: str = "us",
        sort: int = 1,
        max_pages: int | None = None,
    ) -> AsyncIterator[Review]:
        """Stream reviews with pagination (memory efficient).

        This is a generator that yields reviews one by one without
        loading all reviews into memory at once.

        Args:
            app_id: App package ID
            lang: Language code (default: client lang)
            country: Country code (default: "us")
            sort: Sort order (1=newest, 2=highest rating, 3=most helpful)
            max_pages: Maximum number of pages to fetch (default: unlimited)

        Yields:
            Review: Individual review objects

        Examples:
            >>> import asyncio
            >>> async def test():
            ...     async with AsyncClient() as client:
            ...         reviews = []
            ...         async for review in client.stream_reviews("com.spotify.music", max_pages=1):
            ...             reviews.append(review)
            ...             if len(reviews) >= 5:  # Limit for doctest
            ...                 break
            ...         return len(reviews), reviews[0].score >= 1
            >>> count, valid_score = asyncio.run(test())
            >>> count > 0
            True
            >>> valid_score
            True

        """
        continuation_token: str | None = None
        page_count = 0

        while True:
            # Check page limit
            if max_pages and page_count >= max_pages:
                break

            # Use Rust fetch_and_parse_reviews (batchexecute API)
            try:
                loop = asyncio.get_event_loop()
                rust_reviews, next_token = await loop.run_in_executor(
                    None,
                    fetch_and_parse_reviews,
                    app_id,
                    lang or self.lang,
                    country,
                    sort,
                    continuation_token,
                    self.timeout,
                )
            except Exception as e:
                msg = f"Failed to fetch reviews: {e}"
                raise ParseError(msg) from e

            # Yield validated reviews
            for rust_review in rust_reviews:
                yield Review.from_rust(rust_review)

            # Check for next page
            if not next_token:
                break

            continuation_token = next_token
            page_count += 1

    async def search(
        self,
        query: str,
        lang: str | None = None,
        country: str = "us",
        n_hits: int = 30,
    ) -> list[SearchResult]:
        """Search for apps.

        Args:
            query: Search query string
            lang: Language code (default: client lang)
            country: Country code (default: "us")
            n_hits: Number of results to return (max: 250)

        Returns:
            list[SearchResult]: List of search results

        Examples:
            >>> import asyncio
            >>> async def test():
            ...     async with AsyncClient() as client:
            ...         results = await client.search("music streaming")
            ...         return len(results), results[0].title
            >>> count, title = asyncio.run(test())
            >>> count > 0
            True
            >>> title
            'Spotify: Music and Podcasts'

        """
        url = f"{self.BASE_URL}/store/search"
        params = {
            "q": query,
            "hl": lang or self.lang,
            "gl": country,
            "c": "apps",
        }

        # Fetch HTML
        html = await self._fetch_html(url, params)

        # Parse search results (Rust, GIL-free)
        try:
            loop = asyncio.get_event_loop()
            rust_results = await loop.run_in_executor(None, parse_search_results, html)
        except Exception as e:
            msg = f"Failed to parse search results: {e}"
            raise ParseError(msg) from e

        # Validate and limit results
        validated = [SearchResult.from_rust(r) for r in rust_results]
        return validated[:n_hits]

    async def list(
        self,
        collection: str,
        category: str | None = None,
        lang: str | None = None,
        country: str = "us",
        num: int = 100,
    ) -> list[SearchResult]:
        """Get apps from a category/collection.

        This method uses the async HTTP + Rust parsing approach for true parallelism:
        1. Build request body with Rust (GIL-free)
        2. Download response with async I/O (aiohttp)
        3. Parse with Rust (GIL-free, parallel-ready)

        Args:
            collection: Collection type (e.g., "topselling_free", "topgrossing")
            category: Category code (e.g., "GAME_ACTION", "SOCIAL") or None for all
            lang: Language code (default: client lang)
            country: Country code (default: "us")
            num: Number of results (default: 100, max: 250)

        Returns:
            list[SearchResult]: List of apps

        Examples:
            >>> import asyncio
            >>> async def test():
            ...     async with AsyncClient() as client:
            ...         apps = await client.list(
            ...             collection="topselling_free", category="GAME_ACTION", country="us", num=50
            ...         )
            ...         return len(apps) > 0, isinstance(apps[0].title, str)
            >>> has_apps, valid = asyncio.run(test())
            >>> has_apps
            True
            >>> valid
            True

        """
        if not self._session:
            error_msg = "Client not initialized. Use 'async with AsyncClient()'"
            raise RuntimeError(error_msg)

        # Step 1: Build request body (Rust, GIL-free)
        loop = asyncio.get_event_loop()
        body = await loop.run_in_executor(
            None, build_list_request_body, category, collection, num
        )

        # Prepare batchexecute URL with params
        url = f"{self.BASE_URL}/_/PlayStoreUi/data/batchexecute"
        params = {
            "rpcids": "vyAe2",
            "source-path": "/store/apps",
            "f.sid": "-4178618388443751758",
            "bl": "boq_playuiserver_20220612.08_p0",
            "hl": lang or self.lang,
            "gl": country,
            "authuser": "0",
            "soc-app": "121",
            "soc-platform": "1",
            "soc-device": "1",
            "_reqid": "82003",
            "rt": "c",
        }

        headers = {
            **self._headers,
            "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
        }

        # Step 2: Fetch response (async I/O)
        async with self._semaphore:
            try:
                async with self._session.post(
                    url, params=params, data=body, headers=headers
                ) as response:
                    if response.status == 429:
                        retry_after = int(response.headers.get("Retry-After", 60))
                        raise RateLimitError(retry_after)

                    if response.status >= 400:
                        raise NetworkError(url, response.status)

                    response_text = await response.text()

            except TimeoutError as e:
                msg = "HTTP request"
                raise PlayfastTimeoutError(msg, self.timeout) from e
            except aiohttp.ClientError as e:
                raise NetworkError(url) from e

        # Step 3: Parse with Rust (GIL-free, parallel-ready)
        try:
            rust_results = await loop.run_in_executor(
                None, parse_batchexecute_list_response, response_text
            )
        except Exception as e:
            msg = f"Failed to parse list response: {e}"
            raise ParseError(msg) from e

        # Validate and return
        return [SearchResult.from_rust(r) for r in rust_results]

    async def close(self) -> None:
        """Close the HTTP session manually (if not using context manager)."""
        if self._session:
            await self._session.close()
            self._session = None

__init__(max_concurrent=10, timeout=30, headers=None, lang='en')

Initialize the async client.

Source code in python/playfast/client.py
def __init__(
    self,
    max_concurrent: int = 10,
    timeout: int = 30,
    headers: dict[str, str] | None = None,
    lang: str = "en",
) -> None:
    """Initialize the async client."""
    self.max_concurrent = max_concurrent
    self.timeout = timeout
    self.lang = lang

    # Default headers (mimic Chrome browser)
    self._headers = headers or {
        "User-Agent": (
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
            "AppleWebKit/537.36 (KHTML, like Gecko) "
            "Chrome/131.0.0.0 Safari/537.36"
        ),
        "Accept-Language": f"{lang},en-US;q=0.9,en;q=0.8",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    }

    self._session: aiohttp.ClientSession | None = None
    self._semaphore = asyncio.Semaphore(max_concurrent)

__aenter__() async

Async context manager entry.

Source code in python/playfast/client.py
async def __aenter__(self) -> "AsyncClient":
    """Async context manager entry."""
    timeout_config = aiohttp.ClientTimeout(total=self.timeout)

    # Use default connector (already optimized by aiohttp)
    # Custom settings can add overhead for high-concurrency scenarios
    self._session = aiohttp.ClientSession(
        timeout=timeout_config,
        headers=self._headers,
    )
    return self

__aexit__(*args) async

Async context manager exit.

Source code in python/playfast/client.py
async def __aexit__(self, *args: object) -> None:
    """Async context manager exit."""
    if self._session:
        await self._session.close()

get_app(app_id, lang=None, country='us') async

Get app information.

This method performs 3 steps: 1. Download HTML (async I/O with aiohttp) 2. Parse HTML (CPU-intensive Rust, GIL-free) 3. Validate with Pydantic (Python)

Parameters:

Name Type Description Default
app_id str

App package ID (e.g., "com.spotify.music")

required
lang str | None

Language code (default: client lang)

None
country str

Country code (default: "us")

'us'

Returns:

Name Type Description
AppInfo AppInfo

Validated app information

Raises:

Type Description
AppNotFoundError

If app doesn't exist

ParseError

If parsing fails

NetworkError

If network request fails

Examples:

>>> import asyncio
>>> async def test():
...     async with AsyncClient() as client:
...         app = await client.get_app("com.spotify.music")
...         return app.title, app.score >= 4.0
>>> title, high_score = asyncio.run(test())
>>> title
'Spotify: Music and Podcasts'
>>> high_score
True
Source code in python/playfast/client.py
async def get_app(
    self, app_id: str, lang: str | None = None, country: str = "us"
) -> AppInfo:
    """Get app information.

    This method performs 3 steps:
    1. Download HTML (async I/O with aiohttp)
    2. Parse HTML (CPU-intensive Rust, GIL-free)
    3. Validate with Pydantic (Python)

    Args:
        app_id: App package ID (e.g., "com.spotify.music")
        lang: Language code (default: client lang)
        country: Country code (default: "us")

    Returns:
        AppInfo: Validated app information

    Raises:
        AppNotFoundError: If app doesn't exist
        ParseError: If parsing fails
        NetworkError: If network request fails

    Examples:
        >>> import asyncio
        >>> async def test():
        ...     async with AsyncClient() as client:
        ...         app = await client.get_app("com.spotify.music")
        ...         return app.title, app.score >= 4.0
        >>> title, high_score = asyncio.run(test())
        >>> title
        'Spotify: Music and Podcasts'
        >>> high_score
        True

    """
    # Step 1: Async I/O - Download HTML
    url = f"{self.BASE_URL}/store/apps/details"
    params = {"id": app_id, "hl": lang or self.lang, "gl": country}

    html = await self._fetch_html(url, params)

    # Step 2: CPU-intensive - Parse with Rust (GIL-free)
    try:
        loop = asyncio.get_event_loop()
        rust_app = await loop.run_in_executor(None, parse_app_page, html, app_id)
    except Exception as e:
        msg = f"Failed to parse app page: {e}"
        raise ParseError(msg) from e

    # Step 3: Validation - Pydantic
    return AppInfo.from_rust(rust_app)

get_apps_parallel(app_ids, countries=None, lang=None) async

Get multiple apps in parallel across multiple countries.

This method leverages true parallelism: - Async I/O for concurrent network requests - Rust parsing releases GIL for parallel CPU work

Parameters:

Name Type Description Default
app_ids list[str]

List of app package IDs

required
countries list[str] | None

List of country codes (default: ["us"])

None
lang str | None

Language code (default: client lang)

None

Returns:

Name Type Description
dict dict[str, list[AppInfo]]

Country code -> list of AppInfo

Examples:

>>> import asyncio
>>> async def test():
...     async with AsyncClient() as client:
...         results = await client.get_apps_parallel(
...             ["com.spotify.music", "com.netflix.mediaclient"], countries=["us", "kr"]
...         )
...         return sorted(results.keys()), len(results["us"])
>>> countries, us_count = asyncio.run(test())
>>> countries
['kr', 'us']
>>> us_count
2
Source code in python/playfast/client.py
async def get_apps_parallel(
    self,
    app_ids: list[str],
    countries: list[str] | None = None,
    lang: str | None = None,
) -> dict[str, list[AppInfo]]:
    """Get multiple apps in parallel across multiple countries.

    This method leverages true parallelism:
    - Async I/O for concurrent network requests
    - Rust parsing releases GIL for parallel CPU work

    Args:
        app_ids: List of app package IDs
        countries: List of country codes (default: ["us"])
        lang: Language code (default: client lang)

    Returns:
        dict: Country code -> list of AppInfo

    Examples:
        >>> import asyncio
        >>> async def test():
        ...     async with AsyncClient() as client:
        ...         results = await client.get_apps_parallel(
        ...             ["com.spotify.music", "com.netflix.mediaclient"], countries=["us", "kr"]
        ...         )
        ...         return sorted(results.keys()), len(results["us"])
        >>> countries, us_count = asyncio.run(test())
        >>> countries
        ['kr', 'us']
        >>> us_count
        2

    """
    countries = countries or ["us"]

    # Create tasks for all app+country combinations
    tasks: list[asyncio.Task[AppInfo]] = []
    task_metadata: list[tuple[str, str]] = []

    for country in countries:
        for app_id in app_ids:
            task = asyncio.create_task(
                self.get_app(app_id, lang=lang, country=country)
            )
            tasks.append(task)
            task_metadata.append((country, app_id))

    # Execute all tasks in parallel
    results: list[AppInfo | BaseException] = await asyncio.gather(
        *tasks, return_exceptions=True
    )

    # Group by country
    by_country: dict[str, list[AppInfo]] = {c: [] for c in countries}

    for (country, _app_id), result in zip(task_metadata, results, strict=False):
        if isinstance(result, AppInfo):
            by_country[country].append(result)
        elif isinstance(result, Exception):
            # Log error but continue (graceful degradation)
            # In production, you might want proper logging here
            pass

    return by_country

stream_reviews(app_id, lang=None, country='us', sort=1, max_pages=None) async

Stream reviews with pagination (memory efficient).

This is a generator that yields reviews one by one without loading all reviews into memory at once.

Parameters:

Name Type Description Default
app_id str

App package ID

required
lang str | None

Language code (default: client lang)

None
country str

Country code (default: "us")

'us'
sort int

Sort order (1=newest, 2=highest rating, 3=most helpful)

1
max_pages int | None

Maximum number of pages to fetch (default: unlimited)

None

Yields:

Name Type Description
Review AsyncIterator[Review]

Individual review objects

Examples:

>>> import asyncio
>>> async def test():
...     async with AsyncClient() as client:
...         reviews = []
...         async for review in client.stream_reviews("com.spotify.music", max_pages=1):
...             reviews.append(review)
...             if len(reviews) >= 5:  # Limit for doctest
...                 break
...         return len(reviews), reviews[0].score >= 1
>>> count, valid_score = asyncio.run(test())
>>> count > 0
True
>>> valid_score
True
Source code in python/playfast/client.py
async def stream_reviews(
    self,
    app_id: str,
    lang: str | None = None,
    country: str = "us",
    sort: int = 1,
    max_pages: int | None = None,
) -> AsyncIterator[Review]:
    """Stream reviews with pagination (memory efficient).

    This is a generator that yields reviews one by one without
    loading all reviews into memory at once.

    Args:
        app_id: App package ID
        lang: Language code (default: client lang)
        country: Country code (default: "us")
        sort: Sort order (1=newest, 2=highest rating, 3=most helpful)
        max_pages: Maximum number of pages to fetch (default: unlimited)

    Yields:
        Review: Individual review objects

    Examples:
        >>> import asyncio
        >>> async def test():
        ...     async with AsyncClient() as client:
        ...         reviews = []
        ...         async for review in client.stream_reviews("com.spotify.music", max_pages=1):
        ...             reviews.append(review)
        ...             if len(reviews) >= 5:  # Limit for doctest
        ...                 break
        ...         return len(reviews), reviews[0].score >= 1
        >>> count, valid_score = asyncio.run(test())
        >>> count > 0
        True
        >>> valid_score
        True

    """
    continuation_token: str | None = None
    page_count = 0

    while True:
        # Check page limit
        if max_pages and page_count >= max_pages:
            break

        # Use Rust fetch_and_parse_reviews (batchexecute API)
        try:
            loop = asyncio.get_event_loop()
            rust_reviews, next_token = await loop.run_in_executor(
                None,
                fetch_and_parse_reviews,
                app_id,
                lang or self.lang,
                country,
                sort,
                continuation_token,
                self.timeout,
            )
        except Exception as e:
            msg = f"Failed to fetch reviews: {e}"
            raise ParseError(msg) from e

        # Yield validated reviews
        for rust_review in rust_reviews:
            yield Review.from_rust(rust_review)

        # Check for next page
        if not next_token:
            break

        continuation_token = next_token
        page_count += 1

search(query, lang=None, country='us', n_hits=30) async

Search for apps.

Parameters:

Name Type Description Default
query str

Search query string

required
lang str | None

Language code (default: client lang)

None
country str

Country code (default: "us")

'us'
n_hits int

Number of results to return (max: 250)

30

Returns:

Type Description
list[SearchResult]

list[SearchResult]: List of search results

Examples:

>>> import asyncio
>>> async def test():
...     async with AsyncClient() as client:
...         results = await client.search("music streaming")
...         return len(results), results[0].title
>>> count, title = asyncio.run(test())
>>> count > 0
True
>>> title
'Spotify: Music and Podcasts'
Source code in python/playfast/client.py
async def search(
    self,
    query: str,
    lang: str | None = None,
    country: str = "us",
    n_hits: int = 30,
) -> list[SearchResult]:
    """Search for apps.

    Args:
        query: Search query string
        lang: Language code (default: client lang)
        country: Country code (default: "us")
        n_hits: Number of results to return (max: 250)

    Returns:
        list[SearchResult]: List of search results

    Examples:
        >>> import asyncio
        >>> async def test():
        ...     async with AsyncClient() as client:
        ...         results = await client.search("music streaming")
        ...         return len(results), results[0].title
        >>> count, title = asyncio.run(test())
        >>> count > 0
        True
        >>> title
        'Spotify: Music and Podcasts'

    """
    url = f"{self.BASE_URL}/store/search"
    params = {
        "q": query,
        "hl": lang or self.lang,
        "gl": country,
        "c": "apps",
    }

    # Fetch HTML
    html = await self._fetch_html(url, params)

    # Parse search results (Rust, GIL-free)
    try:
        loop = asyncio.get_event_loop()
        rust_results = await loop.run_in_executor(None, parse_search_results, html)
    except Exception as e:
        msg = f"Failed to parse search results: {e}"
        raise ParseError(msg) from e

    # Validate and limit results
    validated = [SearchResult.from_rust(r) for r in rust_results]
    return validated[:n_hits]

list(collection, category=None, lang=None, country='us', num=100) async

Get apps from a category/collection.

This method uses the async HTTP + Rust parsing approach for true parallelism: 1. Build request body with Rust (GIL-free) 2. Download response with async I/O (aiohttp) 3. Parse with Rust (GIL-free, parallel-ready)

Parameters:

Name Type Description Default
collection str

Collection type (e.g., "topselling_free", "topgrossing")

required
category str | None

Category code (e.g., "GAME_ACTION", "SOCIAL") or None for all

None
lang str | None

Language code (default: client lang)

None
country str

Country code (default: "us")

'us'
num int

Number of results (default: 100, max: 250)

100

Returns:

Type Description
list[SearchResult]

list[SearchResult]: List of apps

Examples:

>>> import asyncio
>>> async def test():
...     async with AsyncClient() as client:
...         apps = await client.list(
...             collection="topselling_free", category="GAME_ACTION", country="us", num=50
...         )
...         return len(apps) > 0, isinstance(apps[0].title, str)
>>> has_apps, valid = asyncio.run(test())
>>> has_apps
True
>>> valid
True
Source code in python/playfast/client.py
async def list(
    self,
    collection: str,
    category: str | None = None,
    lang: str | None = None,
    country: str = "us",
    num: int = 100,
) -> list[SearchResult]:
    """Get apps from a category/collection.

    This method uses the async HTTP + Rust parsing approach for true parallelism:
    1. Build request body with Rust (GIL-free)
    2. Download response with async I/O (aiohttp)
    3. Parse with Rust (GIL-free, parallel-ready)

    Args:
        collection: Collection type (e.g., "topselling_free", "topgrossing")
        category: Category code (e.g., "GAME_ACTION", "SOCIAL") or None for all
        lang: Language code (default: client lang)
        country: Country code (default: "us")
        num: Number of results (default: 100, max: 250)

    Returns:
        list[SearchResult]: List of apps

    Examples:
        >>> import asyncio
        >>> async def test():
        ...     async with AsyncClient() as client:
        ...         apps = await client.list(
        ...             collection="topselling_free", category="GAME_ACTION", country="us", num=50
        ...         )
        ...         return len(apps) > 0, isinstance(apps[0].title, str)
        >>> has_apps, valid = asyncio.run(test())
        >>> has_apps
        True
        >>> valid
        True

    """
    if not self._session:
        error_msg = "Client not initialized. Use 'async with AsyncClient()'"
        raise RuntimeError(error_msg)

    # Step 1: Build request body (Rust, GIL-free)
    loop = asyncio.get_event_loop()
    body = await loop.run_in_executor(
        None, build_list_request_body, category, collection, num
    )

    # Prepare batchexecute URL with params
    url = f"{self.BASE_URL}/_/PlayStoreUi/data/batchexecute"
    params = {
        "rpcids": "vyAe2",
        "source-path": "/store/apps",
        "f.sid": "-4178618388443751758",
        "bl": "boq_playuiserver_20220612.08_p0",
        "hl": lang or self.lang,
        "gl": country,
        "authuser": "0",
        "soc-app": "121",
        "soc-platform": "1",
        "soc-device": "1",
        "_reqid": "82003",
        "rt": "c",
    }

    headers = {
        **self._headers,
        "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
    }

    # Step 2: Fetch response (async I/O)
    async with self._semaphore:
        try:
            async with self._session.post(
                url, params=params, data=body, headers=headers
            ) as response:
                if response.status == 429:
                    retry_after = int(response.headers.get("Retry-After", 60))
                    raise RateLimitError(retry_after)

                if response.status >= 400:
                    raise NetworkError(url, response.status)

                response_text = await response.text()

        except TimeoutError as e:
            msg = "HTTP request"
            raise PlayfastTimeoutError(msg, self.timeout) from e
        except aiohttp.ClientError as e:
            raise NetworkError(url) from e

    # Step 3: Parse with Rust (GIL-free, parallel-ready)
    try:
        rust_results = await loop.run_in_executor(
            None, parse_batchexecute_list_response, response_text
        )
    except Exception as e:
        msg = f"Failed to parse list response: {e}"
        raise ParseError(msg) from e

    # Validate and return
    return [SearchResult.from_rust(r) for r in rust_results]

close() async

Close the HTTP session manually (if not using context manager).

Source code in python/playfast/client.py
async def close(self) -> None:
    """Close the HTTP session manually (if not using context manager)."""
    if self._session:
        await self._session.close()
        self._session = None

options: show_source: true show_root_heading: true show_root_full_path: false members: - init - get_app - get_apps_parallel - stream_reviews - search - aenter - aexit