From 5cbc3641c3e9dd01ae4622b48faba47c148c09a9 Mon Sep 17 00:00:00 2001 From: Furkan Coban Date: Sun, 15 Nov 2026 13:13:50 +0300 Subject: [PATCH 01/11] feat: expose request statistics on ApifyClient and ApifyClientAsync --- src/apify_client/__init__.py | 2 + src/apify_client/_apify_client.py | 12 ++++ src/apify_client/_statistics.py | 3 + src/apify_client/http_clients/_base.py | 5 ++ tests/unit/test_statistics.py | 96 +++++++++++++++++++++++++- 5 files changed, 117 insertions(+), 1 deletion(-) diff --git a/src/apify_client/__init__.py b/src/apify_client/__init__.py index 97534ce36..7efad70ec 100644 --- a/src/apify_client/__init__.py +++ b/src/apify_client/__init__.py @@ -1,11 +1,13 @@ from importlib import metadata from ._apify_client import ApifyClient, ApifyClientAsync +from ._statistics import ClientStatistics __version__ = metadata.version('apify-client') __all__ = [ 'ApifyClient', 'ApifyClientAsync', + 'ClientStatistics', '__version__', ] diff --git a/src/apify_client/_apify_client.py b/src/apify_client/_apify_client.py index 255c87ea5..f9b7777d4 100644 --- a/src/apify_client/_apify_client.py +++ b/src/apify_client/_apify_client.py @@ -277,6 +277,7 @@ def send_request(self, *, method, url, headers, content, timeout, stream) -> Htt if token is not None: http_client.set_default_authorization(token) instance._http_client = http_client + instance._statistics = http_client.statistics return instance @property @@ -284,6 +285,11 @@ def token(self) -> str | None: """The Apify API token used by the client.""" return self._token + @property + def statistics(self) -> ClientStatistics: + """Statistics about API client usage and rate limit errors.""" + return self._statistics + @property def http_client(self) -> HttpClient: """The HTTP client instance used for API communication. @@ -660,6 +666,7 @@ async def send_request(self, *, method, url, headers, content, timeout, stream) if token is not None: http_client.set_default_authorization(token) instance._http_client = http_client + instance._statistics = http_client.statistics return instance @property @@ -667,6 +674,11 @@ def token(self) -> str | None: """The Apify API token used by the client.""" return self._token + @property + def statistics(self) -> ClientStatistics: + """Statistics about API client usage and rate limit errors.""" + return self._statistics + @property def http_client(self) -> HttpClientAsync: """The HTTP client instance used for API communication. diff --git a/src/apify_client/_statistics.py b/src/apify_client/_statistics.py index b1639bb3f..7d91d8041 100644 --- a/src/apify_client/_statistics.py +++ b/src/apify_client/_statistics.py @@ -3,7 +3,10 @@ from collections import defaultdict from dataclasses import dataclass, field +from apify_client._docs import docs_group + +@docs_group('Other') @dataclass class ClientStatistics: """Statistics about API client usage and rate limit errors.""" diff --git a/src/apify_client/http_clients/_base.py b/src/apify_client/http_clients/_base.py index 4d478f183..fb4450ba1 100644 --- a/src/apify_client/http_clients/_base.py +++ b/src/apify_client/http_clients/_base.py @@ -190,6 +190,11 @@ def __init__( self._headers = merge_headers(default_headers, headers) + @property + def statistics(self) -> ClientStatistics: + """Statistics about API client usage and rate limit errors.""" + return self._statistics + def set_default_authorization(self, token: str) -> None: """Set the `Authorization` header from the token, unless an authorization header is already configured. diff --git a/tests/unit/test_statistics.py b/tests/unit/test_statistics.py index 37634a7bb..e00aaaf6b 100644 --- a/tests/unit/test_statistics.py +++ b/tests/unit/test_statistics.py @@ -1,8 +1,16 @@ from __future__ import annotations +from typing import TYPE_CHECKING + import pytest +from werkzeug import Response + +import apify_client +from apify_client import ApifyClient, ApifyClientAsync, ClientStatistics +from apify_client.http_clients import ImpitHttpClient, ImpitHttpClientAsync -from apify_client._statistics import ClientStatistics +if TYPE_CHECKING: + from pytest_httpserver import HTTPServer @pytest.mark.parametrize( @@ -120,3 +128,89 @@ def test_add_rate_limit_error_large_attempt() -> None: stats.add_rate_limit_error(10000) assert stats.rate_limit_errors[9999] == 1 + + +def test_client_statistics_is_exported() -> None: + """Test that ClientStatistics is exported from the top-level apify_client package.""" + assert 'ClientStatistics' in apify_client.__all__ + assert apify_client.ClientStatistics is ClientStatistics + + +def test_apify_client_exposes_default_http_client_statistics(httpserver: HTTPServer) -> None: + """Test that ApifyClient.statistics tracks calls and requests on the default HTTP client.""" + httpserver.expect_request('/v2/logs/test-id').respond_with_response( + Response('ok', status=200, content_type='text/plain') + ) + client = ApifyClient('test-token', api_url=httpserver.url_for('/')) + + assert isinstance(client.statistics, ClientStatistics) + assert client.statistics is client.http_client.statistics + assert client.statistics.calls == 0 + assert client.statistics.requests == 0 + + client.log('test-id').get() + + assert client.statistics.calls == 1 + assert client.statistics.requests == 1 + + +def test_apify_client_exposes_custom_http_client_statistics(httpserver: HTTPServer) -> None: + """Test that ApifyClient.with_custom_http_client points client.statistics to the custom HTTP client's stats.""" + httpserver.expect_request('/v2/logs/test-id').respond_with_response( + Response('ok', status=200, content_type='text/plain') + ) + custom_http_client = ImpitHttpClient() + client = ApifyClient.with_custom_http_client( + 'test-token', + api_url=httpserver.url_for('/'), + http_client=custom_http_client, + ) + + assert client.statistics is custom_http_client.statistics + assert client.statistics.calls == 0 + assert client.statistics.requests == 0 + + client.log('test-id').get() + + assert client.statistics.calls == 1 + assert client.statistics.requests == 1 + + +async def test_apify_client_async_exposes_default_http_client_statistics(httpserver: HTTPServer) -> None: + """Test that ApifyClientAsync.statistics tracks calls and requests on the default HTTP client.""" + httpserver.expect_request('/v2/logs/test-id').respond_with_response( + Response('ok', status=200, content_type='text/plain') + ) + client = ApifyClientAsync('test-token', api_url=httpserver.url_for('/')) + + assert isinstance(client.statistics, ClientStatistics) + assert client.statistics is client.http_client.statistics + assert client.statistics.calls == 0 + assert client.statistics.requests == 0 + + await client.log('test-id').get() + + assert client.statistics.calls == 1 + assert client.statistics.requests == 1 + + +async def test_apify_client_async_exposes_custom_http_client_statistics(httpserver: HTTPServer) -> None: + """Test that ApifyClientAsync.with_custom_http_client points client.statistics to the custom HTTP client's stats.""" + httpserver.expect_request('/v2/logs/test-id').respond_with_response( + Response('ok', status=200, content_type='text/plain') + ) + custom_http_client = ImpitHttpClientAsync() + client = ApifyClientAsync.with_custom_http_client( + 'test-token', + api_url=httpserver.url_for('/'), + http_client=custom_http_client, + ) + + assert client.statistics is custom_http_client.statistics + assert client.statistics.calls == 0 + assert client.statistics.requests == 0 + + await client.log('test-id').get() + + assert client.statistics.calls == 1 + assert client.statistics.requests == 1 From 49cf0f2fc9aea16bbbcb84d373c4d7755fb88ab8 Mon Sep 17 00:00:00 2001 From: Vlada Dusek Date: Mon, 16 Nov 2026 09:03:57 +0100 Subject: [PATCH 02/11] refactor: rename the `statistics` property to `stats` --- src/apify_client/_apify_client.py | 8 ++-- src/apify_client/http_clients/_base.py | 2 +- tests/unit/test_statistics.py | 52 +++++++++++++------------- 3 files changed, 31 insertions(+), 31 deletions(-) diff --git a/src/apify_client/_apify_client.py b/src/apify_client/_apify_client.py index f9b7777d4..a5b4b81ce 100644 --- a/src/apify_client/_apify_client.py +++ b/src/apify_client/_apify_client.py @@ -277,7 +277,7 @@ def send_request(self, *, method, url, headers, content, timeout, stream) -> Htt if token is not None: http_client.set_default_authorization(token) instance._http_client = http_client - instance._statistics = http_client.statistics + instance._statistics = http_client.stats return instance @property @@ -286,7 +286,7 @@ def token(self) -> str | None: return self._token @property - def statistics(self) -> ClientStatistics: + def stats(self) -> ClientStatistics: """Statistics about API client usage and rate limit errors.""" return self._statistics @@ -666,7 +666,7 @@ async def send_request(self, *, method, url, headers, content, timeout, stream) if token is not None: http_client.set_default_authorization(token) instance._http_client = http_client - instance._statistics = http_client.statistics + instance._statistics = http_client.stats return instance @property @@ -675,7 +675,7 @@ def token(self) -> str | None: return self._token @property - def statistics(self) -> ClientStatistics: + def stats(self) -> ClientStatistics: """Statistics about API client usage and rate limit errors.""" return self._statistics diff --git a/src/apify_client/http_clients/_base.py b/src/apify_client/http_clients/_base.py index fb4450ba1..24a6d1847 100644 --- a/src/apify_client/http_clients/_base.py +++ b/src/apify_client/http_clients/_base.py @@ -191,7 +191,7 @@ def __init__( self._headers = merge_headers(default_headers, headers) @property - def statistics(self) -> ClientStatistics: + def stats(self) -> ClientStatistics: """Statistics about API client usage and rate limit errors.""" return self._statistics diff --git a/tests/unit/test_statistics.py b/tests/unit/test_statistics.py index e00aaaf6b..534b5520f 100644 --- a/tests/unit/test_statistics.py +++ b/tests/unit/test_statistics.py @@ -137,25 +137,25 @@ def test_client_statistics_is_exported() -> None: def test_apify_client_exposes_default_http_client_statistics(httpserver: HTTPServer) -> None: - """Test that ApifyClient.statistics tracks calls and requests on the default HTTP client.""" + """Test that ApifyClient.stats tracks calls and requests on the default HTTP client.""" httpserver.expect_request('/v2/logs/test-id').respond_with_response( Response('ok', status=200, content_type='text/plain') ) client = ApifyClient('test-token', api_url=httpserver.url_for('/')) - assert isinstance(client.statistics, ClientStatistics) - assert client.statistics is client.http_client.statistics - assert client.statistics.calls == 0 - assert client.statistics.requests == 0 + assert isinstance(client.stats, ClientStatistics) + assert client.stats is client.http_client.stats + assert client.stats.calls == 0 + assert client.stats.requests == 0 client.log('test-id').get() - assert client.statistics.calls == 1 - assert client.statistics.requests == 1 + assert client.stats.calls == 1 + assert client.stats.requests == 1 def test_apify_client_exposes_custom_http_client_statistics(httpserver: HTTPServer) -> None: - """Test that ApifyClient.with_custom_http_client points client.statistics to the custom HTTP client's stats.""" + """Test that ApifyClient.with_custom_http_client points client.stats to the custom HTTP client's stats.""" httpserver.expect_request('/v2/logs/test-id').respond_with_response( Response('ok', status=200, content_type='text/plain') ) @@ -166,36 +166,36 @@ def test_apify_client_exposes_custom_http_client_statistics(httpserver: HTTPServ http_client=custom_http_client, ) - assert client.statistics is custom_http_client.statistics - assert client.statistics.calls == 0 - assert client.statistics.requests == 0 + assert client.stats is custom_http_client.stats + assert client.stats.calls == 0 + assert client.stats.requests == 0 client.log('test-id').get() - assert client.statistics.calls == 1 - assert client.statistics.requests == 1 + assert client.stats.calls == 1 + assert client.stats.requests == 1 async def test_apify_client_async_exposes_default_http_client_statistics(httpserver: HTTPServer) -> None: - """Test that ApifyClientAsync.statistics tracks calls and requests on the default HTTP client.""" + """Test that ApifyClientAsync.stats tracks calls and requests on the default HTTP client.""" httpserver.expect_request('/v2/logs/test-id').respond_with_response( Response('ok', status=200, content_type='text/plain') ) client = ApifyClientAsync('test-token', api_url=httpserver.url_for('/')) - assert isinstance(client.statistics, ClientStatistics) - assert client.statistics is client.http_client.statistics - assert client.statistics.calls == 0 - assert client.statistics.requests == 0 + assert isinstance(client.stats, ClientStatistics) + assert client.stats is client.http_client.stats + assert client.stats.calls == 0 + assert client.stats.requests == 0 await client.log('test-id').get() - assert client.statistics.calls == 1 - assert client.statistics.requests == 1 + assert client.stats.calls == 1 + assert client.stats.requests == 1 async def test_apify_client_async_exposes_custom_http_client_statistics(httpserver: HTTPServer) -> None: - """Test that ApifyClientAsync.with_custom_http_client points client.statistics to the custom HTTP client's stats.""" + """Test that ApifyClientAsync.with_custom_http_client points client.stats to the custom HTTP client's stats.""" httpserver.expect_request('/v2/logs/test-id').respond_with_response( Response('ok', status=200, content_type='text/plain') ) @@ -206,11 +206,11 @@ async def test_apify_client_async_exposes_custom_http_client_statistics(httpserv http_client=custom_http_client, ) - assert client.statistics is custom_http_client.statistics - assert client.statistics.calls == 0 - assert client.statistics.requests == 0 + assert client.stats is custom_http_client.stats + assert client.stats.calls == 0 + assert client.stats.requests == 0 await client.log('test-id').get() - assert client.statistics.calls == 1 - assert client.statistics.requests == 1 + assert client.stats.calls == 1 + assert client.stats.requests == 1 From 0fa29e130611d34d13684bb7ac4ab393f211c302 Mon Sep 17 00:00:00 2001 From: Vlada Dusek Date: Mon, 16 Nov 2026 09:04:14 +0100 Subject: [PATCH 03/11] refactor: read `stats` from the HTTP client in use --- src/apify_client/_apify_client.py | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/src/apify_client/_apify_client.py b/src/apify_client/_apify_client.py index a5b4b81ce..45016d1a6 100644 --- a/src/apify_client/_apify_client.py +++ b/src/apify_client/_apify_client.py @@ -277,7 +277,6 @@ def send_request(self, *, method, url, headers, content, timeout, stream) -> Htt if token is not None: http_client.set_default_authorization(token) instance._http_client = http_client - instance._statistics = http_client.stats return instance @property @@ -287,8 +286,12 @@ def token(self) -> str | None: @property def stats(self) -> ClientStatistics: - """Statistics about API client usage and rate limit errors.""" - return self._statistics + """Statistics about API client usage and rate limit errors. + + These are the statistics of the HTTP client in use. A custom HTTP client that overrides `call` counts only + what its own implementation records. + """ + return self.http_client.stats @property def http_client(self) -> HttpClient: @@ -666,7 +669,6 @@ async def send_request(self, *, method, url, headers, content, timeout, stream) if token is not None: http_client.set_default_authorization(token) instance._http_client = http_client - instance._statistics = http_client.stats return instance @property @@ -676,8 +678,12 @@ def token(self) -> str | None: @property def stats(self) -> ClientStatistics: - """Statistics about API client usage and rate limit errors.""" - return self._statistics + """Statistics about API client usage and rate limit errors. + + These are the statistics of the HTTP client in use. A custom HTTP client that overrides `call` counts only + what its own implementation records. + """ + return self.http_client.stats @property def http_client(self) -> HttpClientAsync: From fa7ef4312723e598485eb242a6ef86fcad3ee512 Mon Sep 17 00:00:00 2001 From: Vlada Dusek Date: Mon, 16 Nov 2026 09:04:19 +0100 Subject: [PATCH 04/11] docs: fix the `rate_limit_errors` docstring --- src/apify_client/_statistics.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/apify_client/_statistics.py b/src/apify_client/_statistics.py index 7d91d8041..18b137dbd 100644 --- a/src/apify_client/_statistics.py +++ b/src/apify_client/_statistics.py @@ -18,7 +18,7 @@ class ClientStatistics: """Total number of HTTP requests sent, including retries.""" rate_limit_errors: defaultdict[int, int] = field(default_factory=lambda: defaultdict(int)) - """List tracking which retry attempts encountered rate limit (429) errors.""" + """Number of rate limit (429) errors per attempt, keyed by the 0-based attempt index.""" def add_rate_limit_error(self, attempt: int) -> None: """Add rate limit error for specific attempt. From 7ff736f46b5aff895c8fe904b2fac760c24c9dbc Mon Sep 17 00:00:00 2001 From: Vlada Dusek Date: Mon, 16 Nov 2026 09:05:32 +0100 Subject: [PATCH 05/11] docs: document request statistics in the retries guide --- docs/02_concepts/05_retries.mdx | 25 +++++++++++++++++++++++++ docs/02_concepts/code/05_stats_async.py | 13 +++++++++++++ docs/02_concepts/code/05_stats_sync.py | 13 +++++++++++++ 3 files changed, 51 insertions(+) create mode 100644 docs/02_concepts/code/05_stats_async.py create mode 100644 docs/02_concepts/code/05_stats_sync.py diff --git a/docs/02_concepts/05_retries.mdx b/docs/02_concepts/05_retries.mdx index 54cf25625..d4599d0b4 100644 --- a/docs/02_concepts/05_retries.mdx +++ b/docs/02_concepts/05_retries.mdx @@ -12,6 +12,8 @@ import ApiLink from '@theme/ApiLink'; import RetriesAsyncExample from '!!raw-loader!./code/05_retries_async.py'; import RetriesSyncExample from '!!raw-loader!./code/05_retries_sync.py'; +import StatsAsyncExample from '!!raw-loader!./code/05_stats_async.py'; +import StatsSyncExample from '!!raw-loader!./code/05_stats_sync.py'; import WaitForResourcesAsyncExample from '!!raw-loader!./code/05_wait_for_resources_async.py'; import WaitForResourcesSyncExample from '!!raw-loader!./code/05_wait_for_resources_sync.py'; @@ -46,6 +48,29 @@ Retries with exponential backoff help reduce the load on the server and increase +## Request statistics + +The client counts its API calls, HTTP requests, and rate limit errors. To read the counts, use the `stats` property. It returns a `ClientStatistics` object with these fields: + +- `calls` is the number of API calls made through the client. +- `requests` is the number of HTTP requests sent, including retries. +- `rate_limit_errors` maps each attempt to the number of rate limit (429) errors it got. Index `0` is the first attempt, index `1` is the first retry, and so on. + +With a custom HTTP client, `stats` returns the statistics of that client. For details, see [HTTP clients](/api/client/python/docs/concepts/custom-http-clients). + + + + + {StatsAsyncExample} + + + + + {StatsSyncExample} + + + + ## Wait for resources to start a run Starting a run fails with an HTTP 402 error when the account doesn't have enough free memory for the run, or when it already runs as many Actors as its plan allows. The error `type` is `actor-memory-limit-exceeded` or `concurrent-runs-limit-exceeded`. The client doesn't retry these errors on its own, since they clear only after other runs or builds of the account finish. diff --git a/docs/02_concepts/code/05_stats_async.py b/docs/02_concepts/code/05_stats_async.py new file mode 100644 index 000000000..133feb044 --- /dev/null +++ b/docs/02_concepts/code/05_stats_async.py @@ -0,0 +1,13 @@ +from apify_client import ApifyClientAsync + +TOKEN = 'MY-APIFY-TOKEN' + + +async def main() -> None: + apify_client = ApifyClientAsync(TOKEN) + + await apify_client.actor('username/actor-name').call() + + stats = apify_client.stats + print(f'API calls: {stats.calls}, HTTP requests: {stats.requests}') + print(f'Rate limit errors per attempt: {dict(stats.rate_limit_errors)}') diff --git a/docs/02_concepts/code/05_stats_sync.py b/docs/02_concepts/code/05_stats_sync.py new file mode 100644 index 000000000..2e323903b --- /dev/null +++ b/docs/02_concepts/code/05_stats_sync.py @@ -0,0 +1,13 @@ +from apify_client import ApifyClient + +TOKEN = 'MY-APIFY-TOKEN' + + +def main() -> None: + apify_client = ApifyClient(TOKEN) + + apify_client.actor('username/actor-name').call() + + stats = apify_client.stats + print(f'API calls: {stats.calls}, HTTP requests: {stats.requests}') + print(f'Rate limit errors per attempt: {dict(stats.rate_limit_errors)}') From 382460f39e876e1a65602a9650ecaf8bb34b2789 Mon Sep 17 00:00:00 2001 From: Vlada Dusek Date: Mon, 16 Nov 2026 09:17:56 +0100 Subject: [PATCH 06/11] refactor: drop the unused root `_statistics` field --- src/apify_client/_apify_client.py | 10 +--------- tests/unit/test_actor_server.py | 2 +- 2 files changed, 2 insertions(+), 10 deletions(-) diff --git a/src/apify_client/_apify_client.py b/src/apify_client/_apify_client.py index 45016d1a6..808241c95 100644 --- a/src/apify_client/_apify_client.py +++ b/src/apify_client/_apify_client.py @@ -72,7 +72,6 @@ WebhookDispatchCollectionClient, WebhookDispatchCollectionClientAsync, ) -from apify_client._statistics import ClientStatistics from apify_client._utils.http import check_custom_headers, to_api_base_url from apify_client.http_clients import HttpClient, HttpClientAsync, ImpitHttpClient, ImpitHttpClientAsync from apify_client.http_compressors._resolve import resolve_compressor @@ -80,6 +79,7 @@ if TYPE_CHECKING: from datetime import timedelta + from apify_client._statistics import ClientStatistics from apify_client.http_compressors._base import HttpCompressor from apify_client.types import HttpCompressionAlgorithm @@ -182,9 +182,6 @@ def __init__( self._public_base_url = to_api_base_url(api_public_url) """Public base URL for CDN access.""" - self._statistics = ClientStatistics() - """Collector for client request statistics.""" - self._http_client: HttpClient | None = None """HTTP client used to communicate with the Apify API. Lazily initialized on first access.""" @@ -309,7 +306,6 @@ def http_client(self) -> HttpClient: timeout_max=self._timeout_max, max_retries=self._max_retries, min_delay_between_retries=self._min_delay_between_retries, - statistics=self._statistics, headers=self._headers, user_agent_suffix=self._user_agent_suffix, http_compressor=self._http_compressor, @@ -574,9 +570,6 @@ def __init__( self._public_base_url = to_api_base_url(api_public_url) """Public base URL for CDN access.""" - self._statistics = ClientStatistics() - """Collector for client request statistics.""" - self._http_client: HttpClientAsync | None = None """HTTP client used to communicate with the Apify API. Lazily initialized on first access.""" @@ -701,7 +694,6 @@ def http_client(self) -> HttpClientAsync: timeout_max=self._timeout_max, max_retries=self._max_retries, min_delay_between_retries=self._min_delay_between_retries, - statistics=self._statistics, headers=self._headers, user_agent_suffix=self._user_agent_suffix, http_compressor=self._http_compressor, diff --git a/tests/unit/test_actor_server.py b/tests/unit/test_actor_server.py index f7ba4379c..bd455aca2 100644 --- a/tests/unit/test_actor_server.py +++ b/tests/unit/test_actor_server.py @@ -495,7 +495,7 @@ def test_request_rate_limit_is_left_out_of_statistics(httpserver: HTTPServer) -> client.actor(_MOCKED_ACTOR_ID).server().request('/flaky') - assert client._statistics.rate_limit_errors == {} + assert client.stats.rate_limit_errors == {} def test_request_returns_last_retried_response(httpserver: HTTPServer) -> None: From 62714d034828427d9d7ba0749eacbf722d718a1c Mon Sep 17 00:00:00 2001 From: Vlada Dusek Date: Mon, 16 Nov 2026 09:17:58 +0100 Subject: [PATCH 07/11] docs: note that only API calls count toward `rate_limit_errors` --- docs/02_concepts/05_retries.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/02_concepts/05_retries.mdx b/docs/02_concepts/05_retries.mdx index d4599d0b4..4bf6a7ca6 100644 --- a/docs/02_concepts/05_retries.mdx +++ b/docs/02_concepts/05_retries.mdx @@ -54,7 +54,7 @@ The client counts its API calls, HTTP requests, and rate limit errors. To read t - `calls` is the number of API calls made through the client. - `requests` is the number of HTTP requests sent, including retries. -- `rate_limit_errors` maps each attempt to the number of rate limit (429) errors it got. Index `0` is the first attempt, index `1` is the first retry, and so on. +- `rate_limit_errors` maps each attempt to the number of rate limit (429) errors it got. Index `0` is the first attempt, index `1` is the first retry, and so on. Only API calls count here. A 429 from an Actor server called through `ActorServerClient.request` is not counted. With a custom HTTP client, `stats` returns the statistics of that client. For details, see [HTTP clients](/api/client/python/docs/concepts/custom-http-clients). From e3310a4e4fbded7bed8af8bafab0cca742281ed9 Mon Sep 17 00:00:00 2001 From: Vlada Dusek Date: Mon, 16 Nov 2026 10:30:54 +0100 Subject: [PATCH 08/11] docs: count Actor server requests in the `calls` and `requests` docs --- docs/02_concepts/05_retries.mdx | 6 +++--- src/apify_client/_statistics.py | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/02_concepts/05_retries.mdx b/docs/02_concepts/05_retries.mdx index 4bf6a7ca6..ee3b547db 100644 --- a/docs/02_concepts/05_retries.mdx +++ b/docs/02_concepts/05_retries.mdx @@ -50,10 +50,10 @@ Retries with exponential backoff help reduce the load on the server and increase ## Request statistics -The client counts its API calls, HTTP requests, and rate limit errors. To read the counts, use the `stats` property. It returns a `ClientStatistics` object with these fields: +The client counts its calls, HTTP requests, and rate limit errors. To read the counts, use the `stats` property. It returns a `ClientStatistics` object with these fields: -- `calls` is the number of API calls made through the client. -- `requests` is the number of HTTP requests sent, including retries. +- `calls` is the number of calls made through the client, including requests to Actor servers. +- `requests` is the number of HTTP requests sent, including retries and requests to Actor servers. - `rate_limit_errors` maps each attempt to the number of rate limit (429) errors it got. Index `0` is the first attempt, index `1` is the first retry, and so on. Only API calls count here. A 429 from an Actor server called through `ActorServerClient.request` is not counted. With a custom HTTP client, `stats` returns the statistics of that client. For details, see [HTTP clients](/api/client/python/docs/concepts/custom-http-clients). diff --git a/src/apify_client/_statistics.py b/src/apify_client/_statistics.py index 18b137dbd..983cd23a8 100644 --- a/src/apify_client/_statistics.py +++ b/src/apify_client/_statistics.py @@ -12,7 +12,7 @@ class ClientStatistics: """Statistics about API client usage and rate limit errors.""" calls: int = 0 - """Total number of API method calls made by the client.""" + """Total number of calls made by the client, including requests to Actor servers.""" requests: int = 0 """Total number of HTTP requests sent, including retries.""" From f0d4d8e14df2d475b074d59b43666ed14c8978a5 Mon Sep 17 00:00:00 2001 From: Vlada Dusek Date: Mon, 16 Nov 2026 10:31:01 +0100 Subject: [PATCH 09/11] docs: explain how to read `rate_limit_errors` without adding keys --- docs/02_concepts/05_retries.mdx | 2 +- src/apify_client/_statistics.py | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/02_concepts/05_retries.mdx b/docs/02_concepts/05_retries.mdx index ee3b547db..3f210b897 100644 --- a/docs/02_concepts/05_retries.mdx +++ b/docs/02_concepts/05_retries.mdx @@ -54,7 +54,7 @@ The client counts its calls, HTTP requests, and rate limit errors. To read the c - `calls` is the number of calls made through the client, including requests to Actor servers. - `requests` is the number of HTTP requests sent, including retries and requests to Actor servers. -- `rate_limit_errors` maps each attempt to the number of rate limit (429) errors it got. Index `0` is the first attempt, index `1` is the first retry, and so on. Only API calls count here. A 429 from an Actor server called through `ActorServerClient.request` is not counted. +- `rate_limit_errors` maps each attempt to the number of rate limit (429) errors it got. Key `0` is the first attempt, key `1` is the first retry, and so on. The field is a `defaultdict`, so reading a missing key adds it. To read a count without changing the dict, use `.get()`. Only API calls count here. A 429 from an Actor server called through `ActorServerClient.request` is not counted. With a custom HTTP client, `stats` returns the statistics of that client. For details, see [HTTP clients](/api/client/python/docs/concepts/custom-http-clients). diff --git a/src/apify_client/_statistics.py b/src/apify_client/_statistics.py index 983cd23a8..a288556d1 100644 --- a/src/apify_client/_statistics.py +++ b/src/apify_client/_statistics.py @@ -18,7 +18,10 @@ class ClientStatistics: """Total number of HTTP requests sent, including retries.""" rate_limit_errors: defaultdict[int, int] = field(default_factory=lambda: defaultdict(int)) - """Number of rate limit (429) errors per attempt, keyed by the 0-based attempt index.""" + """Number of rate limit (429) errors per attempt, keyed by the 0-based attempt index. + + Reading a missing key adds it with a count of `0`. Use `.get()` to read a count without changing the dict. + """ def add_rate_limit_error(self, attempt: int) -> None: """Add rate limit error for specific attempt. From d7eb8f5883bcddd9304f1e8c8cac318fabec6d3a Mon Sep 17 00:00:00 2001 From: Vlada Dusek Date: Mon, 16 Nov 2026 10:31:07 +0100 Subject: [PATCH 10/11] test: import `ClientStatistics` from the public package --- tests/unit/test_http_clients.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/unit/test_http_clients.py b/tests/unit/test_http_clients.py index c0aa15234..b6aa27bd3 100644 --- a/tests/unit/test_http_clients.py +++ b/tests/unit/test_http_clients.py @@ -17,10 +17,9 @@ import impit import pytest -from apify_client import ApifyClient, ApifyClientAsync +from apify_client import ApifyClient, ApifyClientAsync, ClientStatistics from apify_client._consts import MIN_COMPRESSION_SIZE from apify_client._logging import logger_name -from apify_client._statistics import ClientStatistics from apify_client.errors import ApifyApiError, InvalidResponseBodyError from apify_client.http_clients import ( HttpClient, From e11f28bc5c86caa4d1454f00c43a12aec5daafb1 Mon Sep 17 00:00:00 2001 From: Vlada Dusek Date: Mon, 16 Nov 2026 10:31:30 +0100 Subject: [PATCH 11/11] test: cover a custom `HttpClient` subclass and rate limits in `stats` tests --- tests/unit/test_statistics.py | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/tests/unit/test_statistics.py b/tests/unit/test_statistics.py index 534b5520f..085e572c9 100644 --- a/tests/unit/test_statistics.py +++ b/tests/unit/test_statistics.py @@ -1,5 +1,6 @@ from __future__ import annotations +from datetime import timedelta from typing import TYPE_CHECKING import pytest @@ -13,6 +14,14 @@ from pytest_httpserver import HTTPServer +class _CustomHttpClient(ImpitHttpClient): + pass + + +class _CustomHttpClientAsync(ImpitHttpClientAsync): + pass + + @pytest.mark.parametrize( ('attempts', 'expected_errors'), [ @@ -155,11 +164,12 @@ def test_apify_client_exposes_default_http_client_statistics(httpserver: HTTPSer def test_apify_client_exposes_custom_http_client_statistics(httpserver: HTTPServer) -> None: - """Test that ApifyClient.with_custom_http_client points client.stats to the custom HTTP client's stats.""" + """Test that ApifyClient.with_custom_http_client tracks rate limits on a custom HTTP client subclass.""" + httpserver.expect_oneshot_request('/v2/logs/test-id').respond_with_response(Response(status=429)) httpserver.expect_request('/v2/logs/test-id').respond_with_response( Response('ok', status=200, content_type='text/plain') ) - custom_http_client = ImpitHttpClient() + custom_http_client = _CustomHttpClient(min_delay_between_retries=timedelta(milliseconds=1)) client = ApifyClient.with_custom_http_client( 'test-token', api_url=httpserver.url_for('/'), @@ -173,7 +183,8 @@ def test_apify_client_exposes_custom_http_client_statistics(httpserver: HTTPServ client.log('test-id').get() assert client.stats.calls == 1 - assert client.stats.requests == 1 + assert client.stats.requests == 2 + assert client.stats.rate_limit_errors == {0: 1} async def test_apify_client_async_exposes_default_http_client_statistics(httpserver: HTTPServer) -> None: @@ -195,11 +206,12 @@ async def test_apify_client_async_exposes_default_http_client_statistics(httpser async def test_apify_client_async_exposes_custom_http_client_statistics(httpserver: HTTPServer) -> None: - """Test that ApifyClientAsync.with_custom_http_client points client.stats to the custom HTTP client's stats.""" + """Test that ApifyClientAsync.with_custom_http_client tracks rate limits on a custom HTTP client subclass.""" + httpserver.expect_oneshot_request('/v2/logs/test-id').respond_with_response(Response(status=429)) httpserver.expect_request('/v2/logs/test-id').respond_with_response( Response('ok', status=200, content_type='text/plain') ) - custom_http_client = ImpitHttpClientAsync() + custom_http_client = _CustomHttpClientAsync(min_delay_between_retries=timedelta(milliseconds=1)) client = ApifyClientAsync.with_custom_http_client( 'test-token', api_url=httpserver.url_for('/'), @@ -213,4 +225,5 @@ async def test_apify_client_async_exposes_custom_http_client_statistics(httpserv await client.log('test-id').get() assert client.stats.calls == 1 - assert client.stats.requests == 1 + assert client.stats.requests == 2 + assert client.stats.rate_limit_errors == {0: 1}