Skip to content

Commit 6d9d72b

Browse files
authored
docs: Document the transport-hook contract and the built-in HTTPX client (#1013)
Rewrites the HTTP clients concepts page around the three-layer hierarchy and the transport hooks, documents the built-in HTTPX client from #1004 (installation, sync/async examples, timeout semantics), and replaces the old HTTPX guide with "Build a custom HTTP client", which implements full AIOHTTP and requests clients including response adapters for the `HttpResponse` protocol. Stack: #1022 (pipeline) → #1004 (HTTPX client) → **#1013 (this)**. Split out of #1006. *✍️ Drafted by Claude Code*
1 parent 2df25d9 commit 6d9d72b

13 files changed

Lines changed: 368 additions & 175 deletions

‎README.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ For a guided walkthrough — authenticating, running an Actor, and reading its r
135135
- **Tiered timeouts** — short / medium / long tiers picked per endpoint, overridable per call ([Timeouts](https://docs.apify.com/api/client/python/docs/concepts/timeouts)).
136136
- **Pagination and streaming** — iterate datasets, key-value store keys, or live logs without manual paging or buffering ([Pagination](https://docs.apify.com/api/client/python/docs/concepts/pagination), [Streaming](https://docs.apify.com/api/client/python/docs/concepts/streaming-resources)).
137137
- **Convenience methods** — `call()`, `wait_for_finish()`, nested resource access, and other shortcuts that hide platform quirks ([Convenience methods](https://docs.apify.com/api/client/python/docs/concepts/convenience-methods)).
138-
- **Pluggable HTTP layer** — use the default [Impit](https://github.com/apify/impit)-based client, opt in to the built-in [HTTPX](https://github.com/pydantic/httpx2) client, or plug in any custom implementation ([Custom HTTP clients](https://docs.apify.com/api/client/python/docs/concepts/custom-http-clients)).
138+
- **Pluggable HTTP layer** — use the default [Impit](https://github.com/apify/impit)-based client, opt in to the built-in [HTTPX](https://github.com/pydantic/httpx2) client, or plug in any custom implementation ([HTTP clients](https://docs.apify.com/api/client/python/docs/concepts/custom-http-clients)).
139139
- **Structured errors** — every API error surfaces as an [`ApifyApiError`](https://docs.apify.com/api/client/python/reference/class/ApifyApiError) with HTTP-specific subclasses for precise handling ([Error handling](https://docs.apify.com/api/client/python/docs/concepts/error-handling)).
140140
- **Debug logging** — opt-in structured logging on the `apify_client` logger captures request URLs, status codes, retry attempts, and more ([Logging](https://docs.apify.com/api/client/python/docs/concepts/logging)).
141141
@@ -202,8 +202,8 @@ The full documentation lives at **[docs.apify.com/api/client/python](https://doc
202202
| --- | --- |
203203
| [Introduction](https://docs.apify.com/api/client/python/docs) | Overview, prerequisites, and a tour of the client. |
204204
| [Quick start](https://docs.apify.com/api/client/python/docs/quick-start) | Authenticate, run an Actor, and fetch its results step by step. |
205-
| [Concepts](https://docs.apify.com/api/client/python/docs/concepts/asyncio-support) | Asyncio, single vs. collection clients, nested clients, error handling, retries, logging, convenience methods, pagination, streaming, custom HTTP clients, timeouts. |
206-
| [Guides](https://docs.apify.com/api/client/python/docs/guides/passing-input-to-actor) | Pass input to an Actor, manage tasks for reusable input, retrieve Actor data, integrate with data libraries (e.g. Pandas), use HTTPX as the HTTP client. |
205+
| [Concepts](https://docs.apify.com/api/client/python/docs/concepts/asyncio-support) | Asyncio, single vs. collection clients, nested clients, error handling, retries, logging, convenience methods, pagination, streaming, HTTP clients, timeouts. |
206+
| [Guides](https://docs.apify.com/api/client/python/docs/guides/passing-input-to-actor) | Pass input to an Actor, manage tasks for reusable input, retrieve Actor data, integrate with data libraries (e.g. Pandas), build a custom HTTP client. |
207207
| [Upgrading](https://docs.apify.com/api/client/python/docs/upgrading/upgrading-to-v3) | Migrating between major versions. |
208208
| [API reference](https://docs.apify.com/api/client/python/reference) | Generated reference for every class, method, and model. |
209209
| [Changelog](https://docs.apify.com/api/client/python/docs/changelog) | Release history and breaking changes. |

‎docs/01_introduction/index.mdx‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,23 @@ For better request-body compression, opt in to `brotli`, which compresses better
6363

6464
For details, see [HTTP compression](../02_concepts/13_http_compression.mdx).
6565

66+
The client uses [Impit](https://github.com/apify/impit) as its default HTTP transport. To use the built-in [HTTPX](https://github.com/pydantic/httpx2) transport, install the optional `httpx` extra. The extra installs `httpx2`, Pydantic's maintained continuation of HTTPX:
67+
68+
<Tabs>
69+
<TabItem value="PyPI" label="PyPI" default>
70+
```bash
71+
pip install "apify-client[httpx]"
72+
```
73+
</TabItem>
74+
<TabItem value="conda-forge" label="conda-forge">
75+
```bash
76+
conda install conda-forge::apify-client conda-forge::httpx2
77+
```
78+
</TabItem>
79+
</Tabs>
80+
81+
For synchronous and asynchronous examples and details about the shared architecture, see [HTTP clients](../02_concepts/10_custom_http_clients.mdx).
82+
6683
## Quick example
6784

6885
The following example shows how to run an Actor and retrieve its results:

‎docs/02_concepts/10_custom_http_clients.mdx‎

Lines changed: 60 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
---
22
id: custom-http-clients
3-
title: Custom HTTP clients
4-
description: Replace the default HTTP client with a custom implementation.
3+
title: HTTP clients
4+
description: Understand the built-in HTTP clients and the custom client interface.
55
---
66

77
import Tabs from '@theme/Tabs';
@@ -11,22 +11,24 @@ import ApiLink from '@theme/ApiLink';
1111

1212
import DefaultHttpClientAsyncExample from '!!raw-loader!./code/10_default_http_client_async.py';
1313
import DefaultHttpClientSyncExample from '!!raw-loader!./code/10_default_http_client_sync.py';
14+
import HttpxHttpClientAsyncExample from '!!raw-loader!./code/10_httpx_client_async.py';
15+
import HttpxHttpClientSyncExample from '!!raw-loader!./code/10_httpx_client_sync.py';
1416

1517
import ArchitectureImportsExample from '!!raw-loader!./code/10_architecture_imports.py';
1618

1719
import PluggingInAsyncExample from '!!raw-loader!./code/10_plugging_in_async.py';
1820
import PluggingInSyncExample from '!!raw-loader!./code/10_plugging_in_sync.py';
1921

20-
The Apify API client uses a pluggable HTTP client architecture. By default, it ships with an [Impit](https://github.com/apify/impit)-based HTTP client that handles retries, timeouts, passing headers, and more. You can replace it with your own implementation for use cases like custom logging, proxying, request modification, or integrating with a different HTTP library.
22+
The Apify API client uses a pluggable HTTP layer. It ships with an [Impit](https://github.com/apify/impit)-based default, offers [HTTPX](https://github.com/pydantic/httpx2) as an optional built-in alternative, and accepts custom synchronous or asynchronous implementations.
2123

2224
## Default HTTP client
2325

2426
When you create an <ApiLink to="class/ApifyClient">`ApifyClient`</ApiLink> or <ApiLink to="class/ApifyClientAsync">`ApifyClientAsync`</ApiLink> instance, it automatically uses the built-in <ApiLink to="class/ImpitHttpClient">`ImpitHttpClient`</ApiLink> (or <ApiLink to="class/ImpitHttpClientAsync">`ImpitHttpClientAsync`</ApiLink>). This default client provides:
2527

2628
- Automatic retries with exponential backoff for network errors, HTTP 429, and HTTP 5xx responses.
2729
- Configurable timeouts.
28-
- Preparing request data and headers according to the API requirements, including authentication.
29-
- Collecting requests statistics for monitoring and debugging.
30+
- Request compression and preparation of API-compatible data, query parameters, and headers, including authentication.
31+
- API error handling, structured logging, and request statistics.
3032

3133
You can configure the default client through the <ApiLink to="class/ApifyClient">`ApifyClient`</ApiLink> or <ApiLink to="class/ApifyClientAsync">`ApifyClientAsync`</ApiLink> constructor:
3234

@@ -43,35 +45,65 @@ You can configure the default client through the <ApiLink to="class/ApifyClient"
4345
</TabItem>
4446
</Tabs>
4547

48+
## Built-in HTTPX client
49+
50+
The package also provides <ApiLink to="class/HttpxHttpClient">`HttpxHttpClient`</ApiLink> and <ApiLink to="class/HttpxHttpClientAsync">`HttpxHttpClientAsync`</ApiLink>. They use the same request preparation, compression, retry policy, timeout tiers and growth, error handling, logging, and statistics as the default Impit clients, with [HTTPX](https://github.com/pydantic/httpx2) as the transport.
51+
52+
HTTPX is an optional dependency. Install `apify-client[httpx]`, then pass the appropriate client to <ApiLink to="class/ApifyClient#with_custom_http_client">`ApifyClient.with_custom_http_client`</ApiLink>. The extra installs `httpx2`, Pydantic's maintained continuation of HTTPX. Impit remains the default even when the HTTPX extra is installed.
53+
54+
```bash
55+
pip install "apify-client[httpx]"
56+
# or
57+
uv add "apify-client[httpx]"
58+
```
59+
60+
<Tabs>
61+
<TabItem value="HttpxAsyncExample" label="Async client" default>
62+
<CodeBlock className="language-python">
63+
{HttpxHttpClientAsyncExample}
64+
</CodeBlock>
65+
</TabItem>
66+
<TabItem value="HttpxSyncExample" label="Sync client">
67+
<CodeBlock className="language-python">
68+
{HttpxHttpClientSyncExample}
69+
</CodeBlock>
70+
</TabItem>
71+
</Tabs>
72+
73+
Configure retries, timeout tiers, default headers, and compression on the HTTPX client instance. The token passed to `with_custom_http_client` is applied automatically unless the HTTP client already has an `Authorization` header. The examples use the clients as context managers so their connection pools are closed deterministically. If a context manager doesn't fit your application's lifecycle, call `close()` on `HttpxHttpClient` or `await aclose()` on `HttpxHttpClientAsync` during shutdown.
74+
75+
Timeout values are passed to the selected transport. Impit enforces them as a deadline for the whole request, body included. HTTPX applies them to each socket operation instead, so a response whose body arrives slowly keeps resetting the timeout and can outlast both the requested timeout and `timeout_max`. The `no_timeout` option disables HTTPX's timeouts.
76+
4677
## Architecture
4778

48-
The HTTP client system is built on two key abstractions:
79+
Internally, the HTTP client hierarchy has three layers:
80+
81+
- A common internal base contains configuration and utilities shared by synchronous and asynchronous clients, including headers, request-body preparation, parameters, compression, and timeout tiers. It isn't a public extension point.
82+
- <ApiLink to="class/HttpClient">`HttpClient`</ApiLink> and <ApiLink to="class/HttpClientAsync">`HttpClientAsync`</ApiLink> add the synchronous or asynchronous request pipeline, retry loop, transport hooks, and lifecycle interface.
83+
- The built-in Impit and HTTPX classes inherit directly from the corresponding sync or async class and adapt the underlying transport.
4984

50-
- <ApiLink to="class/HttpClient">`HttpClient`</ApiLink> / <ApiLink to="class/HttpClientAsync">`HttpClientAsync`</ApiLink> - Abstract base classes that define the interface. Extend one of these to create a custom HTTP client by implementing the `call` method.
51-
- <ApiLink to="class/HttpResponse">`HttpResponse`</ApiLink> - A [runtime-checkable protocol](https://docs.python.org/3/library/typing.html#typing.runtime_checkable) that defines the expected response shape. Any object with the required attributes and methods satisfies the protocol — no inheritance needed.
85+
`HttpClient.is_timeout_error(exc)` and `HttpClientAsync.is_timeout_error(exc)` are the public, transport-neutral way to tell whether an exception is a timeout, so code built on the client, such as streamed logs, doesn't need to know which transport raised it.
5286

53-
To plug in your custom implementation, use the <ApiLink to="class/ApifyClient#with_custom_http_client">`ApifyClient.with_custom_http_client`</ApiLink> class method.
87+
Responses have their own abstraction. <ApiLink to="class/HttpResponse">`HttpResponse`</ApiLink> is a [runtime-checkable protocol](https://docs.python.org/3/library/typing.html#typing.runtime_checkable) that defines the expected response shape. Any object with the required attributes and methods satisfies the protocol, so no inheritance is needed.
5488

55-
All of these are available as top-level imports from the `apify_client` package:
89+
Custom transport adapters implement the request, error-classification, and lifecycle hooks. They inherit request preparation, retries, timeout growth, API error conversion, logging, and statistics from the base.
90+
91+
The base classes and the response protocol are available from the `apify_client.http_clients` module:
5692

5793
<CodeBlock className="language-python">
5894
{ArchitectureImportsExample}
5995
</CodeBlock>
6096

61-
### The call method
97+
### The transport contract
6298

63-
The `call` method receives all the information needed to make an HTTP request:
99+
The public `call` method provides the shared request pipeline. A concrete transport implements these hooks:
64100

65-
- `method` - HTTP method (`GET`, `POST`, `PUT`, `DELETE`, etc.).
66-
- `url` - Full URL to make the request to.
67-
- `headers` - Additional headers to include.
68-
- `params` - Query parameters to append to the URL.
69-
- `data` - Raw request body (mutually exclusive with `json`).
70-
- `json` - JSON-serializable request body (mutually exclusive with `data`).
71-
- `stream` - Whether to stream the response body.
72-
- `timeout` - Timeout for the request as a `timedelta`.
101+
- `send_request(...)` sends one prepared request and returns an `HttpResponse`, error statuses included. It receives the URL with the query parameters already encoded into it, the headers with the client's default headers already merged in, the body already serialized and compressed, and the timeout for this attempt in seconds. The inherited `call` needs it, so every transport adapter has to implement it. Let the HTTP library's exceptions propagate unwrapped, and leave status handling and <ApiLink to="class/ApifyApiError">`ApifyApiError`</ApiLink> to `call`.
102+
- `is_retryable_transport_error(exc)` classifies transport failures for the shared retry loop. The default classifies nothing as retryable, so a transport that doesn't override it gives up on the first connection failure.
103+
- `is_timeout_error(exc)` identifies transport-specific timeout exceptions for higher-level client features. The default recognizes Python's `TimeoutError`. Timeout classification is independent of retryability, so a timeout the retry loop should retry has to be listed in `is_retryable_transport_error` too.
104+
- `close()` or `aclose()` closes resources owned by the transport. The default does nothing, which is correct for a transport that owns no pool or session.
73105

74-
It must return an object satisfying the <ApiLink to="class/HttpResponse">`HttpResponse`</ApiLink> protocol.
106+
Decorate your implementations with `@override`, as the built-in Impit and HTTPX adapters do, so a type checker catches a misspelled or incompatible override.
75107

76108
### The HTTP response protocol
77109

@@ -92,7 +124,9 @@ It must return an object satisfying the <ApiLink to="class/HttpResponse">`HttpRe
92124
| `aiter_bytes() -> AsyncIterator[bytes]` | Iterate body in chunks (async) |
93125

94126
:::note
95-
Many HTTP libraries, including our default [Impit](https://github.com/apify/impit) or for example [HTTPX](https://www.python-httpx.org/) already satisfy this protocol out of the box.
127+
Many HTTP libraries, including our default [Impit](https://github.com/apify/impit) or for example [HTTPX](https://github.com/pydantic/httpx2) already satisfy this protocol out of the box.
128+
129+
For a streamed response, consume the body inside the streaming context manager with `iter_bytes()` / `aiter_bytes()`, or call `read()` / `aread()` before accessing `content`. Some transports, including HTTPX, intentionally reject `content` on an unread streamed response.
96130
:::
97131

98132
### Plugging it in
@@ -115,18 +149,18 @@ Use the <ApiLink to="class/ApifyClient#with_custom_http_client">`ApifyClient.wit
115149
After that, all API calls made through the client will go through your custom HTTP client.
116150

117151
:::warning
118-
When using a custom HTTP client, you are responsible for constructing the request, handling retries, timeouts, and errors yourself. The default retry logic is not applied.
152+
If you override `call` itself, your implementation becomes responsible for request preparation, retries, timeouts, API error conversion, logging, and statistics. Implementing the transport hooks and inheriting `call` keeps the shared behavior.
119153
:::
120154

121155
## Use cases
122156

123-
Custom HTTP clients might be useful when you need to:
157+
Custom HTTP clients might be useful when the built-in Impit and HTTPX clients don't cover your requirements, for example when you need to:
124158

125-
- **Use a different HTTP library** - Swap Impit for [httpx](https://www.python-httpx.org/), [requests](https://requests.readthedocs.io/), or [aiohttp](https://docs.aiohttp.org/).
159+
- **Use a different HTTP library** - Integrate [requests](https://requests.readthedocs.io/), [aiohttp](https://docs.aiohttp.org/), or another transport.
126160
- **Route through a proxy** - Add proxy support or request routing.
127161
- **Implement custom retry logic** - Use different backoff strategies or retry conditions.
128162
- **Log requests and responses** - Track API calls for debugging or auditing.
129163
- **Modify requests** - Add custom fields, modify the body, or change headers.
130164
- **Collect custom metrics** - Measure request latency, track error rates, or count API calls.
131165

132-
For a step-by-step walkthrough of building a custom HTTP client, see the [Using HTTPX as the HTTP client](/api/client/python/docs/guides/custom-http-client-httpx) guide.
166+
For complete synchronous and asynchronous implementations over a transport with a different response API, see [Build a custom HTTP client](../03_guides/05_custom_http_client.mdx). The <ApiLink to="class/HttpClient">`HttpClient`</ApiLink> and <ApiLink to="class/HttpClientAsync">`HttpClientAsync`</ApiLink> API references document the full contract.
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import asyncio
2+
3+
from apify_client import ApifyClientAsync
4+
from apify_client.http_clients import HttpxHttpClientAsync
5+
6+
TOKEN = 'MY-APIFY-TOKEN'
7+
8+
9+
async def main() -> None:
10+
async with HttpxHttpClientAsync() as http_client:
11+
client = ApifyClientAsync.with_custom_http_client(
12+
token=TOKEN,
13+
http_client=http_client,
14+
)
15+
print(await client.actor('apify/hello-world').get())
16+
17+
18+
if __name__ == '__main__':
19+
asyncio.run(main())
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
from apify_client import ApifyClient
2+
from apify_client.http_clients import HttpxHttpClient
3+
4+
TOKEN = 'MY-APIFY-TOKEN'
5+
6+
7+
def main() -> None:
8+
with HttpxHttpClient() as http_client:
9+
client = ApifyClient.with_custom_http_client(
10+
token=TOKEN,
11+
http_client=http_client,
12+
)
13+
print(client.actor('apify/hello-world').get())
14+
15+
16+
if __name__ == '__main__':
17+
main()

‎docs/02_concepts/code/10_plugging_in_async.py‎

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,34 @@
1-
from typing import Any
1+
from typing_extensions import override
22

33
from apify_client import ApifyClientAsync
44
from apify_client.http_clients import HttpClientAsync, HttpResponse
5-
from apify_client.types import Timeout
65

76
TOKEN = 'MY-APIFY-TOKEN'
87

98

109
class MyHttpClientAsync(HttpClientAsync):
1110
"""Custom async HTTP client."""
1211

13-
async def call(
12+
@override
13+
async def send_request(
1414
self,
1515
*,
1616
method: str,
1717
url: str,
18-
headers: dict[str, str] | None = None,
19-
params: dict[str, Any] | None = None,
20-
data: str | bytes | bytearray | None = None,
21-
json: Any = None,
22-
stream: bool | None = None,
23-
timeout: Timeout = 'medium',
24-
) -> HttpResponse: ...
18+
headers: dict[str, str],
19+
content: bytes | None,
20+
timeout: float | None,
21+
stream: bool,
22+
) -> HttpResponse:
23+
"""Send one request through the custom transport."""
24+
raise NotImplementedError
25+
26+
@override
27+
def is_retryable_transport_error(self, exc: Exception) -> bool:
28+
# List the transport's transient failures here, e.g. its timeout
29+
# and connection errors. Returning False for everything opts out
30+
# of transport retries entirely.
31+
return isinstance(exc, TimeoutError)
2532

2633

2734
async def main() -> None:

0 commit comments

Comments
 (0)