tigrbl_client 0.2.2.dev7__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.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2025] [Jacob Stewart @ Swarmauri]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,80 @@
1
+ Metadata-Version: 2.4
2
+ Name: tigrbl_client
3
+ Version: 0.2.2.dev7
4
+ Summary: A client for Tigrbl servers by Swarmauri.
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ Keywords: tigrbl,sdk,standards,client
8
+ Author: Jacob Stewart
9
+ Author-email: jacob@swarmauri.com
10
+ Requires-Python: >=3.10,<3.13
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Requires-Dist: fastapi (>=0.100.0)
20
+ Requires-Dist: pydantic (>=2.0.0)
21
+ Requires-Dist: swarmauri_base
22
+ Requires-Dist: swarmauri_core
23
+ Requires-Dist: swarmauri_standard
24
+ Description-Content-Type: text/markdown
25
+
26
+ ![Tigrbl Logo](https://raw.githubusercontent.com/swarmauri/swarmauri-sdk/master/assets/tigrbl_full_logo.png)
27
+
28
+ <p align="center">
29
+ <a href="https://pypi.org/project/tigrbl_client/">
30
+ <img src="https://img.shields.io/pypi/v/tigrbl_client?label=tigrbl_client&color=green" alt="PyPI - tigrbl_client"/>
31
+ </a>
32
+ <a href="https://pypi.org/project/tigrbl_client/">
33
+ <img src="https://img.shields.io/pypi/dm/tigrbl_client" alt="PyPI - Downloads"/>
34
+ </a>
35
+ <a href="https://pypi.org/project/tigrbl_client/">
36
+ <img src="https://img.shields.io/pypi/pyversions/tigrbl_client" alt="PyPI - Python Version"/>
37
+ </a>
38
+ <a href="https://pypi.org/project/tigrbl_client/">
39
+ <img src="https://img.shields.io/pypi/l/tigrbl_client" alt="PyPI - License"/>
40
+ </a>
41
+ <a href="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/standards/tigrbl_client/">
42
+ <img alt="Hits" src="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/standards/tigrbl_client.svg"/>
43
+ </a>
44
+ </p>
45
+
46
+ ---
47
+
48
+ # Tigrbl Client 🐅
49
+
50
+ A lightweight HTTP client for interacting with Tigrbl services.
51
+ Tigrbl exposes operations under resource-based namespaces such as
52
+ `api.core.Users.create` or `api.rpc.Users.login`, all accessible via
53
+ this client.
54
+
55
+ ## Features ✨
56
+
57
+ - Minimal dependencies with friendly typing
58
+ - Automatic JSON serialization / deserialization
59
+ - Simple namespace-based method access
60
+
61
+ ## Installation 📦
62
+
63
+ ```bash
64
+ pip install tigrbl_client
65
+ ```
66
+
67
+ ## Quick Start 🚀
68
+
69
+ ```python
70
+ from tigrbl_client import Client
71
+
72
+ client = Client("https://api.tigrbl.io", token="your-token")
73
+ response = client.api.core.Users.read(id=1)
74
+ print(response)
75
+ ```
76
+
77
+ ## License 📝
78
+
79
+ This project is licensed under the terms of the [MIT license](LICENSE).
80
+
@@ -0,0 +1,54 @@
1
+ ![Tigrbl Logo](https://raw.githubusercontent.com/swarmauri/swarmauri-sdk/master/assets/tigrbl_full_logo.png)
2
+
3
+ <p align="center">
4
+ <a href="https://pypi.org/project/tigrbl_client/">
5
+ <img src="https://img.shields.io/pypi/v/tigrbl_client?label=tigrbl_client&color=green" alt="PyPI - tigrbl_client"/>
6
+ </a>
7
+ <a href="https://pypi.org/project/tigrbl_client/">
8
+ <img src="https://img.shields.io/pypi/dm/tigrbl_client" alt="PyPI - Downloads"/>
9
+ </a>
10
+ <a href="https://pypi.org/project/tigrbl_client/">
11
+ <img src="https://img.shields.io/pypi/pyversions/tigrbl_client" alt="PyPI - Python Version"/>
12
+ </a>
13
+ <a href="https://pypi.org/project/tigrbl_client/">
14
+ <img src="https://img.shields.io/pypi/l/tigrbl_client" alt="PyPI - License"/>
15
+ </a>
16
+ <a href="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/standards/tigrbl_client/">
17
+ <img alt="Hits" src="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/standards/tigrbl_client.svg"/>
18
+ </a>
19
+ </p>
20
+
21
+ ---
22
+
23
+ # Tigrbl Client 🐅
24
+
25
+ A lightweight HTTP client for interacting with Tigrbl services.
26
+ Tigrbl exposes operations under resource-based namespaces such as
27
+ `api.core.Users.create` or `api.rpc.Users.login`, all accessible via
28
+ this client.
29
+
30
+ ## Features ✨
31
+
32
+ - Minimal dependencies with friendly typing
33
+ - Automatic JSON serialization / deserialization
34
+ - Simple namespace-based method access
35
+
36
+ ## Installation 📦
37
+
38
+ ```bash
39
+ pip install tigrbl_client
40
+ ```
41
+
42
+ ## Quick Start 🚀
43
+
44
+ ```python
45
+ from tigrbl_client import Client
46
+
47
+ client = Client("https://api.tigrbl.io", token="your-token")
48
+ response = client.api.core.Users.read(id=1)
49
+ print(response)
50
+ ```
51
+
52
+ ## License 📝
53
+
54
+ This project is licensed under the terms of the [MIT license](LICENSE).
@@ -0,0 +1,75 @@
1
+ [project]
2
+ name = "tigrbl_client"
3
+ version = "0.2.2.dev7"
4
+ description = "A client for Tigrbl servers by Swarmauri."
5
+ license = "Apache-2.0"
6
+ readme = "README.md"
7
+ repository = "http://github.com/swarmauri/swarmauri-sdk"
8
+ requires-python = ">=3.10,<3.13"
9
+ classifiers = [
10
+ "License :: OSI Approved :: Apache Software License",
11
+ "Development Status :: 3 - Alpha",
12
+ "Programming Language :: Python :: 3.10",
13
+ "Programming Language :: Python :: 3.11",
14
+ "Programming Language :: Python :: 3.12",
15
+ "Programming Language :: Python",
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3 :: Only",
18
+ ]
19
+ authors = [{ name = "Jacob Stewart", email = "jacob@swarmauri.com" }]
20
+ dependencies = [
21
+ "swarmauri_core",
22
+ "swarmauri_base",
23
+ "swarmauri_standard",
24
+ "fastapi>=0.100.0",
25
+ "pydantic>=2.0.0",
26
+ ]
27
+ keywords = [
28
+ 'tigrbl',
29
+ 'sdk',
30
+ 'standards',
31
+ 'client',
32
+ ]
33
+
34
+ [tool.uv.sources]
35
+ swarmauri_core = { workspace = true }
36
+ swarmauri_base = { workspace = true }
37
+ swarmauri_standard = { workspace = true }
38
+
39
+ [tool.pytest.ini_options]
40
+ norecursedirs = ["combined", "scripts"]
41
+ markers = [
42
+ "test: standard test",
43
+ "unit: Unit tests",
44
+ "i9n: Integration tests",
45
+ "r8n: Regression tests",
46
+ "timeout: mark test to timeout after X seconds",
47
+ "xpass: Expected passes",
48
+ "xfail: Expected failures",
49
+ "acceptance: Acceptance tests",
50
+ "perf: Performance tests that measure execution time and resource usage",
51
+ ]
52
+ timeout = 300
53
+ log_cli = true
54
+ log_cli_level = "INFO"
55
+ log_cli_format = "%(asctime)s [%(levelname)s] %(message)s"
56
+ log_cli_date_format = "%Y-%m-%d %H:%M:%S"
57
+ asyncio_default_fixture_loop_scope = "function"
58
+
59
+ [build-system]
60
+ requires = ["poetry-core>=1.0.0"]
61
+ build-backend = "poetry.core.masonry.api"
62
+
63
+ [dependency-groups]
64
+ dev = [
65
+ "pytest>=8.0",
66
+ "pytest-asyncio>=0.24.0",
67
+ "pytest-xdist>=3.6.1",
68
+ "pytest-json-report>=1.5.0",
69
+ "python-dotenv",
70
+ "requests>=2.32.3",
71
+ "flake8>=7.0",
72
+ "pytest-timeout>=2.3.1",
73
+ "ruff>=0.9.9",
74
+ "pytest-benchmark>=4.0.0",
75
+ ]
@@ -0,0 +1,128 @@
1
+ # tigrbl_client/__init__.py
2
+ from __future__ import annotations
3
+
4
+ import httpx
5
+ from typing import TypeVar
6
+
7
+ from ._rpc import RPCMixin, _Schema
8
+ from ._crud import CRUDMixin
9
+ from ._nested_crud import NestedCRUDMixin
10
+
11
+ T = TypeVar("T")
12
+
13
+
14
+ # Re-export the Schema protocol for public use
15
+ __all__ = ["TigrblClient", "_Schema"]
16
+
17
+
18
+ class TigrblClient(RPCMixin, CRUDMixin, NestedCRUDMixin):
19
+ """
20
+ Unified API client supporting both JSON-RPC and REST CRUD operations.
21
+
22
+ Features:
23
+ * JSON-RPC calls with optional Pydantic schema validation
24
+ * REST CRUD operations (GET, POST, PUT, PATCH, DELETE)
25
+ * Async versions of all operations (aget, apost, aput, apatch, adelete)
26
+ * Connection pooling via httpx.Client
27
+ * Optional Pydantic schema validation for requests and responses
28
+ * Placeholder for future nested CRUD operations
29
+ * Works with Tigrbl services that expose operations via resource-based
30
+ namespaces (e.g., ``api.core.Users.create`` or ``api.rpc.Users.login``)
31
+
32
+ Examples:
33
+ # JSON-RPC usage
34
+ client = TigrblClient("http://api.example.com/rpc")
35
+ result = client.call("user.get", params={"id": 123})
36
+
37
+ # REST CRUD usage
38
+ client = TigrblClient("http://api.example.com")
39
+ user = client.get("/users/123")
40
+ new_user = client.post("/users", data={"name": "John", "email": "john@example.com"})
41
+
42
+ # Async usage
43
+ user = await client.aget("/users/123")
44
+ result = await client.apost("/users", data={"name": "Jane"})
45
+ """
46
+
47
+ def __init__(
48
+ self,
49
+ endpoint: str,
50
+ *,
51
+ client: httpx.Client | None = None,
52
+ headers: dict[str, str] | None = None,
53
+ api_key: str | None = None,
54
+ ) -> None:
55
+ """
56
+ Initialize the TigrblClient.
57
+
58
+ Args:
59
+ endpoint: Base URL for the API
60
+ client: Optional httpx.Client instance. If not provided, a new one will be created.
61
+ headers: Optional default headers for all requests.
62
+ api_key: Optional API key for authenticated requests. The key is
63
+ sent using the ``x-api-key`` header.
64
+ """
65
+ self._endpoint = endpoint
66
+ self._own = client is None # whether we manage its lifecycle
67
+ self._client = client or httpx.Client(timeout=10.0)
68
+ self._headers = headers.copy() if headers else {}
69
+ self.api_key = api_key
70
+
71
+ # Create async client for async operations
72
+ self._async_client = httpx.AsyncClient(timeout=10.0)
73
+ self._own_async = True # we always own the async client
74
+
75
+ # Initialize nested CRUD placeholder
76
+ NestedCRUDMixin.__init__(self)
77
+
78
+ @property
79
+ def api_key(self) -> str | None:
80
+ """Return the currently configured API key, if any."""
81
+ return self._headers.get("x-api-key")
82
+
83
+ @api_key.setter
84
+ def api_key(self, value: str | None) -> None:
85
+ """Set or remove the API key used for requests."""
86
+ if value is None:
87
+ self._headers.pop("x-api-key", None)
88
+ else:
89
+ self._headers["x-api-key"] = value
90
+
91
+ def _get_endpoint(self) -> str:
92
+ """Get the endpoint URL."""
93
+ return self._endpoint
94
+
95
+ def _get_client(self) -> httpx.Client:
96
+ """Get the HTTP client."""
97
+ return self._client
98
+
99
+ def _get_async_client(self) -> httpx.AsyncClient:
100
+ """Get the async HTTP client."""
101
+ return self._async_client
102
+
103
+ # Context manager support
104
+ def __enter__(self):
105
+ """Enter context manager."""
106
+ return self
107
+
108
+ def __exit__(self, *args):
109
+ """Exit context manager."""
110
+ self.close()
111
+
112
+ async def __aenter__(self):
113
+ """Enter async context manager."""
114
+ return self
115
+
116
+ async def __aexit__(self, *args):
117
+ """Exit async context manager."""
118
+ await self.aclose()
119
+
120
+ def close(self):
121
+ """Close the HTTP clients."""
122
+ if self._own:
123
+ self._client.close()
124
+
125
+ async def aclose(self):
126
+ """Close the async HTTP client."""
127
+ if self._own_async:
128
+ await self._async_client.aclose()
@@ -0,0 +1,563 @@
1
+ # tigrbl_client/_crud.py
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import httpx
6
+ from typing import Any, TypeVar, overload, Protocol
7
+ from typing import runtime_checkable
8
+
9
+ T = TypeVar("T")
10
+
11
+
12
+ @runtime_checkable
13
+ class _Schema(Protocol[T]): # anything with Pydantic-v2 interface
14
+ @classmethod
15
+ def model_validate(cls, data: Any) -> T: ...
16
+ @classmethod
17
+ def model_dump_json(cls, **kw) -> str: ...
18
+
19
+
20
+ class CRUDMixin:
21
+ """
22
+ Mixin class providing REST CRUD functionality for TigrblClient.
23
+ """
24
+
25
+ def _get_endpoint(self) -> str:
26
+ """Get the endpoint URL."""
27
+ return self._endpoint
28
+
29
+ def _get_client(self) -> httpx.Client:
30
+ """Get the HTTP client."""
31
+ return self._client
32
+
33
+ def _get_async_client(self) -> httpx.AsyncClient:
34
+ """Get the async HTTP client."""
35
+ return self._async_client
36
+
37
+ def _build_url(self, path: str) -> str:
38
+ """Build full URL from path."""
39
+ if path.startswith("/"):
40
+ return self._get_endpoint() + path
41
+ return f"{self._get_endpoint()}/{path}"
42
+
43
+ def _prepare_data(self, data: _Schema[Any] | dict | None) -> dict | None:
44
+ """Prepare data for sending."""
45
+ if data is None:
46
+ return None
47
+ if isinstance(data, _Schema):
48
+ return json.loads(data.model_dump_json(exclude_none=True))
49
+ return data
50
+
51
+ def _process_response(
52
+ self,
53
+ response: httpx.Response,
54
+ out_schema: type[_Schema[T]] | None = None,
55
+ *,
56
+ status_code: bool = False,
57
+ raise_status: bool = True,
58
+ ) -> Any:
59
+ """Process HTTP response."""
60
+ if raise_status:
61
+ try:
62
+ response.raise_for_status()
63
+ except httpx.HTTPStatusError as exc:
64
+ if response.status_code == 422:
65
+ try:
66
+ detail = response.json()
67
+ except ValueError:
68
+ detail = response.text
69
+ raise httpx.HTTPStatusError(
70
+ f"Unprocessable Entity: {detail}",
71
+ request=exc.request,
72
+ response=exc.response,
73
+ ) from None
74
+ raise
75
+
76
+ # Handle empty responses (like 204 No Content)
77
+ if response.status_code == 204 or not response.content:
78
+ result: Any = None
79
+ else:
80
+ try:
81
+ result = response.json()
82
+ except ValueError:
83
+ # If response is not JSON, return raw content as string
84
+ result = response.text
85
+
86
+ if out_schema is not None and result is not None:
87
+ result = out_schema.model_validate(result)
88
+
89
+ if status_code:
90
+ return result, response.status_code
91
+ return result
92
+
93
+ # ─────────── GET methods ────────────────────────────────────────── #
94
+ @overload
95
+ def get(
96
+ self,
97
+ path: str,
98
+ *,
99
+ params: dict | None = None,
100
+ out_schema: type[_Schema[T]],
101
+ ) -> T: ...
102
+
103
+ @overload
104
+ def get(
105
+ self,
106
+ path: str,
107
+ *,
108
+ params: dict | None = None,
109
+ out_schema: None = None,
110
+ ) -> Any: ...
111
+
112
+ def get(
113
+ self,
114
+ path: str,
115
+ *,
116
+ params: dict | None = None,
117
+ out_schema: type[_Schema[T]] | None = None,
118
+ status_code: bool = False,
119
+ raise_status: bool = True,
120
+ ) -> Any:
121
+ """
122
+ Make a GET request.
123
+
124
+ Args:
125
+ path: The path to request (will be appended to endpoint)
126
+ params: Query parameters
127
+ out_schema: Optional Pydantic schema for response validation
128
+
129
+ Returns:
130
+ The response data, optionally validated through out_schema
131
+ """
132
+ url = self._build_url(path)
133
+ headers = getattr(self, "_headers", {})
134
+ response = self._get_client().get(url, params=params, headers=headers)
135
+ return self._process_response(
136
+ response, out_schema, status_code=status_code, raise_status=raise_status
137
+ )
138
+
139
+ # ─────────── POST methods ───────────────────────────────────────── #
140
+ @overload
141
+ def post(
142
+ self,
143
+ path: str,
144
+ *,
145
+ data: _Schema[Any] | dict | None = None,
146
+ out_schema: type[_Schema[T]],
147
+ ) -> T: ...
148
+
149
+ @overload
150
+ def post(
151
+ self,
152
+ path: str,
153
+ *,
154
+ data: _Schema[Any] | dict | None = None,
155
+ out_schema: None = None,
156
+ ) -> Any: ...
157
+
158
+ def post(
159
+ self,
160
+ path: str,
161
+ *,
162
+ data: _Schema[Any] | dict | None = None,
163
+ out_schema: type[_Schema[T]] | None = None,
164
+ status_code: bool = False,
165
+ raise_status: bool = True,
166
+ ) -> Any:
167
+ """
168
+ Make a POST request.
169
+
170
+ Args:
171
+ path: The path to request (will be appended to endpoint)
172
+ data: Data to send in request body
173
+ out_schema: Optional Pydantic schema for response validation
174
+
175
+ Returns:
176
+ The response data, optionally validated through out_schema
177
+ """
178
+ url = self._build_url(path)
179
+ json_data = self._prepare_data(data)
180
+ headers = {"Content-Type": "application/json"}
181
+ headers.update(getattr(self, "_headers", {}))
182
+ response = self._get_client().post(url, json=json_data, headers=headers)
183
+ return self._process_response(
184
+ response, out_schema, status_code=status_code, raise_status=raise_status
185
+ )
186
+
187
+ # ─────────── PUT methods ────────────────────────────────────────── #
188
+ @overload
189
+ def put(
190
+ self,
191
+ path: str,
192
+ *,
193
+ data: _Schema[Any] | dict | None = None,
194
+ out_schema: type[_Schema[T]],
195
+ ) -> T: ...
196
+
197
+ @overload
198
+ def put(
199
+ self,
200
+ path: str,
201
+ *,
202
+ data: _Schema[Any] | dict | None = None,
203
+ out_schema: None = None,
204
+ ) -> Any: ...
205
+
206
+ def put(
207
+ self,
208
+ path: str,
209
+ *,
210
+ data: _Schema[Any] | dict | None = None,
211
+ out_schema: type[_Schema[T]] | None = None,
212
+ status_code: bool = False,
213
+ raise_status: bool = True,
214
+ ) -> Any:
215
+ """
216
+ Make a PUT request.
217
+
218
+ Args:
219
+ path: The path to request (will be appended to endpoint)
220
+ data: Data to send in request body
221
+ out_schema: Optional Pydantic schema for response validation
222
+
223
+ Returns:
224
+ The response data, optionally validated through out_schema
225
+ """
226
+ url = self._build_url(path)
227
+ json_data = self._prepare_data(data)
228
+ headers = {"Content-Type": "application/json"}
229
+ headers.update(getattr(self, "_headers", {}))
230
+ response = self._get_client().put(url, json=json_data, headers=headers)
231
+ return self._process_response(
232
+ response, out_schema, status_code=status_code, raise_status=raise_status
233
+ )
234
+
235
+ # ─────────── PATCH methods ──────────────────────────────────────── #
236
+ @overload
237
+ def patch(
238
+ self,
239
+ path: str,
240
+ *,
241
+ data: _Schema[Any] | dict | None = None,
242
+ out_schema: type[_Schema[T]],
243
+ ) -> T: ...
244
+
245
+ @overload
246
+ def patch(
247
+ self,
248
+ path: str,
249
+ *,
250
+ data: _Schema[Any] | dict | None = None,
251
+ out_schema: None = None,
252
+ ) -> Any: ...
253
+
254
+ def patch(
255
+ self,
256
+ path: str,
257
+ *,
258
+ data: _Schema[Any] | dict | None = None,
259
+ out_schema: type[_Schema[T]] | None = None,
260
+ status_code: bool = False,
261
+ raise_status: bool = True,
262
+ ) -> Any:
263
+ """
264
+ Make a PATCH request.
265
+
266
+ Args:
267
+ path: The path to request (will be appended to endpoint)
268
+ data: Data to send in request body
269
+ out_schema: Optional Pydantic schema for response validation
270
+
271
+ Returns:
272
+ The response data, optionally validated through out_schema
273
+ """
274
+ url = self._build_url(path)
275
+ json_data = self._prepare_data(data)
276
+ headers = {"Content-Type": "application/json"}
277
+ headers.update(getattr(self, "_headers", {}))
278
+ response = self._get_client().patch(url, json=json_data, headers=headers)
279
+ return self._process_response(
280
+ response, out_schema, status_code=status_code, raise_status=raise_status
281
+ )
282
+
283
+ # ─────────── DELETE methods ─────────────────────────────────────── #
284
+ @overload
285
+ def delete(
286
+ self,
287
+ path: str,
288
+ *,
289
+ out_schema: type[_Schema[T]],
290
+ ) -> T: ...
291
+
292
+ @overload
293
+ def delete(
294
+ self,
295
+ path: str,
296
+ *,
297
+ out_schema: None = None,
298
+ ) -> Any: ...
299
+
300
+ def delete(
301
+ self,
302
+ path: str,
303
+ *,
304
+ out_schema: type[_Schema[T]] | None = None,
305
+ status_code: bool = False,
306
+ raise_status: bool = True,
307
+ ) -> Any:
308
+ """
309
+ Make a DELETE request.
310
+
311
+ Args:
312
+ path: The path to request (will be appended to endpoint)
313
+ out_schema: Optional Pydantic schema for response validation
314
+
315
+ Returns:
316
+ The response data, optionally validated through out_schema
317
+ """
318
+ url = self._build_url(path)
319
+ headers = getattr(self, "_headers", {})
320
+ response = self._get_client().delete(url, headers=headers)
321
+ return self._process_response(
322
+ response, out_schema, status_code=status_code, raise_status=raise_status
323
+ )
324
+
325
+ # ─────────── Async GET methods ──────────────────────────────────── #
326
+ @overload
327
+ async def aget(
328
+ self,
329
+ path: str,
330
+ *,
331
+ params: dict | None = None,
332
+ out_schema: type[_Schema[T]],
333
+ ) -> T: ...
334
+
335
+ @overload
336
+ async def aget(
337
+ self,
338
+ path: str,
339
+ *,
340
+ params: dict | None = None,
341
+ out_schema: None = None,
342
+ ) -> Any: ...
343
+
344
+ async def aget(
345
+ self,
346
+ path: str,
347
+ *,
348
+ params: dict | None = None,
349
+ out_schema: type[_Schema[T]] | None = None,
350
+ status_code: bool = False,
351
+ raise_status: bool = True,
352
+ ) -> Any:
353
+ """
354
+ Make an async GET request.
355
+
356
+ Args:
357
+ path: The path to request (will be appended to endpoint)
358
+ params: Query parameters
359
+ out_schema: Optional Pydantic schema for response validation
360
+
361
+ Returns:
362
+ The response data, optionally validated through out_schema
363
+ """
364
+ url = self._build_url(path)
365
+ headers = getattr(self, "_headers", {})
366
+ response = await self._get_async_client().get(
367
+ url, params=params, headers=headers
368
+ )
369
+ return self._process_response(
370
+ response, out_schema, status_code=status_code, raise_status=raise_status
371
+ )
372
+
373
+ # ─────────── Async POST methods ─────────────────────────────────── #
374
+ @overload
375
+ async def apost(
376
+ self,
377
+ path: str,
378
+ *,
379
+ data: _Schema[Any] | dict | None = None,
380
+ out_schema: type[_Schema[T]],
381
+ ) -> T: ...
382
+
383
+ @overload
384
+ async def apost(
385
+ self,
386
+ path: str,
387
+ *,
388
+ data: _Schema[Any] | dict | None = None,
389
+ out_schema: None = None,
390
+ ) -> Any: ...
391
+
392
+ async def apost(
393
+ self,
394
+ path: str,
395
+ *,
396
+ data: _Schema[Any] | dict | None = None,
397
+ out_schema: type[_Schema[T]] | None = None,
398
+ status_code: bool = False,
399
+ raise_status: bool = True,
400
+ ) -> Any:
401
+ """
402
+ Make an async POST request.
403
+
404
+ Args:
405
+ path: The path to request (will be appended to endpoint)
406
+ data: Data to send in request body
407
+ out_schema: Optional Pydantic schema for response validation
408
+
409
+ Returns:
410
+ The response data, optionally validated through out_schema
411
+ """
412
+ url = self._build_url(path)
413
+ json_data = self._prepare_data(data)
414
+ headers = {"Content-Type": "application/json"}
415
+ headers.update(getattr(self, "_headers", {}))
416
+ response = await self._get_async_client().post(
417
+ url, json=json_data, headers=headers
418
+ )
419
+ return self._process_response(
420
+ response, out_schema, status_code=status_code, raise_status=raise_status
421
+ )
422
+
423
+ # ─────────── Async PUT methods ──────────────────────────────────── #
424
+ @overload
425
+ async def aput(
426
+ self,
427
+ path: str,
428
+ *,
429
+ data: _Schema[Any] | dict | None = None,
430
+ out_schema: type[_Schema[T]],
431
+ ) -> T: ...
432
+
433
+ @overload
434
+ async def aput(
435
+ self,
436
+ path: str,
437
+ *,
438
+ data: _Schema[Any] | dict | None = None,
439
+ out_schema: None = None,
440
+ ) -> Any: ...
441
+
442
+ async def aput(
443
+ self,
444
+ path: str,
445
+ *,
446
+ data: _Schema[Any] | dict | None = None,
447
+ out_schema: type[_Schema[T]] | None = None,
448
+ status_code: bool = False,
449
+ raise_status: bool = True,
450
+ ) -> Any:
451
+ """
452
+ Make an async PUT request.
453
+
454
+ Args:
455
+ path: The path to request (will be appended to endpoint)
456
+ data: Data to send in request body
457
+ out_schema: Optional Pydantic schema for response validation
458
+
459
+ Returns:
460
+ The response data, optionally validated through out_schema
461
+ """
462
+ url = self._build_url(path)
463
+ json_data = self._prepare_data(data)
464
+ headers = {"Content-Type": "application/json"}
465
+ headers.update(getattr(self, "_headers", {}))
466
+ response = await self._get_async_client().put(
467
+ url, json=json_data, headers=headers
468
+ )
469
+ return self._process_response(
470
+ response, out_schema, status_code=status_code, raise_status=raise_status
471
+ )
472
+
473
+ # ─────────── Async PATCH methods ────────────────────────────────── #
474
+ @overload
475
+ async def apatch(
476
+ self,
477
+ path: str,
478
+ *,
479
+ data: _Schema[Any] | dict | None = None,
480
+ out_schema: type[_Schema[T]],
481
+ ) -> T: ...
482
+
483
+ @overload
484
+ async def apatch(
485
+ self,
486
+ path: str,
487
+ *,
488
+ data: _Schema[Any] | dict | None = None,
489
+ out_schema: None = None,
490
+ ) -> Any: ...
491
+
492
+ async def apatch(
493
+ self,
494
+ path: str,
495
+ *,
496
+ data: _Schema[Any] | dict | None = None,
497
+ out_schema: type[_Schema[T]] | None = None,
498
+ status_code: bool = False,
499
+ raise_status: bool = True,
500
+ ) -> Any:
501
+ """
502
+ Make an async PATCH request.
503
+
504
+ Args:
505
+ path: The path to request (will be appended to endpoint)
506
+ data: Data to send in request body
507
+ out_schema: Optional Pydantic schema for response validation
508
+
509
+ Returns:
510
+ The response data, optionally validated through out_schema
511
+ """
512
+ url = self._build_url(path)
513
+ json_data = self._prepare_data(data)
514
+ headers = {"Content-Type": "application/json"}
515
+ headers.update(getattr(self, "_headers", {}))
516
+ response = await self._get_async_client().patch(
517
+ url, json=json_data, headers=headers
518
+ )
519
+ return self._process_response(
520
+ response, out_schema, status_code=status_code, raise_status=raise_status
521
+ )
522
+
523
+ # ─────────── Async DELETE methods ──────────────────────────────── #
524
+ @overload
525
+ async def adelete(
526
+ self,
527
+ path: str,
528
+ *,
529
+ out_schema: type[_Schema[T]],
530
+ ) -> T: ...
531
+
532
+ @overload
533
+ async def adelete(
534
+ self,
535
+ path: str,
536
+ *,
537
+ out_schema: None = None,
538
+ ) -> Any: ...
539
+
540
+ async def adelete(
541
+ self,
542
+ path: str,
543
+ *,
544
+ out_schema: type[_Schema[T]] | None = None,
545
+ status_code: bool = False,
546
+ raise_status: bool = True,
547
+ ) -> Any:
548
+ """
549
+ Make an async DELETE request.
550
+
551
+ Args:
552
+ path: The path to request (will be appended to endpoint)
553
+ out_schema: Optional Pydantic schema for response validation
554
+
555
+ Returns:
556
+ The response data, optionally validated through out_schema
557
+ """
558
+ url = self._build_url(path)
559
+ headers = getattr(self, "_headers", {})
560
+ response = await self._get_async_client().delete(url, headers=headers)
561
+ return self._process_response(
562
+ response, out_schema, status_code=status_code, raise_status=raise_status
563
+ )
@@ -0,0 +1,50 @@
1
+ # tigrbl_client/_nested_crud.py
2
+ """
3
+ Placeholder module for nested CRUD operations.
4
+
5
+ This module will be developed in the future to support nested resource paths
6
+ and more complex CRUD operations with hierarchical data structures.
7
+
8
+ Examples of future functionality:
9
+ - /users/{user_id}/posts/{post_id}/comments
10
+ - /organizations/{org_id}/teams/{team_id}/members
11
+ - Complex resource relationships and nested operations
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from typing import Any, TypeVar, Protocol
17
+ from typing import runtime_checkable
18
+
19
+ T = TypeVar("T")
20
+
21
+
22
+ @runtime_checkable
23
+ class _Schema(Protocol[T]): # anything with Pydantic-v2 interface
24
+ @classmethod
25
+ def model_validate(cls, data: Any) -> T: ...
26
+ @classmethod
27
+ def model_dump_json(cls, **kw) -> str: ...
28
+
29
+
30
+ class NestedCRUDMixin:
31
+ """
32
+ Placeholder mixin class for nested CRUD functionality.
33
+
34
+ This will be developed to support complex nested resource paths
35
+ and hierarchical data operations.
36
+ """
37
+
38
+ def __init__(self):
39
+ """Initialize the NestedCRUDMixin."""
40
+ # Placeholder for future initialization
41
+ pass
42
+
43
+ def _placeholder_method(self) -> str:
44
+ """
45
+ Placeholder method to demonstrate future functionality.
46
+
47
+ Returns:
48
+ A message indicating this is a placeholder
49
+ """
50
+ return "This is a placeholder for future nested CRUD functionality"
@@ -0,0 +1,236 @@
1
+ # tigrbl_client/_rpc.py
2
+ from __future__ import annotations
3
+
4
+ import uuid
5
+ import json
6
+ import httpx
7
+ from typing import Any, TypeVar, overload, Protocol
8
+ from typing import runtime_checkable
9
+
10
+ T = TypeVar("T")
11
+
12
+
13
+ @runtime_checkable
14
+ class _Schema(Protocol[T]): # anything with Pydantic-v2 interface
15
+ @classmethod
16
+ def model_validate(cls, data: Any) -> T: ...
17
+ @classmethod
18
+ def model_dump_json(cls, **kw) -> str: ...
19
+
20
+
21
+ class RPCMixin:
22
+ """
23
+ Mixin class providing JSON-RPC functionality for TigrblClient.
24
+ """
25
+
26
+ def _get_endpoint(self) -> str:
27
+ """Get the endpoint URL."""
28
+ return self._endpoint
29
+
30
+ def _get_client(self) -> httpx.Client:
31
+ """Get the HTTP client."""
32
+ return self._client
33
+
34
+ def _get_async_client(self) -> httpx.AsyncClient:
35
+ """Get the async HTTP client."""
36
+ return self._async_client
37
+
38
+ # ─────────── public high-level call helpers ────────────────────── #
39
+ @overload
40
+ def call( # result with schema
41
+ self,
42
+ method: str,
43
+ *,
44
+ params: _Schema[Any] | dict | None = None,
45
+ out_schema: type[_Schema[T]],
46
+ status_code: bool = False,
47
+ error_code: bool = False,
48
+ raise_status: bool = True,
49
+ raise_error: bool = True,
50
+ ) -> T: ...
51
+
52
+ @overload
53
+ def call( # raw / no schema
54
+ self,
55
+ method: str,
56
+ *,
57
+ params: dict | None = None,
58
+ out_schema: None = None,
59
+ status_code: bool = False,
60
+ error_code: bool = False,
61
+ raise_status: bool = True,
62
+ raise_error: bool = True,
63
+ ) -> Any: ...
64
+
65
+ def call(
66
+ self,
67
+ method: str,
68
+ *,
69
+ params: _Schema[Any] | dict | None = None,
70
+ out_schema: type[_Schema[T]] | None = None,
71
+ status_code: bool = False,
72
+ error_code: bool = False,
73
+ raise_status: bool = True,
74
+ raise_error: bool = True,
75
+ ) -> Any:
76
+ """
77
+ Make a JSON-RPC call.
78
+
79
+ Args:
80
+ method: The RPC method name
81
+ params: Parameters to send (dict or Pydantic schema)
82
+ out_schema: Optional Pydantic schema for result validation
83
+
84
+ Returns:
85
+ The RPC result, optionally validated through out_schema
86
+
87
+ Raises:
88
+ RuntimeError: If the RPC returns an error
89
+ httpx.HTTPStatusError: If the HTTP request fails
90
+ """
91
+ # ----- payload build ------------------------------------------------
92
+ if isinstance(params, _Schema): # pydantic in → dump to dict
93
+ params_dict = json.loads(
94
+ params.model_dump_json(exclude_none=True, exclude=None)
95
+ )
96
+ else:
97
+ # ensure plain dicts contain only JSON-serializable values
98
+ params_dict = json.loads(json.dumps(params or {}, default=str))
99
+
100
+ req = {
101
+ "jsonrpc": "2.0",
102
+ "method": method,
103
+ "params": params_dict,
104
+ "id": str(uuid.uuid4()),
105
+ }
106
+
107
+ # ----- HTTP roundtrip ----------------------------------------------
108
+ headers = {"Content-Type": "application/json"}
109
+ headers.update(getattr(self, "_headers", {}))
110
+ r = self._get_client().post(
111
+ self._get_endpoint(),
112
+ json=req,
113
+ headers=headers,
114
+ )
115
+
116
+ if raise_status:
117
+ r.raise_for_status()
118
+ res = r.json()
119
+ err = res.get("error")
120
+ err_code = 0
121
+ if err:
122
+ err_code = err.get("code", -32000)
123
+ msg = err.get("message", "Unknown error")
124
+ if raise_error:
125
+ raise RuntimeError(f"RPC error {err_code}: {msg}")
126
+
127
+ result = res.get("result")
128
+
129
+ if out_schema is not None and result is not None:
130
+ result = out_schema.model_validate(result) # type: ignore[assignment]
131
+
132
+ parts = [result]
133
+ if status_code:
134
+ parts.append(r.status_code)
135
+ if error_code:
136
+ parts.append(err_code)
137
+ return parts[0] if len(parts) == 1 else tuple(parts)
138
+
139
+ # ─────────── Async call helper ──────────────────────────────────── #
140
+ @overload
141
+ async def acall( # result with schema
142
+ self,
143
+ method: str,
144
+ *,
145
+ params: _Schema[Any] | dict | None = None,
146
+ out_schema: type[_Schema[T]],
147
+ status_code: bool = False,
148
+ error_code: bool = False,
149
+ raise_status: bool = True,
150
+ raise_error: bool = True,
151
+ ) -> T: ...
152
+
153
+ @overload
154
+ async def acall( # raw / no schema
155
+ self,
156
+ method: str,
157
+ *,
158
+ params: dict | None = None,
159
+ out_schema: None = None,
160
+ status_code: bool = False,
161
+ error_code: bool = False,
162
+ raise_status: bool = True,
163
+ raise_error: bool = True,
164
+ ) -> Any: ...
165
+
166
+ async def acall(
167
+ self,
168
+ method: str,
169
+ *,
170
+ params: _Schema[Any] | dict | None = None,
171
+ out_schema: type[_Schema[T]] | None = None,
172
+ status_code: bool = False,
173
+ error_code: bool = False,
174
+ raise_status: bool = True,
175
+ raise_error: bool = True,
176
+ ) -> Any:
177
+ """
178
+ Make an async JSON-RPC call.
179
+
180
+ Args:
181
+ method: The RPC method name
182
+ params: Parameters to send (dict or Pydantic schema)
183
+ out_schema: Optional Pydantic schema for result validation
184
+
185
+ Returns:
186
+ The RPC result, optionally validated through out_schema
187
+
188
+ Raises:
189
+ RuntimeError: If the RPC returns an error
190
+ httpx.HTTPStatusError: If the HTTP request fails
191
+ """
192
+ # ----- payload build ------------------------------------------------
193
+ if isinstance(params, _Schema): # pydantic in → dump to dict
194
+ params_dict = json.loads(params.model_dump_json(exclude_none=True))
195
+ else:
196
+ # ensure plain dicts contain only JSON-serializable values
197
+ params_dict = json.loads(json.dumps(params or {}, default=str))
198
+
199
+ req = {
200
+ "jsonrpc": "2.0",
201
+ "method": method,
202
+ "params": params_dict,
203
+ "id": str(uuid.uuid4()),
204
+ }
205
+
206
+ # ----- HTTP roundtrip ----------------------------------------------
207
+ headers = {"Content-Type": "application/json"}
208
+ headers.update(getattr(self, "_headers", {}))
209
+ r = await self._get_async_client().post(
210
+ self._get_endpoint(),
211
+ json=req,
212
+ headers=headers,
213
+ )
214
+
215
+ if raise_status:
216
+ r.raise_for_status()
217
+ res = r.json()
218
+ err = res.get("error")
219
+ err_code = 0
220
+ if err:
221
+ err_code = err.get("code", -32000)
222
+ msg = err.get("message", "Unknown error")
223
+ if raise_error:
224
+ raise RuntimeError(f"RPC error {err_code}: {msg}")
225
+
226
+ result = res.get("result")
227
+
228
+ if out_schema is not None and result is not None:
229
+ result = out_schema.model_validate(result) # type: ignore[assignment]
230
+
231
+ parts = [result]
232
+ if status_code:
233
+ parts.append(r.status_code)
234
+ if error_code:
235
+ parts.append(err_code)
236
+ return parts[0] if len(parts) == 1 else tuple(parts)