clientx 0.1.0__py3-none-any.whl

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.
clientx/__init__.py ADDED
@@ -0,0 +1,39 @@
1
+ """A typed, declarative HTTP API client framework for Python."""
2
+
3
+ from httpx2 import Auth, Request, Response, Timeout
4
+
5
+ from clientx import method
6
+ from clientx._client import AsyncClientX, AsyncResource, ClientX, Resource
7
+ from clientx._version import __version__
8
+ from clientx.arguments import Body, File, Form, Header, Json, Query, Send, Url
9
+ from clientx.exceptions import ArgumentError, ClientXError, DefinitionError
10
+
11
+ __all__ = [
12
+ # clientx._version
13
+ "__version__",
14
+ # httpx2
15
+ "Auth",
16
+ "Request",
17
+ "Response",
18
+ "Timeout",
19
+ # clientx._client
20
+ "AsyncClientX",
21
+ "AsyncResource",
22
+ "ClientX",
23
+ "Resource",
24
+ # clientx.arguments
25
+ "Body",
26
+ "File",
27
+ "Form",
28
+ "Header",
29
+ "Json",
30
+ "Query",
31
+ "Send",
32
+ "Url",
33
+ # clientx.exceptions
34
+ "ArgumentError",
35
+ "ClientXError",
36
+ "DefinitionError",
37
+ # submodules
38
+ "method",
39
+ ]
clientx/_arguments.py ADDED
@@ -0,0 +1,65 @@
1
+ """The machinery behind the ``clientx.arguments`` helpers.
2
+
3
+ ``clientx.arguments`` builds its helpers with ``bind_argument``. A helper marks
4
+ its ``FieldInfo`` by appending its ``HttpxArgument`` to the metadata. The mark
5
+ isn't public, so how a helper marks its ``FieldInfo`` can change without
6
+ breaking users. ``get_httpx_argument`` reads the mark for the rest of ClientX.
7
+ """
8
+
9
+ import functools
10
+ from collections.abc import Callable
11
+ from typing import Any
12
+
13
+ from pydantic.fields import FieldInfo
14
+
15
+ from clientx._types import HttpxArgument
16
+
17
+
18
+ def get_httpx_argument(field_info: object) -> HttpxArgument | None:
19
+ """Return the request part a helper marked ``field_info`` for, or ``None``.
20
+
21
+ A helper adds one mark. If there are several, the last one wins, as the last
22
+ helper in an ``Annotated`` does.
23
+ """
24
+ if not isinstance(field_info, FieldInfo):
25
+ return None
26
+ return next((meta for meta in reversed(field_info.metadata) if isinstance(meta, HttpxArgument)), None)
27
+
28
+
29
+ def bind_argument[**P](
30
+ name: str,
31
+ location: HttpxArgument,
32
+ field_fn: Callable[P, Any],
33
+ ) -> Callable[P, Any]:
34
+ """Wrap ``field_fn`` so each field it creates is marked for ``location``.
35
+
36
+ The wrapper takes the same arguments as ``field_fn`` (through
37
+ ``ParamSpec``), so editors offer ``pydantic.Field``'s parameters for each
38
+ helper. At runtime it has its own name and docstring, and
39
+ ``functools.wraps`` records ``field_fn`` as the wrapped function, so
40
+ ``help()`` and ``inspect.signature()`` show ``field_fn``'s arguments rather
41
+ than ``*args, **kwargs``.
42
+
43
+ Args:
44
+ name: The helper's name, for its ``__name__`` and ``__qualname__``.
45
+ location: The request part to mark each field for.
46
+ field_fn: The function that creates the ``FieldInfo``, normally
47
+ ``pydantic.Field``.
48
+ """
49
+
50
+ @functools.wraps(field_fn)
51
+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> Any:
52
+ field_info = field_fn(*args, **kwargs)
53
+ field_info.metadata.append(location)
54
+ return field_info
55
+
56
+ wrapper.__name__ = wrapper.__qualname__ = name
57
+ # The public module that exports the helpers, so help() and reprs show the
58
+ # path users import from. functools.wraps copied field_fn's module, such as
59
+ # pydantic.fields.
60
+ wrapper.__module__ = "clientx.arguments"
61
+ wrapper.__doc__ = (
62
+ f"Create a ``pydantic.Field`` for an endpoint parameter that goes to the request's ``{location}``.\n\n"
63
+ "Takes the same arguments as ``pydantic.Field``; see ``help(pydantic.Field)``."
64
+ )
65
+ return wrapper
clientx/_builder.py ADDED
@@ -0,0 +1,429 @@
1
+ """Build one call's request by the endpoint's ``RequestPlan``.
2
+
3
+ ``Endpoint.request_arguments`` calls ``build_request`` with the plan
4
+ ``_planner`` made when the class was defined, the call's arguments, and the
5
+ names the caller passed. The builder only follows the plan: it never reads
6
+ annotations, ``Send`` or the specs, and the only error it raises is
7
+ ``ArgumentError``, before anything is sent, for a path value that would call a
8
+ different path, a value that can't become text or JSON, or a header name or
9
+ value that isn't ASCII.
10
+
11
+ - Path: each placeholder is filled with percent-encoded text, one segment, or
12
+ several for ``{name:path}``. ``.`` and ``..`` are encoded too. A ``None`` or
13
+ empty value, or a ``{name:path}`` value with an empty segment, raises.
14
+ - Text: a value becomes text by one rule, for the path, query, headers and
15
+ form: pydantic's JSON form, so an ``Enum`` is its value, a ``datetime`` ISO
16
+ 8601 text, a number or ``bool`` JSON text (``true``), and a list or dict
17
+ compact JSON text. ``str`` is used only for an object pydantic doesn't know.
18
+ - Query, headers, form: ``None`` is left out, and so is an empty collection
19
+ and a ``None`` item in one. Where the plan says ``many``, a collection
20
+ repeats the key, decided by the value: a ``str`` is one value. A spread
21
+ model or dataclass is dumped with its ``DumpOptions``, then each field is
22
+ sent under its planned key; what a spread mapping, or a model with its own
23
+ model serializer, dumps is sent under its own keys. A header's name and
24
+ value must be ASCII, as httpx2 sends them, or they raise.
25
+ - Not passed: a parameter planned ``only_if_passed`` is left out when the
26
+ caller didn't pass it, so the server's default applies.
27
+ - Files: each file is passed as it is, and a list of them repeats the field.
28
+ A ``None`` in the list is left out. A form field planned ``json_part`` is
29
+ sent among them, as its own part: its JSON, with ``application/json``.
30
+ - JSON fields: each is dumped with its ``DumpOptions``, by alias, into one JSON
31
+ object. ``None`` is left out, unless it was passed explicitly and the plan
32
+ says ``sends_null``: then it's ``null``. With no fields left, there's no
33
+ JSON body.
34
+ - Body: ``Body()`` is passed as it is; a lone JSON body is dumped with its
35
+ ``DumpOptions``. ``None`` means no body, never ``null``.
36
+ - NaN and infinity: JSON can't hold them, so one in a JSON field, body or part
37
+ raises. Values are dumped keeping them, where pydantic would send ``null``.
38
+ """
39
+
40
+ from __future__ import annotations
41
+
42
+ import json
43
+ from collections.abc import Collection, Generator, Iterable, Mapping
44
+ from contextlib import contextmanager
45
+ from typing import Any, cast
46
+ from urllib.parse import quote
47
+
48
+ from pydantic import ConfigDict, TypeAdapter
49
+ from pydantic_core import PydanticSerializationError, to_jsonable_python
50
+
51
+ from clientx._planner import DumpOptions, PathPlaceholder, PlannedParameter, RequestPlan, SpreadParameter
52
+ from clientx._types import BuildRequestKwargs, HttpxArgument
53
+ from clientx.exceptions import ArgumentError
54
+
55
+
56
+ # --- Entry point --------------------------------------------------------------
57
+ def build_request(
58
+ plan: RequestPlan, arguments: Mapping[str, object], passed: Collection[str]
59
+ ) -> tuple[str, BuildRequestKwargs]:
60
+ """Return the URL path and the ``build_request`` arguments for one call.
61
+
62
+ Args:
63
+ plan: The endpoint's plan, from ``plan_request``.
64
+ arguments: The call's arguments by parameter name, defaults filled in.
65
+ passed: The names of the arguments the caller passed, so an explicit
66
+ ``None`` can be told from a default one.
67
+
68
+ Raises:
69
+ ArgumentError: If a path value would change which path is called, a
70
+ value can't become text or JSON, or a header name or value isn't
71
+ ASCII.
72
+ """
73
+ path = _build_path(plan.path, arguments)
74
+ # Each argument's keyed values: params, headers, data and json. Files are a
75
+ # list of pairs instead, so one field can repeat.
76
+ keyed: dict[HttpxArgument, dict[str, object]] = {}
77
+ files: list[tuple[str, object]] = []
78
+ for item in plan.parameters:
79
+ if item.only_if_passed and item.name not in passed:
80
+ continue
81
+ value = arguments[item.name]
82
+ with _converting(item.name):
83
+ if isinstance(item, SpreadParameter):
84
+ if value is not None:
85
+ # A key known only at the call that equals another replaces
86
+ # it, as in dict.update; httpx2 sends both header names
87
+ # that differ only in case. The planner caught every clash
88
+ # it could see.
89
+ keyed.setdefault(item.httpx_argument, {}).update(_spread(item, value))
90
+ elif item.httpx_argument is HttpxArgument.FILES or item.json_part:
91
+ files.extend(_multipart_entries(item, value))
92
+ elif (sent := _keyed_value(item, value, passed)) is not _LEFT_OUT:
93
+ keyed.setdefault(item.httpx_argument, {})[item.key] = sent
94
+
95
+ # Each argument's name is build_request's: "params", "headers", "data"...
96
+ request_arguments: dict[str, object] = {argument.value: values for argument, values in keyed.items() if values}
97
+ if files:
98
+ request_arguments["files"] = files
99
+ body = plan.body
100
+ if body is not None and not (body.only_if_passed and body.name not in passed):
101
+ request_arguments.update(_body(body, arguments[body.name]))
102
+ return path, cast("BuildRequestKwargs", request_arguments)
103
+
104
+
105
+ # What _keyed_value returns for a value that isn't sent at all.
106
+ _LEFT_OUT = object()
107
+
108
+
109
+ def _keyed_value(item: PlannedParameter, value: object, passed: Collection[str]) -> object:
110
+ """Return what's sent under a parameter's key, or ``_LEFT_OUT``.
111
+
112
+ A JSON field is dumped, or is ``null`` for a ``None`` passed explicitly
113
+ where the plan says ``sends_null``. Any other value becomes text. ``None``
114
+ and an empty collection are left out.
115
+ """
116
+ if item.httpx_argument is HttpxArgument.JSON:
117
+ if value is not None:
118
+ return _dump_json(item, value)
119
+ return None if item.sends_null and item.name in passed else _LEFT_OUT
120
+ text = _text_value(value, many=item.many)
121
+ if text is None:
122
+ return _LEFT_OUT
123
+ if item.httpx_argument is HttpxArgument.HEADERS:
124
+ # Headers take one plain value, never a list.
125
+ _check_header(item, item.key, cast("str", text))
126
+ return text
127
+
128
+
129
+ def _check_header(item: PlannedParameter | SpreadParameter, key: str, text: str) -> None:
130
+ """Raise ``ArgumentError`` if a header's name or value isn't ASCII.
131
+
132
+ httpx2 sends both as ASCII, and would raise ``UnicodeEncodeError`` without
133
+ naming the parameter. The planner checked every name it could see; a
134
+ spread mapping's keys exist only at the call.
135
+ """
136
+ if not key.isascii():
137
+ raise ArgumentError(
138
+ f"Can't send {item.name!r}: the header name {key!r} isn't ASCII, and header names must be. No request "
139
+ "was sent.",
140
+ parameter=item.name,
141
+ )
142
+ if not text.isascii():
143
+ raise ArgumentError(
144
+ f"Can't send {item.name!r} as header {key!r}: {text!r} isn't ASCII, and header values must be. Encode "
145
+ "it as the API expects, such as with urllib.parse.quote(). No request was sent.",
146
+ parameter=item.name,
147
+ )
148
+
149
+
150
+ @contextmanager
151
+ def _converting(name: str) -> Generator[None]:
152
+ """Raise ``ArgumentError`` if a parameter's value can't become text.
153
+
154
+ Such as ``bytes`` that aren't UTF-8, or an object pydantic can't
155
+ serialize, so the error names the parameter, and nothing is sent.
156
+ """
157
+ try:
158
+ yield
159
+ except (UnicodeDecodeError, PydanticSerializationError) as error:
160
+ raise ArgumentError(f"Can't send {name!r}: {error}. No request was sent.", parameter=name) from error
161
+
162
+
163
+ # --- The path -----------------------------------------------------------------
164
+ # A "." or ".." segment would move up the path, so it's encoded too.
165
+ _DOT_SEGMENTS = {".": "%2E", "..": "%2E%2E"}
166
+
167
+
168
+ def _build_path(path: tuple[str | PathPlaceholder, ...], arguments: Mapping[str, object]) -> str:
169
+ """Return the path with each placeholder filled with its encoded value.
170
+
171
+ The planner checked that every placeholder names a parameter, so
172
+ ``arguments`` has a value for each.
173
+ """
174
+ parts: list[str] = []
175
+ for part in path:
176
+ if isinstance(part, str):
177
+ parts.append(part)
178
+ continue
179
+ with _converting(part.name):
180
+ parts.append(_encode_path_value(part, arguments[part.name]))
181
+ return "".join(parts)
182
+
183
+
184
+ def _encode_path_value(placeholder: PathPlaceholder, value: object) -> str:
185
+ """Return ``value`` as percent-encoded text for ``placeholder``.
186
+
187
+ Every character that isn't unreserved is encoded, slashes too unless the
188
+ placeholder keeps them, so a value can't add segments, a query string or a
189
+ fragment.
190
+
191
+ Raises:
192
+ ArgumentError: If the value is ``None`` or empty, or, for a
193
+ ``{name:path}`` placeholder, has an empty segment. Each would call a
194
+ different path: ``/users/{user_id}`` with ``""`` would call
195
+ ``/users/``.
196
+ """
197
+ if value is None:
198
+ raise _path_value_error(placeholder, value, "None would be sent as 'null'")
199
+ text = _to_text(value)
200
+ if not text:
201
+ raise _path_value_error(placeholder, value, "an empty value would remove the segment")
202
+ segments = text.split("/") if placeholder.keep_slashes else [text]
203
+ if "" in segments:
204
+ raise _path_value_error(placeholder, value, "a leading, trailing or doubled slash leaves an empty segment")
205
+ return "/".join(_DOT_SEGMENTS.get(segment) or quote(segment, safe="") for segment in segments)
206
+
207
+
208
+ def _path_value_error(placeholder: PathPlaceholder, value: object, problem: str) -> ArgumentError:
209
+ """Return the error for a value that would call a different path."""
210
+ return ArgumentError(
211
+ f"Can't fill {placeholder} with {value!r}: {problem}, so a different path would be called. "
212
+ "No request was sent.",
213
+ parameter=placeholder.name,
214
+ )
215
+
216
+
217
+ # --- Parameters sent under a key ----------------------------------------------
218
+ def _text_value(value: object, *, many: bool) -> str | list[str] | None:
219
+ """Return a query, header or form value as text, or ``None`` to omit it.
220
+
221
+ ``None`` is left out, and so is an empty collection: "no values" behaves
222
+ like "no value". A ``None`` item in a collection is left out too. Where
223
+ ``many`` allows a collection, the value decides: a ``str`` passed for a
224
+ ``Sequence[str]`` is one value, not one per character.
225
+ """
226
+ if value is None:
227
+ return None
228
+ if not (many and _is_several(value)):
229
+ return _to_text(value)
230
+ texts = [_to_text(item) for item in cast("Iterable[object]", value) if item is not None]
231
+ return texts or None
232
+
233
+
234
+ def _is_several(value: object, *, tuples_too: bool = True) -> bool:
235
+ """Return whether the value is a collection of values, rather than one.
236
+
237
+ ``str`` and ``bytes`` are collections, but each is one value. A file's
238
+ tuple is one file, so files pass ``tuples_too=False``.
239
+ """
240
+ if not isinstance(value, Collection) or isinstance(value, str | bytes | bytearray | Mapping):
241
+ return False
242
+ return tuples_too or not isinstance(value, tuple)
243
+
244
+
245
+ def _spread(item: SpreadParameter, value: object) -> dict[str, object]:
246
+ """Return a spread parameter's fields as text, by the key each goes under.
247
+
248
+ A model or dataclass is dumped with the plan's ``DumpOptions`` first, so a
249
+ field ``exclude_unset`` leaves out isn't sent; then each field the plan
250
+ lists is sent under its planned key. What a mapping, or a model with its
251
+ own model serializer, dumps is sent under its own keys. A field that's
252
+ ``None`` or an empty collection is left out.
253
+
254
+ Raises:
255
+ ArgumentError: If a model's own serializer dumps it to something other
256
+ than a mapping, which can't be spread, or a header's name or value
257
+ isn't ASCII.
258
+ """
259
+ if item.keys is None:
260
+ source = dict(cast("Mapping[object, object]", value)) if isinstance(value, Mapping) else value
261
+ dumped = _dump(source, item.dump, by_alias=True)
262
+ if not isinstance(dumped, dict):
263
+ raise ArgumentError(
264
+ f"Can't spread {item.name!r}: it dumps to {type(dumped).__name__}, not a mapping of keys to "
265
+ "values. No request was sent.",
266
+ parameter=item.name,
267
+ )
268
+ pairs = [(str(key), field) for key, field in cast("dict[object, object]", dumped).items()]
269
+ else:
270
+ dumped = cast("dict[str, object]", _dump(value, item.dump, by_alias=False))
271
+ pairs = [(key, dumped[attribute]) for attribute, key in item.keys if attribute in dumped]
272
+ fields: dict[str, object] = {}
273
+ for key, field in pairs:
274
+ # Dumped to JSON-ready data, so any collection is a list by now. It
275
+ # repeats the key where the argument takes lists; in a header, it's one
276
+ # value, JSON text.
277
+ text = _text_value(field, many=item.many and isinstance(field, list))
278
+ if text is not None:
279
+ fields[key] = text
280
+ if item.httpx_argument is HttpxArgument.HEADERS:
281
+ for key, text in fields.items():
282
+ _check_header(item, key, cast("str", text))
283
+ return fields
284
+
285
+
286
+ def _multipart_entries(item: PlannedParameter, value: object) -> list[tuple[str, object]]:
287
+ """Return what a parameter adds to httpx2's ``files=``, as key-value pairs.
288
+
289
+ A file parameter's files, or a form field's JSON part: a part with no
290
+ filename, holding its JSON, with ``application/json``.
291
+ """
292
+ if not item.json_part:
293
+ return [(item.key, file) for file in _files(item, value)]
294
+ if value is None:
295
+ return []
296
+ return [(item.key, (None, _json_text(item, value), "application/json"))]
297
+
298
+
299
+ def _files(item: PlannedParameter, value: object) -> list[object]:
300
+ """Return the files to send under the parameter's key, as they are.
301
+
302
+ One file, or each file of a collection, which repeats the field. ``None``,
303
+ an empty collection and a ``None`` in one send none. A tuple is one file,
304
+ ``(filename, content...)``, and ``bytes`` are one file's content.
305
+ """
306
+ if value is None:
307
+ return []
308
+ several = item.many and _is_several(value, tuples_too=False)
309
+ files = list(cast("Iterable[object]", value)) if several else [value]
310
+ return [file for file in files if file is not None]
311
+
312
+
313
+ # --- The body -----------------------------------------------------------------
314
+ def _body(body: PlannedParameter, value: object) -> dict[str, object]:
315
+ """Return the ``build_request`` argument for the whole body, if any.
316
+
317
+ ``Body()`` is passed as it is, as ``content``; a lone JSON body is dumped as
318
+ ``json``. ``None`` means no body, never ``null``.
319
+ """
320
+ if value is None:
321
+ return {}
322
+ if body.httpx_argument is HttpxArgument.CONTENT:
323
+ return {"content": value}
324
+ return {"json": _dump_json(body, value)}
325
+
326
+
327
+ # --- Text ---------------------------------------------------------------------
328
+ def _to_text(value: object) -> str:
329
+ """Return ``value`` as the text that's sent for it.
330
+
331
+ It's pydantic's JSON form: an ``Enum`` becomes its value, a ``datetime``
332
+ ISO 8601 text, a ``UUID`` or ``Decimal`` its string, a number or ``bool``
333
+ JSON text (``2``, ``true``), and a list or dict compact JSON text, with
334
+ text as it is, as in a JSON body. Only an object pydantic doesn't know uses
335
+ ``str``: the ``Any`` escape hatch.
336
+ """
337
+ jsonable = to_jsonable_python(value, fallback=str)
338
+ return jsonable if isinstance(jsonable, str) else _compact_json(jsonable, allow_nan=True)
339
+
340
+
341
+ # --- Dumping values -----------------------------------------------------------
342
+ # Dumps a value by its own type, at the call: models nested anywhere in it get
343
+ # the dump options too, as in list[User]. NaN and infinity are kept, where
344
+ # pydantic would make them None everywhere but in a model's float field, so a
345
+ # JSON value holding one raises, and a text value is sent as NaN or Infinity,
346
+ # as a float is.
347
+ _BY_VALUE = TypeAdapter[Any](Any, config=ConfigDict(ser_json_inf_nan="constants"))
348
+
349
+
350
+ def _dump(value: object, dump: DumpOptions, *, by_alias: bool) -> object:
351
+ """Return a spread value's fields as JSON-ready data, with dump options.
352
+
353
+ A model is dumped by attribute name, which the plan maps to keys; a
354
+ mapping, or a model with its own model serializer, by alias. A field
355
+ pydantic doesn't know uses ``str``: the ``Any`` escape hatch, as for any
356
+ text value.
357
+ """
358
+ return _BY_VALUE.dump_python(
359
+ value,
360
+ mode="json",
361
+ by_alias=by_alias,
362
+ exclude_unset=dump.exclude_unset,
363
+ exclude_none=dump.exclude_none,
364
+ exclude_defaults=dump.exclude_defaults,
365
+ fallback=str,
366
+ )
367
+
368
+
369
+ def _json_text(item: PlannedParameter, value: object) -> str:
370
+ """Return a value as JSON text, for a JSON part of a form."""
371
+ return _encode_json(item, _jsonable(item, value))
372
+
373
+
374
+ def _dump_json(item: PlannedParameter, value: object) -> object:
375
+ """Return a JSON field's or body's value as JSON-ready data.
376
+
377
+ httpx2 encodes it when it builds the request. It's encoded once here first,
378
+ so a value JSON can't hold raises here, naming the parameter.
379
+ """
380
+ dumped = _jsonable(item, value)
381
+ _encode_json(item, dumped)
382
+ return dumped
383
+
384
+
385
+ def _jsonable(item: PlannedParameter, value: object) -> object:
386
+ """Return a JSON value dumped as JSON-ready data, by alias.
387
+
388
+ There's no ``str`` fallback here: JSON has no one text form for an object
389
+ pydantic doesn't know.
390
+
391
+ Raises:
392
+ ArgumentError: If pydantic can't serialize the value, as for a class it
393
+ doesn't know passed through ``Any``. No request is sent.
394
+ """
395
+ try:
396
+ return _BY_VALUE.dump_python(
397
+ value,
398
+ mode="json",
399
+ by_alias=True,
400
+ exclude_unset=item.dump.exclude_unset,
401
+ exclude_none=item.dump.exclude_none,
402
+ exclude_defaults=item.dump.exclude_defaults,
403
+ )
404
+ except PydanticSerializationError as error:
405
+ raise ArgumentError(
406
+ f"Can't send {item.name!r} as JSON: {error}. Pass a value pydantic can serialize, such as a model, "
407
+ "dataclass, dict or list, or convert it at the call. No request was sent.",
408
+ parameter=item.name,
409
+ ) from error
410
+
411
+
412
+ def _encode_json(item: PlannedParameter, data: object) -> str:
413
+ """Return JSON-ready data as JSON text, as httpx2 encodes a JSON body.
414
+
415
+ Raises:
416
+ ArgumentError: If the data holds NaN or infinity, which JSON can't. No
417
+ request is sent.
418
+ """
419
+ try:
420
+ return _compact_json(data, allow_nan=False)
421
+ except ValueError as error:
422
+ raise ArgumentError(
423
+ f"Can't send {item.name!r} as JSON: {error}. No request was sent.", parameter=item.name
424
+ ) from error
425
+
426
+
427
+ def _compact_json(data: object, *, allow_nan: bool) -> str:
428
+ """Return JSON text as httpx2 encodes it: compact, with text as it is."""
429
+ return json.dumps(data, separators=(",", ":"), ensure_ascii=False, allow_nan=allow_nan)