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 +39 -0
- clientx/_arguments.py +65 -0
- clientx/_builder.py +429 -0
- clientx/_class_setup.py +252 -0
- clientx/_client.py +300 -0
- clientx/_decoding.py +240 -0
- clientx/_endpoint.py +276 -0
- clientx/_method.py +198 -0
- clientx/_planner.py +1281 -0
- clientx/_registry.py +32 -0
- clientx/_signature.py +312 -0
- clientx/_tools.py +440 -0
- clientx/_types.py +313 -0
- clientx/_version.py +5 -0
- clientx/arguments.py +60 -0
- clientx/exceptions.py +61 -0
- clientx/method.py +16 -0
- clientx/py.typed +0 -0
- clientx/tools.py +23 -0
- clientx-0.1.0.dist-info/METADATA +176 -0
- clientx-0.1.0.dist-info/RECORD +23 -0
- clientx-0.1.0.dist-info/WHEEL +4 -0
- clientx-0.1.0.dist-info/licenses/LICENSE +21 -0
clientx/_types.py
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
import ssl
|
|
2
|
+
from collections.abc import Awaitable, Callable, Mapping
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from enum import StrEnum
|
|
5
|
+
from typing import Any, Literal, TypedDict
|
|
6
|
+
|
|
7
|
+
from httpx2 import AsyncBaseTransport, BaseTransport, Limits, Request, Response
|
|
8
|
+
|
|
9
|
+
# httpx2 exports the `USE_CLIENT_DEFAULT` value but not its class, so this is
|
|
10
|
+
# the one place that imports the class from httpx2's private module. Other
|
|
11
|
+
# modules import it from here, so a move upstream is a one-line fix.
|
|
12
|
+
from httpx2._client import UseClientDefault
|
|
13
|
+
|
|
14
|
+
# httpx2's aliases are in its private `_types` module. Other modules import them
|
|
15
|
+
# from here, so a move upstream is a fix in one place.
|
|
16
|
+
from httpx2._types import (
|
|
17
|
+
AuthTypes,
|
|
18
|
+
CertTypes,
|
|
19
|
+
CookieTypes,
|
|
20
|
+
HeaderTypes,
|
|
21
|
+
ProxyTypes,
|
|
22
|
+
QueryParamTypes,
|
|
23
|
+
RequestContent,
|
|
24
|
+
RequestData,
|
|
25
|
+
RequestExtensions,
|
|
26
|
+
RequestFiles,
|
|
27
|
+
TimeoutTypes,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
# --- Request parts and Send ---------------------------------------------------
|
|
32
|
+
class HttpxArgument(StrEnum):
|
|
33
|
+
"""A part of an HTTP request.
|
|
34
|
+
|
|
35
|
+
Each is named after the ``httpx2.Client.build_request`` argument that sets
|
|
36
|
+
it.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
URL = "url"
|
|
40
|
+
PARAMS = "params"
|
|
41
|
+
HEADERS = "headers"
|
|
42
|
+
COOKIES = "cookies"
|
|
43
|
+
CONTENT = "content"
|
|
44
|
+
DATA = "data"
|
|
45
|
+
FILES = "files"
|
|
46
|
+
JSON = "json"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
50
|
+
class Send:
|
|
51
|
+
"""Options that change how a parameter is sent.
|
|
52
|
+
|
|
53
|
+
The helper says where a value goes; ``Send`` says how. Put it in the
|
|
54
|
+
parameter's outermost ``Annotated``, next to the helper, as in
|
|
55
|
+
``Annotated[list[str], Json(), Send(embed=True)]``.
|
|
56
|
+
|
|
57
|
+
Each option applies to some parts of the request only, and one where it
|
|
58
|
+
can't apply raises ``DefinitionError`` when the class is defined, as does a
|
|
59
|
+
``Send`` on a path parameter, nested inside the type, or on a model's field.
|
|
60
|
+
|
|
61
|
+
With several ``Send`` in one ``Annotated``, the last one wins whole, as the
|
|
62
|
+
last helper does, so one on the parameter replaces one from a ``type``
|
|
63
|
+
alias rather than adding to it.
|
|
64
|
+
|
|
65
|
+
Attributes:
|
|
66
|
+
embed: Send a lone ``Json()`` parameter under its alias or name, as a
|
|
67
|
+
field of a JSON object, instead of as the whole body:
|
|
68
|
+
``ids: Annotated[list[str], Json(), Send(embed=True)]`` sends
|
|
69
|
+
``{"ids": [...]}`` rather than ``[...]``. Like FastAPI's
|
|
70
|
+
``Body(embed=True)``. A parameter that's already keyed, a plain
|
|
71
|
+
value or one of several ``Json()`` parameters, is sent the same.
|
|
72
|
+
exclude_unset: Leave out what the caller didn't set, so the server's
|
|
73
|
+
defaults apply: the parameter itself, when the caller didn't pass
|
|
74
|
+
it, and a model's fields that weren't set when it was made (a
|
|
75
|
+
pydantic model's only: a dataclass doesn't record them). For JSON,
|
|
76
|
+
the query string, headers and form.
|
|
77
|
+
exclude_none: Leave out the fields of a pydantic model or pydantic
|
|
78
|
+
dataclass that are ``None``. For JSON, and a form's JSON part
|
|
79
|
+
(``json_part``): the query string, headers and a plain form leave
|
|
80
|
+
out ``None`` already.
|
|
81
|
+
exclude_defaults: Leave out the fields of a pydantic model or pydantic
|
|
82
|
+
dataclass that equal their defaults. For JSON, and for a model
|
|
83
|
+
spread into the query string, headers or form.
|
|
84
|
+
json_part: Send a ``Form()`` parameter's value as its own part of a
|
|
85
|
+
multipart form, as JSON with the ``application/json`` content
|
|
86
|
+
type, as some APIs take a JSON document next to files. The value
|
|
87
|
+
can be anything pydantic can serialize, and the form becomes
|
|
88
|
+
multipart.
|
|
89
|
+
"""
|
|
90
|
+
|
|
91
|
+
embed: bool | None = None
|
|
92
|
+
exclude_unset: bool | None = None
|
|
93
|
+
exclude_none: bool | None = None
|
|
94
|
+
exclude_defaults: bool | None = None
|
|
95
|
+
json_part: bool | None = None
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
# --- Type aliases -------------------------------------------------------------
|
|
99
|
+
type MethodType = Literal["GET", "PUT", "POST", "PATCH", "DELETE", "HEAD", "OPTIONS"]
|
|
100
|
+
|
|
101
|
+
type Decoder = Callable[[Response], object]
|
|
102
|
+
|
|
103
|
+
type EventHook = Callable[[Request], object] | Callable[[Response], object]
|
|
104
|
+
"""A sync hook, called with the request or the response."""
|
|
105
|
+
|
|
106
|
+
type AsyncEventHook = Callable[[Request], Awaitable[object]] | Callable[[Response], Awaitable[object]]
|
|
107
|
+
"""An async hook: like ``EventHook`` but must be an ``async def``."""
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
# --- httpx2's signatures ------------------------------------------------------
|
|
111
|
+
class _HttpxClientOptions(TypedDict, total=False):
|
|
112
|
+
"""The keyword arguments ``Client`` and ``AsyncClient`` share.
|
|
113
|
+
|
|
114
|
+
They differ in ``transport``, ``mounts`` and ``event_hooks``, which take
|
|
115
|
+
sync or async objects, so those live in ``HttpxClientOptions`` and
|
|
116
|
+
``AsyncHttpxClientOptions``.
|
|
117
|
+
|
|
118
|
+
Every constructor parameter except ``base_url`` is included, deprecated ones
|
|
119
|
+
too, so ``ClientX`` and ``AsyncClientX`` can forward ``**kwargs`` to httpx2
|
|
120
|
+
unchanged. They take ``base_url`` as a parameter of their own.
|
|
121
|
+
"""
|
|
122
|
+
|
|
123
|
+
auth: AuthTypes | None
|
|
124
|
+
"""Authentication to apply to every request.
|
|
125
|
+
|
|
126
|
+
An ``Auth``, a (username, password) tuple, or a callable that signs each
|
|
127
|
+
request.
|
|
128
|
+
"""
|
|
129
|
+
|
|
130
|
+
params: QueryParamTypes | None
|
|
131
|
+
"""Query parameters to include in request URLs.
|
|
132
|
+
|
|
133
|
+
A mapping, a list of pairs, a string, or ``QueryParams``.
|
|
134
|
+
"""
|
|
135
|
+
|
|
136
|
+
headers: HeaderTypes | None
|
|
137
|
+
"""HTTP headers to include when sending requests.
|
|
138
|
+
|
|
139
|
+
A mapping, a list of pairs, or ``Headers``.
|
|
140
|
+
"""
|
|
141
|
+
|
|
142
|
+
cookies: CookieTypes | None
|
|
143
|
+
"""Cookie items to include when sending requests."""
|
|
144
|
+
|
|
145
|
+
verify: bool | str | ssl.SSLContext
|
|
146
|
+
"""TLS verification: ``True``, ``False``, or an ``ssl.SSLContext``.
|
|
147
|
+
|
|
148
|
+
``True`` uses the system trust store, and ``False`` turns verification off.
|
|
149
|
+
|
|
150
|
+
Deprecated: a CA-bundle path ``str`` still works but emits a
|
|
151
|
+
``DeprecationWarning``; build an ``ssl.SSLContext`` instead.
|
|
152
|
+
"""
|
|
153
|
+
|
|
154
|
+
cert: CertTypes | None
|
|
155
|
+
"""Client certificate for TLS.
|
|
156
|
+
|
|
157
|
+
A cert file, (cert, key), or (cert, key, password).
|
|
158
|
+
|
|
159
|
+
Deprecated: emits a ``DeprecationWarning``. Build an ``ssl.SSLContext``,
|
|
160
|
+
call ``.load_cert_chain()``, and pass it as ``verify``.
|
|
161
|
+
"""
|
|
162
|
+
|
|
163
|
+
http1: bool
|
|
164
|
+
"""Enable or disable HTTP/1.1 support."""
|
|
165
|
+
|
|
166
|
+
http2: bool
|
|
167
|
+
"""Enable or disable HTTP/2 support."""
|
|
168
|
+
|
|
169
|
+
proxy: ProxyTypes | None
|
|
170
|
+
"""A proxy URL or configuration where all traffic should be routed."""
|
|
171
|
+
|
|
172
|
+
timeout: TimeoutTypes
|
|
173
|
+
"""The default timeouts for requests.
|
|
174
|
+
|
|
175
|
+
Seconds, ``None`` for none, a (connect, read, write, pool) tuple, or a
|
|
176
|
+
``Timeout``.
|
|
177
|
+
"""
|
|
178
|
+
|
|
179
|
+
follow_redirects: bool
|
|
180
|
+
"""Whether to follow HTTP redirect responses."""
|
|
181
|
+
|
|
182
|
+
limits: Limits
|
|
183
|
+
"""Connection pool limits configuration."""
|
|
184
|
+
|
|
185
|
+
max_redirects: int
|
|
186
|
+
"""Maximum number of redirect responses to follow."""
|
|
187
|
+
|
|
188
|
+
trust_env: bool
|
|
189
|
+
"""Enable or disable usage of environment variables for configuration."""
|
|
190
|
+
|
|
191
|
+
default_encoding: str | Callable[[bytes], str | None]
|
|
192
|
+
"""Encoding for response text that has no charset."""
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
class HttpxClientOptions(_HttpxClientOptions, total=False):
|
|
196
|
+
"""Keyword arguments of ``Client.__init__``.
|
|
197
|
+
|
|
198
|
+
``ClientX.__init__`` takes them as ``**kwargs``.
|
|
199
|
+
"""
|
|
200
|
+
|
|
201
|
+
mounts: Mapping[str, BaseTransport | None] | None
|
|
202
|
+
"""Transports for requests whose URLs match a pattern, keyed by pattern."""
|
|
203
|
+
|
|
204
|
+
transport: BaseTransport | None
|
|
205
|
+
"""Transport instance used to send requests over the network."""
|
|
206
|
+
|
|
207
|
+
event_hooks: Mapping[str, list[EventHook]] | None
|
|
208
|
+
"""Event hooks to call while requests and responses are processed.
|
|
209
|
+
|
|
210
|
+
Supported hook types:
|
|
211
|
+
- "request": called with a ``Request`` immediately before it is sent.
|
|
212
|
+
- "response": called with a ``Response`` as soon as the response
|
|
213
|
+
headers are received.
|
|
214
|
+
|
|
215
|
+
Each value is a list of callables, invoked in list order.
|
|
216
|
+
|
|
217
|
+
Note:
|
|
218
|
+
Response hooks run before the body is read. Avoid consuming the body or
|
|
219
|
+
doing blocking work that depends on the full content.
|
|
220
|
+
"""
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
class AsyncHttpxClientOptions(_HttpxClientOptions, total=False):
|
|
224
|
+
"""Keyword arguments of ``AsyncClient.__init__``.
|
|
225
|
+
|
|
226
|
+
The same as ``HttpxClientOptions``, except ``mounts`` and ``transport`` take
|
|
227
|
+
async transports and event hooks must be ``async`` functions.
|
|
228
|
+
"""
|
|
229
|
+
|
|
230
|
+
mounts: Mapping[str, AsyncBaseTransport | None] | None
|
|
231
|
+
"""Transports for requests whose URLs match a pattern, keyed by pattern."""
|
|
232
|
+
|
|
233
|
+
transport: AsyncBaseTransport | None
|
|
234
|
+
"""Transport instance used to send requests over the network."""
|
|
235
|
+
|
|
236
|
+
event_hooks: Mapping[str, list[AsyncEventHook]] | None
|
|
237
|
+
"""Async event hooks to call while requests and responses are processed.
|
|
238
|
+
|
|
239
|
+
Supported hook types:
|
|
240
|
+
- "request": called with a ``Request`` immediately before it is sent.
|
|
241
|
+
- "response": called with a ``Response`` as soon as the response
|
|
242
|
+
headers are received.
|
|
243
|
+
|
|
244
|
+
Each value is a list of ``async`` callables, invoked in list order.
|
|
245
|
+
|
|
246
|
+
Note:
|
|
247
|
+
Response hooks run before the body is read. Avoid consuming the body or
|
|
248
|
+
doing blocking work that depends on the full content.
|
|
249
|
+
"""
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
class BuildRequestKwargs(TypedDict, total=False):
|
|
253
|
+
"""Keyword arguments of ``build_request``, after ``method`` and ``url``.
|
|
254
|
+
|
|
255
|
+
``_builder.build_request`` fills the parts that carry an endpoint's
|
|
256
|
+
arguments, and ``Endpoint.request_arguments`` adds ``timeout``. ClientX
|
|
257
|
+
never sets ``cookies`` or ``extensions``: they're listed so the keys match
|
|
258
|
+
``build_request``'s parameters.
|
|
259
|
+
"""
|
|
260
|
+
|
|
261
|
+
content: RequestContent | None
|
|
262
|
+
"""The raw body: ``str``, ``bytes``, or a sync or async iterable of bytes.
|
|
263
|
+
|
|
264
|
+
A ``Body()`` parameter sets it.
|
|
265
|
+
"""
|
|
266
|
+
|
|
267
|
+
data: RequestData | None
|
|
268
|
+
"""Form fields, form-encoded, or a multipart form with ``files``.
|
|
269
|
+
|
|
270
|
+
``Form()`` parameters set it.
|
|
271
|
+
"""
|
|
272
|
+
|
|
273
|
+
files: RequestFiles | None
|
|
274
|
+
"""Files to upload in a multipart form.
|
|
275
|
+
|
|
276
|
+
``File()`` parameters set it.
|
|
277
|
+
"""
|
|
278
|
+
|
|
279
|
+
json: Any | None
|
|
280
|
+
"""A JSON body.
|
|
281
|
+
|
|
282
|
+
``Json()`` parameters set it.
|
|
283
|
+
"""
|
|
284
|
+
|
|
285
|
+
params: QueryParamTypes | None
|
|
286
|
+
"""Query parameters, merged with the client's.
|
|
287
|
+
|
|
288
|
+
``Query()`` parameters set it.
|
|
289
|
+
"""
|
|
290
|
+
|
|
291
|
+
headers: HeaderTypes | None
|
|
292
|
+
"""HTTP headers, merged with the client's.
|
|
293
|
+
|
|
294
|
+
``Header()`` parameters set it.
|
|
295
|
+
"""
|
|
296
|
+
|
|
297
|
+
cookies: CookieTypes | None
|
|
298
|
+
"""Cookies, merged with the client's.
|
|
299
|
+
|
|
300
|
+
ClientX never sets it: there's no ``Cookie()`` helper.
|
|
301
|
+
"""
|
|
302
|
+
|
|
303
|
+
timeout: TimeoutTypes | UseClientDefault
|
|
304
|
+
"""The request's timeout, or ``USE_CLIENT_DEFAULT`` for the client's.
|
|
305
|
+
|
|
306
|
+
The endpoint's ``timeout=`` sets it.
|
|
307
|
+
"""
|
|
308
|
+
|
|
309
|
+
extensions: RequestExtensions | None
|
|
310
|
+
"""Options for the transport, such as a ``trace`` callback.
|
|
311
|
+
|
|
312
|
+
ClientX never sets it.
|
|
313
|
+
"""
|
clientx/_version.py
ADDED
clientx/arguments.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Request-part helpers built on ``pydantic.Field``, exported by ``clientx``.
|
|
2
|
+
|
|
3
|
+
Each helper takes exactly the arguments of ``pydantic.Field`` and returns its
|
|
4
|
+
``FieldInfo``, marked with the part of the request it goes to. On an endpoint
|
|
5
|
+
parameter, put the helper inside ``Annotated``. ClientX reads it only there, by
|
|
6
|
+
design: a helper given as a parameter's default value isn't read, and a default
|
|
7
|
+
inside the helper raises ``DefinitionError``, so put it after ``=``::
|
|
8
|
+
|
|
9
|
+
class UsersAPI(ClientX):
|
|
10
|
+
@method.post("/users")
|
|
11
|
+
def create(
|
|
12
|
+
self,
|
|
13
|
+
username: Annotated[str, Json(min_length=3)],
|
|
14
|
+
dry_run: Annotated[bool, Query()] = False,
|
|
15
|
+
) -> None: ...
|
|
16
|
+
|
|
17
|
+
Every parameter needs a helper, except one named like a path placeholder,
|
|
18
|
+
which fills it. ClientX doesn't guess where a parameter goes: a parameter
|
|
19
|
+
without a helper raises ``DefinitionError``.
|
|
20
|
+
|
|
21
|
+
A ``Query()``, ``Header()`` or ``Form()`` helper on a model, dataclass or
|
|
22
|
+
mapping parameter sends each of its fields to that part: with
|
|
23
|
+
``filters: Annotated[Filters, Query()]``, each field of ``Filters`` is a query
|
|
24
|
+
parameter. A helper on a model's own field raises ``DefinitionError``, because
|
|
25
|
+
the parameter decides where all of its fields go.
|
|
26
|
+
|
|
27
|
+
The helpers align one-to-one with the arguments of
|
|
28
|
+
``httpx2.Client.build_request`` that carry request data (every argument except
|
|
29
|
+
``method``, ``timeout``, ``extensions`` and ``cookies``), so ``Body`` is httpx's
|
|
30
|
+
raw ``content`` and ``Json`` its ``json``. There's no ``Cookie`` helper: httpx2
|
|
31
|
+
is deprecating per-request cookies, so set cookies on the client instead. Each
|
|
32
|
+
helper, and the argument it marks:
|
|
33
|
+
|
|
34
|
+
``Url`` ``url``
|
|
35
|
+
``Query`` ``params``
|
|
36
|
+
``Header`` ``headers``
|
|
37
|
+
``Body`` ``content``, the raw body
|
|
38
|
+
``Form`` ``data``
|
|
39
|
+
``File`` ``files``
|
|
40
|
+
``Json`` ``json``
|
|
41
|
+
|
|
42
|
+
``Send`` changes how a parameter is sent, put next to its helper in
|
|
43
|
+
``Annotated``: ``ids: Annotated[list[str], Json(), Send(embed=True)]`` sends a
|
|
44
|
+
lone list as ``{"ids": [...]}`` rather than as the whole body.
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
from pydantic import Field
|
|
48
|
+
|
|
49
|
+
from clientx._arguments import bind_argument
|
|
50
|
+
from clientx._types import HttpxArgument, Send
|
|
51
|
+
|
|
52
|
+
Url = bind_argument("Url", HttpxArgument.URL, Field)
|
|
53
|
+
Query = bind_argument("Query", HttpxArgument.PARAMS, Field)
|
|
54
|
+
Header = bind_argument("Header", HttpxArgument.HEADERS, Field)
|
|
55
|
+
Body = bind_argument("Body", HttpxArgument.CONTENT, Field)
|
|
56
|
+
Form = bind_argument("Form", HttpxArgument.DATA, Field)
|
|
57
|
+
File = bind_argument("File", HttpxArgument.FILES, Field)
|
|
58
|
+
Json = bind_argument("Json", HttpxArgument.JSON, Field)
|
|
59
|
+
|
|
60
|
+
__all__ = ["Body", "File", "Form", "Header", "Json", "Query", "Send", "Url"]
|
clientx/exceptions.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Exceptions raised by ClientX.
|
|
2
|
+
|
|
3
|
+
Every exception derives from ``ClientXError``, so ``except ClientXError``
|
|
4
|
+
catches them all. Each also keeps a built-in base, so ``except TypeError`` and
|
|
5
|
+
``except ValueError`` handlers keep working.
|
|
6
|
+
|
|
7
|
+
HTTP errors aren't wrapped: connection errors, timeouts, and
|
|
8
|
+
``httpx2.HTTPStatusError`` for 4xx and 5xx responses come from httpx2.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ClientXError(Exception):
|
|
13
|
+
"""Base class for every exception ClientX raises."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class DefinitionError(ClientXError, TypeError):
|
|
17
|
+
"""Raised for a client, resource or endpoint ClientX can't use as written.
|
|
18
|
+
|
|
19
|
+
Almost all are raised when the class is defined, so a mistake fails when its
|
|
20
|
+
module is imported, not on the first call. The message names the class or
|
|
21
|
+
endpoint, and the fix. It's raised at call time for an endpoint declared
|
|
22
|
+
outside a client or resource class, or called on a resource that isn't
|
|
23
|
+
mounted on a client, or on an object that isn't a client.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ArgumentError(ClientXError, ValueError):
|
|
28
|
+
"""Raised before a request is sent, when an argument's value can't be sent.
|
|
29
|
+
|
|
30
|
+
For example, a path value that's ``None`` or empty: ``/users/{user_id}``
|
|
31
|
+
with ``""`` would call ``/users/``, a different path. The message names the
|
|
32
|
+
parameter and the problem.
|
|
33
|
+
|
|
34
|
+
Attributes:
|
|
35
|
+
parameter: The name of the endpoint parameter the value was passed for.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
def __init__(self, message: str, *, parameter: str) -> None:
|
|
39
|
+
super().__init__(message)
|
|
40
|
+
self.parameter = parameter
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class ToolError(ClientXError):
|
|
44
|
+
"""Raised when a tool call fails, with a message written for a model.
|
|
45
|
+
|
|
46
|
+
``clientx.tools`` raises it for arguments that don't fit, a request that
|
|
47
|
+
couldn't be sent or failed, and a response that doesn't fit the endpoint's
|
|
48
|
+
annotation. The message says what went wrong without the host or query
|
|
49
|
+
string, which can hold credentials, and the original error is its
|
|
50
|
+
``__cause__``, for logs.
|
|
51
|
+
|
|
52
|
+
Attributes:
|
|
53
|
+
tool: The name of the tool that failed, such as ``"users_create"``.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
def __init__(self, message: str, *, tool: str) -> None:
|
|
57
|
+
super().__init__(message)
|
|
58
|
+
self.tool = tool
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
__all__ = ["ArgumentError", "ClientXError", "DefinitionError", "ToolError"]
|
clientx/method.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""The HTTP verb decorators that turn a client's methods into endpoints.
|
|
2
|
+
|
|
3
|
+
Use them as ``@method.get("/users")``.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from clientx._method import Method
|
|
7
|
+
|
|
8
|
+
get = Method("GET")
|
|
9
|
+
post = Method("POST")
|
|
10
|
+
put = Method("PUT")
|
|
11
|
+
patch = Method("PATCH")
|
|
12
|
+
delete = Method("DELETE")
|
|
13
|
+
head = Method("HEAD")
|
|
14
|
+
options = Method("OPTIONS")
|
|
15
|
+
|
|
16
|
+
__all__ = ["delete", "get", "head", "options", "patch", "post", "put"]
|
clientx/py.typed
ADDED
|
File without changes
|
clientx/tools.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Describe a client's endpoints as tools a model can call.
|
|
2
|
+
|
|
3
|
+
``list_tools(client)`` returns one ``Tool`` per endpoint a model can use, on
|
|
4
|
+
the client and the resources mounted on it. Each has a name, a description, a
|
|
5
|
+
JSON Schema of its arguments and of its result, hints from its HTTP method, and
|
|
6
|
+
``call()`` (or ``acall()`` for an async client), which validates a model's
|
|
7
|
+
arguments, calls the endpoint and returns JSON-ready data. A failed call raises
|
|
8
|
+
``ToolError``, with a message written for the model::
|
|
9
|
+
|
|
10
|
+
for tool in list_tools(api):
|
|
11
|
+
print(tool.name, tool.input_schema)
|
|
12
|
+
|
|
13
|
+
tools = {tool.name: tool for tool in list_tools(api)}
|
|
14
|
+
tools["users_search"].call({"name": "Ada"})
|
|
15
|
+
|
|
16
|
+
Nothing here depends on an AI library: register the tools with MCP or another
|
|
17
|
+
framework, which decides how a model sees and calls them.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from clientx._tools import Tool, list_tools
|
|
21
|
+
from clientx.exceptions import ToolError
|
|
22
|
+
|
|
23
|
+
__all__ = ["Tool", "ToolError", "list_tools"]
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: clientx
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A typed, declarative HTTP API client framework for Python
|
|
5
|
+
Keywords: http,api,client,httpx,httpx2,pydantic,typed,declarative
|
|
6
|
+
Author: slatecipher
|
|
7
|
+
Author-email: slatecipher <25094255+slatecipher@users.noreply.github.com>
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Framework :: Pydantic :: 2
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
19
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
20
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Dist: httpx2>=2.10.0
|
|
23
|
+
Requires-Dist: pydantic>=2.12.5
|
|
24
|
+
Requires-Python: >=3.12
|
|
25
|
+
Project-URL: Repository, https://github.com/slatecipher/ClientX
|
|
26
|
+
Project-URL: Issues, https://github.com/slatecipher/ClientX/issues
|
|
27
|
+
Project-URL: Changelog, https://github.com/slatecipher/ClientX/blob/mainline/CHANGELOG.md
|
|
28
|
+
Description-Content-Type: text/markdown
|
|
29
|
+
|
|
30
|
+
<h1 align="center">
|
|
31
|
+
<picture>
|
|
32
|
+
<source media="(prefers-color-scheme: dark)" srcset="docs/assets/logo-dark.svg">
|
|
33
|
+
<source media="(prefers-color-scheme: light)" srcset="docs/assets/logo-light.svg">
|
|
34
|
+
<img alt="ClientX" src="https://raw.githubusercontent.com/slatecipher/ClientX/mainline/docs/assets/logo-light.svg" width="400">
|
|
35
|
+
</picture>
|
|
36
|
+
</h1>
|
|
37
|
+
|
|
38
|
+
<p align="center">
|
|
39
|
+
<em>Typed, declarative HTTP API clients for Python 3.12+.</em>
|
|
40
|
+
</p>
|
|
41
|
+
|
|
42
|
+
<p align="center">
|
|
43
|
+
<a href="https://pypi.org/project/clientx/"><img src="https://img.shields.io/pypi/v/clientx" alt="PyPI"></a>
|
|
44
|
+
<a href="https://pypi.org/project/clientx/"><img src="https://img.shields.io/pypi/pyversions/clientx" alt="Python versions"></a>
|
|
45
|
+
<a href="https://github.com/slatecipher/ClientX/actions/workflows/ci.yml"><img src="https://github.com/slatecipher/ClientX/actions/workflows/ci.yml/badge.svg?branch=mainline" alt="CI"></a>
|
|
46
|
+
<a href="https://github.com/slatecipher/ClientX/blob/mainline/LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue" alt="License: MIT"></a>
|
|
47
|
+
</p>
|
|
48
|
+
|
|
49
|
+
## Overview
|
|
50
|
+
|
|
51
|
+
ClientX is a declarative API client framework designed to make writing and maintaining API clients easier while keeping the client contract explicit and well documented.
|
|
52
|
+
|
|
53
|
+
For client authors, ClientX reduces boilerplate by turning typed endpoint definitions into concrete `httpx2` requests and centralizing request/response behavior. For client consumers, it pushes API contracts and guard rails into the client itself, helping prevent avoidable runtime mistakes and making integrations more predictable.
|
|
54
|
+
|
|
55
|
+
The result is less scaffolding and more focus on outcomes: authors, human or AI, spend less time on plumbing, and the developers and AI agents calling your API spend less time guessing how to use it correctly. The same endpoints become tools an AI model can call, described by your docstrings and type hints, with errors it can act on.
|
|
56
|
+
|
|
57
|
+
## Quickstart
|
|
58
|
+
|
|
59
|
+
<!-- docs_src/readme/quickstart.py -->
|
|
60
|
+
```python
|
|
61
|
+
from typing import Annotated
|
|
62
|
+
|
|
63
|
+
from clientx import ClientX, Header, Json, Query, Resource, method
|
|
64
|
+
from pydantic import BaseModel
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class User(BaseModel):
|
|
68
|
+
id: int
|
|
69
|
+
name: str
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class NewUser(BaseModel):
|
|
73
|
+
name: str
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class Users(Resource, prefix="/users"):
|
|
77
|
+
@method.get("/{user_id}")
|
|
78
|
+
def retrieve(self, user_id: int) -> User:
|
|
79
|
+
"""Fetch one user by ID."""
|
|
80
|
+
...
|
|
81
|
+
|
|
82
|
+
@method.get()
|
|
83
|
+
def search(self, name: Annotated[str | None, Query()] = None) -> list[User]:
|
|
84
|
+
"""List users, or only those with this name."""
|
|
85
|
+
...
|
|
86
|
+
|
|
87
|
+
@method.post()
|
|
88
|
+
def create(
|
|
89
|
+
self,
|
|
90
|
+
user: Annotated[NewUser, Json()],
|
|
91
|
+
request_id: Annotated[str | None, Header()] = None,
|
|
92
|
+
) -> User:
|
|
93
|
+
"""Create a user."""
|
|
94
|
+
...
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class ExampleAPI(ClientX, user_agent="example-app/1.0"):
|
|
98
|
+
users = Users()
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
with ExampleAPI("https://api.example.com") as api:
|
|
102
|
+
user = api.users.retrieve(42) # GET /users/42 -> User
|
|
103
|
+
matches = api.users.search(name="Ada") # GET /users?name=Ada -> list[User]
|
|
104
|
+
new = api.users.create(NewUser(name="Ada"), request_id="r-1") # POST /users, JSON body, request-id header -> User
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
- Endpoint bodies never run. ClientX builds each request from the method's signature, sends it, and decodes the response into the return annotation.
|
|
108
|
+
- Type checkers see the real signatures: `api.users.retrieve(user_id: int) -> User`.
|
|
109
|
+
- A 4xx or 5xx response raises `httpx2.HTTPStatusError`.
|
|
110
|
+
- The `with` block closes the client's connections when it ends. It's optional: a long-lived client is created once and closed with `close()` at shutdown, as [Closing a client](https://github.com/slatecipher/ClientX/blob/mainline/docs/configuration.md#closing-a-client) explains.
|
|
111
|
+
- For async code, subclass `AsyncClientX` and `AsyncResource`, write the endpoints as `async def` methods, and `await` them, as [Async clients](https://github.com/slatecipher/ClientX/blob/mainline/docs/async.md) explains.
|
|
112
|
+
- Using mypy? Turn off its `empty-body` check for your client modules, as [Defining endpoints](https://github.com/slatecipher/ClientX/blob/mainline/docs/endpoints.md#empty-method-bodies-and-mypy) explains.
|
|
113
|
+
|
|
114
|
+
## Why ClientX
|
|
115
|
+
|
|
116
|
+
ClientX is inspired by FastAPI, which reads type hints to define server endpoints. ClientX applies the same idea to the client side:
|
|
117
|
+
|
|
118
|
+
- **The method signature is the contract.** Path placeholders, query parameters, headers and bodies come from the method's parameters and annotations, so there's no request-building code to keep in sync.
|
|
119
|
+
- **The return annotation decodes the response.** `-> User` returns the JSON body validated as a `User`, `-> Iterator[str]` streams it line by line, and `-> Response` returns the response itself.
|
|
120
|
+
- **Type checkers see real types.** Decorated methods keep their signatures, so editors and type checkers see the actual parameters and return types.
|
|
121
|
+
- **Sync or async.** Write endpoints as `def` methods on a `ClientX`, or as `async def` methods on an `AsyncClientX`, with the same decorators.
|
|
122
|
+
- **Mistakes surface early.** A missing return annotation, a parameter that doesn't say where it goes, a placeholder that names no parameter, or a type ClientX can't decode raises an error when the class is defined, not on the first request.
|
|
123
|
+
- **Pydantic v2 throughout.** Send models as JSON bodies, or spread them into query parameters, headers or form fields, and decode responses into models.
|
|
124
|
+
- **Built on httpx2.** A client is an `httpx2.Client`, or an `httpx2.AsyncClient`, so every option is available, including auth, timeouts, proxies and custom transports.
|
|
125
|
+
- **Ready for AI agents.** `clientx.tools` turns each endpoint into a tool a model can call: its description from the docstring, a JSON Schema of its arguments, and errors that tell the model what went wrong, never your credentials.
|
|
126
|
+
|
|
127
|
+
## Features
|
|
128
|
+
|
|
129
|
+
- Declarative endpoint definitions with HTTP verb decorators.
|
|
130
|
+
- Responses decoded from the return annotation, with streaming, and your own decoder when you need one.
|
|
131
|
+
- Path parameters filled from method arguments and percent-encoded (e.g. `"/users/{user_id}"`).
|
|
132
|
+
- Request parts declared with helpers named like FastAPI's (`Query`, `Header`, `Json`, `Body`, `Form`, `File`): every parameter but a path placeholder's says where it goes.
|
|
133
|
+
- Resources that group endpoints under a path prefix.
|
|
134
|
+
- Built-in deprecation warnings per endpoint.
|
|
135
|
+
- Full access to `httpx2.Client` configuration through `ClientX(...)` arguments.
|
|
136
|
+
- Async clients (`AsyncClientX`, `AsyncResource`) with the same decorators, for `async def` endpoints.
|
|
137
|
+
- AI tools from the same endpoints (`clientx.tools`): descriptions from docstrings, JSON Schemas, and errors a model can act on.
|
|
138
|
+
|
|
139
|
+
## Project status
|
|
140
|
+
|
|
141
|
+
ClientX is a passion project that comes from my experience integrating APIs. Every small prototype against a new API means writing the same boilerplate again, and third-party clients are hit or miss. ClientX lets me focus on outcomes rather than plumbing, and I hope it does the same for you. I maintain it in my spare time, so replies may take a while, but issues and pull requests are always welcome.
|
|
142
|
+
|
|
143
|
+
ClientX is pre-1.0, so the API may change between minor versions. Changes are listed in the [changelog](https://github.com/slatecipher/ClientX/blob/mainline/CHANGELOG.md).
|
|
144
|
+
|
|
145
|
+
## Install
|
|
146
|
+
|
|
147
|
+
```bash
|
|
148
|
+
pip install clientx
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
Using an AI coding assistant? Point it at [llms.txt](https://github.com/slatecipher/ClientX/blob/mainline/llms.txt), a compact guide to ClientX's patterns and pitfalls.
|
|
152
|
+
|
|
153
|
+
## Guide
|
|
154
|
+
|
|
155
|
+
- [Defining endpoints](https://github.com/slatecipher/ClientX/blob/mainline/docs/endpoints.md): the verb decorators and their options, the rules for an endpoint method, deprecating endpoints, and endpoint names.
|
|
156
|
+
- [Building requests](https://github.com/slatecipher/ClientX/blob/mainline/docs/requests.md): how parameters become the path, query string, headers and body.
|
|
157
|
+
- [Responses](https://github.com/slatecipher/ClientX/blob/mainline/docs/responses.md): how the return annotation decides what an endpoint returns, streaming, your own decoder, and errors for 4xx and 5xx responses.
|
|
158
|
+
- [Resources](https://github.com/slatecipher/ClientX/blob/mainline/docs/resources.md): grouping endpoints under a path prefix, nesting them, and plain methods for logic such as pagination.
|
|
159
|
+
- [Client configuration](https://github.com/slatecipher/ClientX/blob/mainline/docs/configuration.md): creating and closing a client, the base URL and `User-Agent` class defaults, authentication, logging and event hooks.
|
|
160
|
+
- [Async clients](https://github.com/slatecipher/ClientX/blob/mainline/docs/async.md): `AsyncClientX` and `AsyncResource` for `async def` endpoints, concurrent requests, and async streaming.
|
|
161
|
+
- [Testing](https://github.com/slatecipher/ClientX/blob/mainline/docs/testing.md): testing a client without the network.
|
|
162
|
+
- [AI tools](https://github.com/slatecipher/ClientX/blob/mainline/docs/tools.md): a client's endpoints as tools a model can call.
|
|
163
|
+
- [Errors](https://github.com/slatecipher/ClientX/blob/mainline/docs/errors.md): the errors ClientX raises, and when.
|
|
164
|
+
- [API reference](https://github.com/slatecipher/ClientX/blob/mainline/docs/reference.md): every public name, with its signature and arguments.
|
|
165
|
+
|
|
166
|
+
## Development
|
|
167
|
+
|
|
168
|
+
See [CONTRIBUTING.md](https://github.com/slatecipher/ClientX/blob/mainline/CONTRIBUTING.md) for setup, checks, and conventions.
|
|
169
|
+
|
|
170
|
+
## Acknowledgments
|
|
171
|
+
|
|
172
|
+
ClientX is inspired by FastAPI and built on Pydantic and httpx2, and I'm grateful to the developers behind all three. It's an independent project, though, and isn't affiliated with or endorsed by any of them.
|
|
173
|
+
|
|
174
|
+
## License
|
|
175
|
+
|
|
176
|
+
ClientX is released under the [MIT License](https://github.com/slatecipher/ClientX/blob/mainline/LICENSE).
|