cloudru-qa-http-client 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. cloudru_qa_http_client-1.0.0/.agents/skills/http-client-usage/SKILL.md +227 -0
  2. cloudru_qa_http_client-1.0.0/.agents/skills/http-client-usage/references/options.md +219 -0
  3. cloudru_qa_http_client-1.0.0/.agents/skills/http-client-usage/references/pitfalls.md +53 -0
  4. cloudru_qa_http_client-1.0.0/.gitignore +26 -0
  5. cloudru_qa_http_client-1.0.0/LICENSE +202 -0
  6. cloudru_qa_http_client-1.0.0/PKG-INFO +615 -0
  7. cloudru_qa_http_client-1.0.0/README.md +589 -0
  8. cloudru_qa_http_client-1.0.0/http_client/__init__.py +16 -0
  9. cloudru_qa_http_client-1.0.0/http_client/client.py +603 -0
  10. cloudru_qa_http_client-1.0.0/http_client/config.py +82 -0
  11. cloudru_qa_http_client-1.0.0/http_client/event_hooks.py +159 -0
  12. cloudru_qa_http_client-1.0.0/http_client/options.py +226 -0
  13. cloudru_qa_http_client-1.0.0/http_client/py.typed +1 -0
  14. cloudru_qa_http_client-1.0.0/http_client/types.py +141 -0
  15. cloudru_qa_http_client-1.0.0/http_client/utils/__init__.py +0 -0
  16. cloudru_qa_http_client-1.0.0/http_client/utils/logutils.py +275 -0
  17. cloudru_qa_http_client-1.0.0/http_client/utils/sanitizer.py +59 -0
  18. cloudru_qa_http_client-1.0.0/http_client/utils/traceparent.py +12 -0
  19. cloudru_qa_http_client-1.0.0/pyproject.toml +80 -0
  20. cloudru_qa_http_client-1.0.0/tests/__init__.py +0 -0
  21. cloudru_qa_http_client-1.0.0/tests/conftest.py +77 -0
  22. cloudru_qa_http_client-1.0.0/tests/support/__init__.py +0 -0
  23. cloudru_qa_http_client-1.0.0/tests/support/clients.py +27 -0
  24. cloudru_qa_http_client-1.0.0/tests/support/logs.py +178 -0
  25. cloudru_qa_http_client-1.0.0/tests/support/streams.py +36 -0
  26. cloudru_qa_http_client-1.0.0/tests/support/tls.py +71 -0
  27. cloudru_qa_http_client-1.0.0/tests/test_auth.py +74 -0
  28. cloudru_qa_http_client-1.0.0/tests/test_closing.py +70 -0
  29. cloudru_qa_http_client-1.0.0/tests/test_custom_options.py +85 -0
  30. cloudru_qa_http_client-1.0.0/tests/test_decorators.py +339 -0
  31. cloudru_qa_http_client-1.0.0/tests/test_endpoint.py +114 -0
  32. cloudru_qa_http_client-1.0.0/tests/test_examples.py +24 -0
  33. cloudru_qa_http_client-1.0.0/tests/test_headers.py +136 -0
  34. cloudru_qa_http_client-1.0.0/tests/test_hooks.py +166 -0
  35. cloudru_qa_http_client-1.0.0/tests/test_logging.py +727 -0
  36. cloudru_qa_http_client-1.0.0/tests/test_redirects.py +90 -0
  37. cloudru_qa_http_client-1.0.0/tests/test_request.py +47 -0
  38. cloudru_qa_http_client-1.0.0/tests/test_sanitizer.py +144 -0
  39. cloudru_qa_http_client-1.0.0/tests/test_streaming.py +260 -0
  40. cloudru_qa_http_client-1.0.0/tests/test_timeout.py +94 -0
  41. cloudru_qa_http_client-1.0.0/tests/test_tls.py +106 -0
@@ -0,0 +1,227 @@
1
+ ---
2
+ name: http-client-usage
3
+ description: Building HTTP clients on the http_client library — an httpx wrapper providing constructor options, event hooks, send/stream decorators, request logging with secret masking, and streaming requests. Use when creating a client for an external API, adding an endpoint to an existing client, or configuring authentication, timeouts, retries, TLS, default headers, tracing, or streaming in a project that imports http_client. Key names are HttpClient, AsyncHttpClient, ClientOption, options.with_*, send_decorator, stream_request.
4
+ license: Apache-2.0
5
+ metadata:
6
+ library-version: "1.0.0"
7
+ source: packages/http-client
8
+ ---
9
+
10
+ # Building clients on http_client
11
+
12
+ `http_client` is a thin wrapper around `httpx`. It adds exactly three things:
13
+
14
+ 1. **Constructor options** (`ClientOption`) — configuration is passed as positional arguments to the constructor instead of a dozen keyword parameters.
15
+ 2. **Transport decorators** — wrappers around `send` and `stream_request` for cross-cutting concerns: metrics, caching, plugging in an existing retry library.
16
+ 3. **Request/response logging** with field masking by glom paths.
17
+
18
+ Everything else (`Request`, `Response`, `Auth`, `Timeout`, status codes) is plain `httpx`. Do not invent your own wrappers around what `httpx` already provides.
19
+
20
+ ## Hard rules
21
+
22
+ 1. Subclass `HttpClient` or `AsyncHttpClient`. `BaseHttpClient` is abstract and has no transport; never subclass it directly.
23
+ 2. Configure only through constructor options. Do not assign `client.timeout`, `client.auth`, etc. after construction — `httpx.Client` is already built and the change will not apply.
24
+ 3. Inside endpoint methods call `self.send(request)`, **not** `self.client.send(request)`. The direct call bypasses every decorator.
25
+ 4. Do not add dependencies to the library itself — it must stay lightweight.
26
+ 5. Never write a retry loop, backoff, or circuit breaker by hand. Take the project's existing retry library and mount it via `with_send_decorator`.
27
+
28
+ Before claiming an option cannot do something, check `references/pitfalls.md` — it documents the non-obvious behaviour that trips people up.
29
+
30
+ ## Canonical client (sync)
31
+
32
+ ```python
33
+ import httpx
34
+ from http_client import HttpClient
35
+
36
+
37
+ class OrdersClient(HttpClient):
38
+ """Client for the orders service."""
39
+
40
+ def get_order(self, order_id: str) -> httpx.Response:
41
+ request = self.client.build_request("GET", f"/orders/{order_id}")
42
+ return self.send(request)
43
+
44
+ def create_order(self, payload: dict[str, object]) -> httpx.Response:
45
+ request = self.client.build_request("POST", "/orders", json=payload)
46
+ return self.send(request)
47
+ ```
48
+
49
+ Paths are relative to the `base_url` passed to the constructor — `httpx` joins them.
50
+
51
+ Assembly:
52
+
53
+ ```python
54
+ import logging
55
+
56
+ from http_client import options
57
+ from httpx import BasicAuth
58
+
59
+ client = OrdersClient(
60
+ "https://api.example.com",
61
+ options.with_auth(BasicAuth("admin", "PazzW0rD")),
62
+ options.with_timeout(30),
63
+ options.with_logger(logging.getLogger("orders")),
64
+ options.with_autogenerated_request_id(),
65
+ )
66
+ ```
67
+
68
+ ## Canonical client (async)
69
+
70
+ Exactly two differences: the base class and `await`. The options are identical, including synchronous event hooks — those are wrapped into coroutines automatically.
71
+
72
+ ```python
73
+ class AsyncOrdersClient(AsyncHttpClient):
74
+ async def get_order(self, order_id: str) -> httpx.Response:
75
+ request = self.client.build_request("GET", f"/orders/{order_id}")
76
+ return await self.send(request)
77
+ ```
78
+
79
+ One exception: `send`/`stream_request` decorators for an async client must themselves be async — there is no auto-wrapping for them.
80
+
81
+ ## Choosing how to send
82
+
83
+ | Task | What to call |
84
+ |---|---|
85
+ | Endpoint method in your own client | `self.client.build_request(...)` → `self.send(request)` |
86
+ | One-off call without a custom client | `client.get(...)`, `client.post(...)`, `client.request(method, url, ...)` |
87
+ | Streaming download/upload, method and URL known | `client.stream(method, url, ...)` |
88
+ | Stream from a prepared `httpx.Request` | `client.stream_request(request)` |
89
+
90
+ `send` and `stream_request` are the only points decorators pass through. The `get`/`post`/... shortcuts call `send` internally, so decorators apply to them as well.
91
+
92
+ ## Releasing connections
93
+
94
+ The connection pool is created in the constructor, so every client must be closed. Prefer the context manager:
95
+
96
+ ```python
97
+ with OrdersClient("https://api.example.com") as client:
98
+ client.get_order("42")
99
+
100
+ async with AsyncOrdersClient("https://api.example.com") as client:
101
+ await client.get_order("42")
102
+ ```
103
+
104
+ For a long-lived client, close it explicitly: `client.close()` / `await client.aclose()`.
105
+
106
+ ## Options
107
+
108
+ The full catalog with exact signatures and behaviour is in `references/options.md`. Summary:
109
+
110
+ | Option | Purpose |
111
+ |---|---|
112
+ | `with_auth(auth)` | any httpx authentication mechanism |
113
+ | `with_timeout(timeout)` | client timeout; defaults to 60 s on every phase |
114
+ | `with_logger(logger, sanitize_keys=..., ...)` | request and response logging |
115
+ | `with_default_headers(headers)` | headers applied to every request |
116
+ | `with_request_hook(hook)` / `with_response_hook(hook)` | arbitrary request/response processing |
117
+ | `with_autogenerated_request_id()` | `X-Request-ID` header |
118
+ | `with_autogenerated_traceparent()` | `Traceparent` header (W3C Trace Context) |
119
+ | `with_send_decorator(dec)` / `with_stream_decorator(dec)` | transport wrappers |
120
+ | `with_follow_redirects(max_redirects=20)` | follow redirects |
121
+ | `with_verify_context(verify=...)` / `use_truststore()` | TLS configuration |
122
+
123
+ ### Writing your own option
124
+
125
+ `ClientOption` is `Callable[[BaseHttpClient], None]`. Options receive the actual client inside
126
+ `BaseHttpClient.__init__`, before the httpx transport exists. Use the public configuration properties
127
+ (`timeout`, `auth`, `verify`, `url_suffix`) and registration methods. Accessing `client.client` inside
128
+ an option raises `AttributeError`.
129
+
130
+ ```python
131
+ import httpx
132
+ from http_client import ClientOption
133
+ from http_client.client import BaseHttpClient
134
+
135
+
136
+ def with_api_key(key: str) -> ClientOption:
137
+ def add_key(request: httpx.Request) -> None:
138
+ request.headers["X-Api-Key"] = key
139
+
140
+ def option(client: BaseHttpClient) -> None:
141
+ client.add_request_hook(add_key, prepend=True)
142
+
143
+ return option
144
+ ```
145
+
146
+ Compose options from built-ins or call `add_request_hook`, `add_response_hook`, `add_send_decorator`
147
+ and `add_stream_decorator`. `prepend=True` puts a request hook first. Configuration properties and
148
+ registration methods reject changes after construction with `RuntimeError`.
149
+
150
+ ## Wrapping the transport
151
+
152
+ A decorator wraps `send`, so it sees the request on the way out and the response on the way back. The shape below is the whole pattern — this particular one just records what passed through, which is handy in tests:
153
+
154
+ ```python
155
+ from collections.abc import Callable
156
+ from functools import wraps
157
+
158
+ import httpx
159
+ from http_client.types import SyncSendMethod
160
+
161
+
162
+ def with_call_recorder(calls: list[str]) -> Callable[[SyncSendMethod], SyncSendMethod]:
163
+ def decorator(func: SyncSendMethod) -> SyncSendMethod:
164
+ @wraps(func)
165
+ def wrapper(request: httpx.Request, **kwargs: object) -> httpx.Response:
166
+ calls.append(f"-> {request.method} {request.url}")
167
+ response = func(request, **kwargs)
168
+ calls.append(f"<- {response.status_code}")
169
+ return response
170
+
171
+ return wrapper
172
+
173
+ return decorator
174
+ ```
175
+
176
+ **Do not hand-roll retries, backoff, or circuit breakers here.** They are solved problems with dedicated libraries; check what the project already depends on and plug it in through this hook. Writing the retry loop yourself means reimplementing jitter, budgets, and idempotency rules — and getting them subtly wrong.
177
+
178
+ Annotation types live in `http_client.types`: `SyncSendMethod`, `AsyncSendMethod`, `SyncStreamRequestMethod`, `AsyncStreamRequestMethod` and the matching `*Decorator` aliases.
179
+
180
+ A `stream_request` decorator must itself be a context manager — put `@contextmanager` / `@asynccontextmanager` **below** `@wraps`:
181
+
182
+ ```python
183
+ @wraps(func)
184
+ @contextmanager
185
+ def wrapper(request, **kwargs):
186
+ with func(request, **kwargs) as response:
187
+ yield response
188
+ ```
189
+
190
+ ## Streaming requests
191
+
192
+ ```python
193
+ with client.stream("GET", "/large-file.zip") as response:
194
+ response.raise_for_status()
195
+ with open("file.zip", "wb") as f:
196
+ for chunk in response.iter_bytes(chunk_size=8192):
197
+ f.write(chunk)
198
+ ```
199
+
200
+ ```python
201
+ async with client.stream("GET", "/events") as response:
202
+ async for line in response.aiter_lines():
203
+ handle(line)
204
+ ```
205
+
206
+ A streamed response body shows up in logs as `<streamed content>` — at the time the response hook fires the content has not been read yet. This is not an error.
207
+
208
+ ## Logging
209
+
210
+ `with_logger` installs hooks that emit one record per request and one per response. The records are linked by the `id` field — an internal `trace_id` unrelated to any server-side tracing.
211
+
212
+ Common secrets — `authorization`, `cookie`, `x-api-key`, `password`, `token` and friends — are masked out of the box. `sanitize_keys` adds project-specific paths on top; it does not replace the defaults.
213
+
214
+ Masking is driven by glom paths applied to the body, headers, and query parameters. httpx lowercases header names, so write `"authorization"`, not `"Authorization"`.
215
+
216
+ ```python
217
+ options.with_logger(
218
+ logger,
219
+ sanitize_keys=["authorization", "user.password", "items.*.token"],
220
+ )
221
+ ```
222
+
223
+ Global defaults (level, JSON indent, truncation of long bodies) come from `http_client.configure_logging(...)`. `HTTP_CLIENT_*` environment variables **override** that function's arguments. Details and the full variable list are in `references/options.md`.
224
+
225
+ ## Known pitfalls
226
+
227
+ Before debugging "strange" behaviour, read `references/pitfalls.md`. It covers `url_suffix` join rules, decorator ordering and freezing, Content-Type body filtering, and why options cannot touch the transport.
@@ -0,0 +1,219 @@
1
+ # Option catalog and configuration
2
+
3
+ All options live in `http_client.options`.
4
+
5
+ ## Transport and connection
6
+
7
+ ### `with_timeout(timeout: TimeoutTypes) -> ClientOption`
8
+
9
+ Client timeout. Accepts a number of seconds or an `httpx.Timeout`.
10
+
11
+ The default is `httpx.Timeout(60)`, i.e. 60 seconds for each phase (`connect`, `read`, `write`, `pool`).
12
+
13
+ ```python
14
+ from httpx import Timeout
15
+
16
+ options.with_timeout(Timeout(connect=5.0, read=30.0, write=5.0, pool=1.0))
17
+ ```
18
+
19
+ Precedence: an explicit `timeout=` on the call wins over the client timeout. Passing `timeout=None` on a call deliberately disables the timeout for that request.
20
+
21
+ ### `with_follow_redirects(max_redirects: int = 20) -> ClientOption`
22
+
23
+ Enables redirect following and sets the limit. The default comes from `httpx._config.DEFAULT_MAX_REDIRECTS`.
24
+
25
+ Without this option the client does not follow redirects. Override per request with `client.get(url, follow_redirects=True)`.
26
+
27
+ ### `with_verify_context(*, verify: ssl.SSLContext | str | bool) -> ClientOption`
28
+
29
+ TLS verification context. Accepts an `SSLContext`, a path to a CA bundle (converted to an `SSLContext` internally), or `False` to disable verification. Applies to both `HttpClient` and `AsyncHttpClient`.
30
+
31
+ ⚠️ `False` disables certificate checking entirely — local debugging only, never production.
32
+
33
+ ### `use_truststore() -> ClientOption`
34
+
35
+ Certificate verification through the system trust store. Requires the extra dependency:
36
+
37
+ ```shell
38
+ pip install "cloudru-qa-http-client[truststore]"
39
+ ```
40
+
41
+ Without `truststore` installed it raises `ImportError` with a hint. Internally it calls `with_verify_context`.
42
+
43
+ ## Authentication
44
+
45
+ ### `with_auth(auth: AuthTypes) -> ClientOption`
46
+
47
+ Any httpx authentication mechanism: `BasicAuth`, `DigestAuth`, a callable, or your own `httpx.Auth` subclass.
48
+
49
+ ```python
50
+ from httpx import BasicAuth
51
+
52
+ options.with_auth(BasicAuth("user", "password"))
53
+ options.with_auth(lambda request: request.headers.update({"Authorization": f"Bearer {token}"}))
54
+ ```
55
+
56
+ Override for a single request: `client.get(url, auth=other_auth)`.
57
+ Disable authentication entirely for a request: `client.get(url, anonymous=True)` — `auth` is then not applied at all, not even one passed explicitly. Other per-call arguments such as `follow_redirects` still apply.
58
+
59
+ ## Headers
60
+
61
+ ### `with_default_headers(headers: dict[str, str]) -> ClientOption`
62
+
63
+ Adds a hook that fills in each header only when the request does not already carry it. A value passed per request wins over the default, matching `httpx` semantics.
64
+
65
+ ### `with_autogenerated_request_id() -> ClientOption`
66
+
67
+ An `X-Request-ID` header carrying a random UUID4 per request. The hook is inserted at the **front** of the list, so the identifier is visible to later hooks, including the logging one.
68
+
69
+ ### `with_autogenerated_traceparent() -> ClientOption`
70
+
71
+ A `Traceparent` header in W3C Trace Context format: `00-<32 hex>-<16 hex>-01`. Also inserted at the front of the list.
72
+
73
+ This is standalone generation, not an OpenTelemetry integration: no context is picked up from the current span.
74
+
75
+ ## Event hooks
76
+
77
+ ### `with_request_hook(hook: EventHook) -> ClientOption`
78
+ ### `with_response_hook(hook: EventHook) -> ClientOption`
79
+
80
+ Append a hook to the corresponding list. The contract matches [httpx event hooks](https://www.python-httpx.org/advanced/event-hooks/): the hook receives a `Request` (or `Response`) and its return value is ignored. Mutate the object in place.
81
+
82
+ ```python
83
+ def add_tenant(request: httpx.Request) -> None:
84
+ request.headers["X-Tenant"] = "acme"
85
+ ```
86
+
87
+ For `AsyncHttpClient`, synchronous hooks are wrapped into coroutines during `__init__`, so the same set of options works for both clients. Native async hooks are accepted too; call order is preserved regardless of mixing.
88
+
89
+ ## Transport decorators
90
+
91
+ ### `with_send_decorator(decorator: SendDecorator) -> ClientOption`
92
+ ### `with_stream_decorator(decorator: StreamRequestDecorator) -> ClientOption`
93
+
94
+ Wrap `_send` and `_stream_request` respectively. Composition happens once, in `__init__`:
95
+
96
+ ```python
97
+ for decorator in decorators:
98
+ func = decorator(func)
99
+ ```
100
+
101
+ Consequences:
102
+
103
+ - The last decorator added becomes the outermost.
104
+ - Register decorators only in constructor options; late registration raises `RuntimeError`.
105
+ - For `AsyncHttpClient` the decorator must be async — there is no auto-wrapping, unlike event hooks.
106
+
107
+ Protocol types for annotations are in `http_client.types`.
108
+
109
+ ## Logging
110
+
111
+ ### `with_logger(logger, *, sanitize_keys=None, json_indent=None, use_line_breaks=None, log_level=None, use_default_sanitize_keys=True) -> ClientOption`
112
+
113
+ | Parameter | Type | Meaning |
114
+ |---|---|---|
115
+ | `logger` | `logging.Logger` | where to write |
116
+ | `sanitize_keys` | `Sequence[str] \| None` | glom paths to fields replaced with `****` |
117
+ | `use_default_sanitize_keys` | `bool` | also mask the built-in secret list (default `True`) |
118
+ | `json_indent` | `int \| None` | indent used when serializing JSON parts of the record |
119
+ | `use_line_breaks` | `bool` | newlines between record parts instead of spaces |
120
+ | `log_level` | `int \| None` | record level, defaults to `INFO` |
121
+
122
+ Record format:
123
+
124
+ ```
125
+ Request: id=<uuid> Method: [GET] https://host/path QueryParams: {...} Headers: {...} Body: {...}
126
+ Response: id=<uuid> Status: 200 [OK] Headers: {...} Body: {...}
127
+ ```
128
+
129
+ `id` is an internal identifier linking a request to its response. It is stored in `request.extensions["trace_id"]` and has nothing to do with server-side tracing.
130
+
131
+ Bodies are rendered by `Content-Type`:
132
+
133
+ | `Content-Type` | `Body:` shows |
134
+ |---|---|
135
+ | `application/json` | the parsed, masked, re-serialized body |
136
+ | `text/plain` | the body as is |
137
+ | `application/octet-stream` | the decoded body, or `<binary content (N bytes)>` if it is not text |
138
+ | anything else | `<not logged, content-type: ...>` |
139
+ | absent (no body) | nothing — the `Body:` part is omitted |
140
+
141
+ So an omitted `Body:` means there was no body, while `<not logged, ...>` means there was one and the type is not rendered.
142
+
143
+ A parsing failure in any part never breaks the request — the log gets `<Error parse: ExceptionType>` instead. Only the exception class is recorded: its message could carry fragments of the body or URL.
144
+
145
+ ### Masking
146
+
147
+ A built-in list of common secrets is masked by default — `authorization`, `proxy-authorization`, `cookie`, `set-cookie`, `x-api-key`, `api-key`, `api_key`, `access_token`, `refresh_token`, `password`, `secret`, `token` (`event_hooks.DEFAULT_SANITIZE_KEYS`). Anything in `sanitize_keys` is added on top. Turn the defaults off only with `use_default_sanitize_keys=False`.
148
+
149
+ Masking covers the access-log records this library writes — not `httpx` exceptions, which may carry the full URL including query. Do not put secrets in URLs.
150
+
151
+ `sanitize_keys` is applied to headers, query parameters, and the parsed JSON body — independently, each path is looked up in all three. A path that does not match is silently skipped.
152
+
153
+ Syntax is [glom](https://glom.readthedocs.io/en/latest/):
154
+
155
+ | Path | What it masks |
156
+ |---|---|
157
+ | `authorization` | the `Authorization` header (httpx lowercases names) |
158
+ | `user.password` | a nested object field |
159
+ | `items.*.token` | a field inside every array element |
160
+ | `*.credentials.secret` | a field when the body itself is an array of objects |
161
+
162
+ ### `configure_logging(...)` — global defaults
163
+
164
+ ```python
165
+ from http_client import configure_logging
166
+ from http_client.config import LoggingConfig
167
+
168
+ configure_logging(
169
+ options=LoggingConfig(
170
+ log_level=logging.INFO,
171
+ json_indent=None,
172
+ use_line_breaks=False,
173
+ octet_stream_log_maxlength=1024,
174
+ plain_text_log_maxlength=None,
175
+ json_log_maxlength=None,
176
+ )
177
+ )
178
+ ```
179
+
180
+ Pass a `LoggingConfig` through `options=...`. Its fields set the defaults.
181
+ The function writes to the module-level singleton `LOGGING_CONFIG`, from which the hooks read whenever the corresponding `with_logger` argument was not supplied.
182
+
183
+ **Environment variables override the function arguments**, not the other way round:
184
+
185
+ | Variable | Field |
186
+ |---|---|
187
+ | `HTTP_CLIENT_LOG_LEVEL` | `log_level` (integer) |
188
+ | `HTTP_CLIENT_USE_LINE_BREAKS` | `use_line_breaks` (`true`/`y`/`yes`/`on`) |
189
+ | `HTTP_CLIENT_JSON_INDENT` | `json_indent` |
190
+ | `HTTP_CLIENT_OCTET_STREAM_LOG_MAXLENGTH` | `octet_stream_log_maxlength` |
191
+ | `HTTP_CLIENT_PLAIN_TEXT_LOG_MAXLENGTH` | `plain_text_log_maxlength` |
192
+ | `HTTP_CLIENT_JSON_LOG_MAXLENGTH` | `json_log_maxlength` |
193
+
194
+ The length limits (`*_maxlength`) trim the middle of the string, keeping the head and tail and inserting `...`. They can only be set globally; `with_logger` does not accept them.
195
+
196
+ ## Utilities
197
+
198
+ `http_client.utils.sanitizer.sanitize(value, sensitive_keys)` — masks a dict or list using the same glom paths. Returns a deep copy and leaves the original untouched.
199
+
200
+ `http_client.utils.traceparent.generate()` — a traceparent string.
201
+
202
+ `http_client.utils.logutils.create_request_log` / `create_response_log` — build the same log strings manually.
203
+
204
+ `http_client.utils.logutils` also exports the building blocks those two are made of, so a logger built
205
+ on a different backend renders bodies exactly the same way: `to_json`, `trim`, `decode`, `is_streamed`,
206
+ `is_buffered`, `parse_error`. These helpers are part of the public API.
207
+
208
+ ## Inherited client attributes
209
+
210
+ | Attribute | Where it is set | Purpose |
211
+ |---|---|---|
212
+ | `DEFAULT_URL_SUFFIX` | overridden in the subclass | path prefix injected by the `endpoint()` method |
213
+ | `DEFAULT_TIMEOUT` | overridden in the subclass | default timeout, `httpx.Timeout(60)` |
214
+ | `base_url` | from the constructor | proxies `self.client.base_url` |
215
+ | `client` | created in `__init__` | the underlying `httpx.Client` / `httpx.AsyncClient` |
216
+
217
+ Lifecycle mirrors `httpx` exactly: the connection pool is built in the constructor, `__enter__` / `__aenter__` open it, and `__exit__` / `__aexit__` close it. `HttpClient.close()` and `AsyncHttpClient.aclose()` do the same for a client not used as a context manager — the naming follows `httpx`, so the async client has `aclose()` only. A closed client cannot be reopened; doing so raises `RuntimeError`.
218
+
219
+ `endpoint(path)` joins `url_suffix` with `path`. Leading slashes on `path` and a missing trailing slash on the suffix are both normalized, so `"/u-api/orders/v1"` and `"/u-api/orders/v1/"` behave identically. It accepts relative paths only: an absolute URL or a `..` segment raises `ValueError`.
@@ -0,0 +1,53 @@
1
+ # Pitfalls
2
+
3
+ Non-obvious behaviour that costs time when you hit it unprepared.
4
+
5
+ ## Options run before the httpx client exists
6
+
7
+ Order inside `__init__`: `BaseHttpClient.__init__` creates typed internal configuration and runs
8
+ the options; then `HttpClient.__init__` creates the httpx transport from that configuration.
9
+
10
+ Two consequences:
11
+
12
+ 1. An option that touches `client.client` raises `AttributeError` — there is no transport yet.
13
+ 2. Setting `client.timeout`, `auth`, `verify` or `url_suffix` after construction raises `RuntimeError`.
14
+ Set them through constructor options. For transport-level changes supported by httpx, use its
15
+ public API directly, for example `client.client.timeout`, or rebuild the client.
16
+
17
+ ## Decorators are frozen once
18
+
19
+ Decorators are composed in `__init__`. Register them through constructor options with
20
+ `add_send_decorator` / `add_stream_decorator` or the built-in option factories. Late registration
21
+ raises `RuntimeError`.
22
+
23
+ Composition order is a plain loop:
24
+
25
+ ```python
26
+ for decorator in decorators:
27
+ func = decorator(func)
28
+ ```
29
+
30
+ so the last decorator added ends up outermost and runs first.
31
+
32
+ ## `endpoint()` only accepts relative paths
33
+
34
+ An absolute URL or a `..` segment raises `ValueError` instead of silently escaping the client's base URL. Build cross-host calls with a separate client, not by passing a full URL to `endpoint()`.
35
+
36
+ ## A decorator that sends twice runs the hooks twice
37
+
38
+ Event hooks fire inside `httpx.Client.send`, so a decorator that calls `func()` twice runs every
39
+ request hook twice. The built-in ID hooks preserve existing `X-Request-ID` and `Traceparent` values;
40
+ reusing one request keeps its identifiers stable across retries. A newly built request gets new
41
+ identifiers unless the caller provided them. Other hooks, including logging, still run per attempt.
42
+
43
+ ## Streaming: the logged response body is always a placeholder
44
+
45
+ `stream_request` marks the request with `request.extensions["is_streaming"] = True`. The logging response hook sees the marker and, while the body is unread, writes `Body: <streamed content>`. This is by design — reading the body inside the hook would defeat the purpose of streaming.
46
+
47
+ ## `HttpClient` and `AsyncHttpClient` are declared abstract yet instantiable
48
+
49
+ Both carry `metaclass=ABCMeta`, but the only abstract member, `BaseHttpClient.client`, is implemented in each. So `HttpClient("https://...")` works — the library's own tests rely on it. Subclassing is still the preferred approach, but direct construction is not a mistake.
50
+
51
+ ## False alarms when reading the code
52
+
53
+ - `logutils.create_request_log` writes `r.extensions["trace_id"]`, meaning the logging hook mutates the request. Keep that in mind when comparing `extensions` in tests.
@@ -0,0 +1,26 @@
1
+ /docs/plans/
2
+ .venv/
3
+ .venvs/
4
+ __pycache__/
5
+ *.py[cod]
6
+ .pytest_cache/
7
+ .mypy_cache/
8
+ .ruff_cache/
9
+ .hypothesis/
10
+ .coverage
11
+ coverage.xml
12
+ htmlcov/
13
+ report*.xml
14
+ allure-results/
15
+ allure-report/
16
+ .allure/
17
+ logs/
18
+ *.log
19
+ .env
20
+ .env.*
21
+ .DS_Store
22
+ dist/
23
+ build/
24
+ *.egg-info/
25
+ /packages/*/api/
26
+ .claude/settings.local.json