paxos-sdk 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.
Files changed (78) hide show
  1. paxos/AGENTS.md +306 -0
  2. paxos/__init__.py +61 -0
  3. paxos/_aio.py +29 -0
  4. paxos/_auth.py +414 -0
  5. paxos/_client.py +1755 -0
  6. paxos/_constants.py +7 -0
  7. paxos/_decimal_fields.py +166 -0
  8. paxos/_decimals.py +121 -0
  9. paxos/_errors.py +210 -0
  10. paxos/_pagination.py +210 -0
  11. paxos/_query_keys.py +32 -0
  12. paxos/_raw.py +14 -0
  13. paxos/_service_registry.py +414 -0
  14. paxos/_signing.py +250 -0
  15. paxos/_sync_transport.py +284 -0
  16. paxos/_timestamps.py +36 -0
  17. paxos/_types.py +21 -0
  18. paxos/_version.py +3 -0
  19. paxos/enums.py +1813 -0
  20. paxos/models.py +4337 -0
  21. paxos/py.typed +0 -0
  22. paxos/services/__init__.py +340 -0
  23. paxos/services/_base.py +479 -0
  24. paxos/services/account_members.py +140 -0
  25. paxos/services/accounts.py +260 -0
  26. paxos/services/address_verification.py +295 -0
  27. paxos/services/api_credentials.py +163 -0
  28. paxos/services/claims.py +307 -0
  29. paxos/services/cross_chain_transfer.py +269 -0
  30. paxos/services/crypto_deposits.py +157 -0
  31. paxos/services/crypto_withdrawals.py +209 -0
  32. paxos/services/deposit_addresses.py +154 -0
  33. paxos/services/events.py +157 -0
  34. paxos/services/exchange.py +156 -0
  35. paxos/services/fees.py +81 -0
  36. paxos/services/fiat_transfers.py +549 -0
  37. paxos/services/identity.py +304 -0
  38. paxos/services/identity_controls.py +192 -0
  39. paxos/services/identity_documents.py +187 -0
  40. paxos/services/institution_members.py +136 -0
  41. paxos/services/internal_transfers.py +83 -0
  42. paxos/services/issuer_quotes.py +280 -0
  43. paxos/services/limits.py +82 -0
  44. paxos/services/market_data.py +60 -0
  45. paxos/services/monitoring_addresses.py +276 -0
  46. paxos/services/orchestration_rules.py +188 -0
  47. paxos/services/orchestrations.py +198 -0
  48. paxos/services/orders.py +332 -0
  49. paxos/services/paxos_transfers.py +99 -0
  50. paxos/services/payments.py +112 -0
  51. paxos/services/payout_groups.py +253 -0
  52. paxos/services/pricing.py +210 -0
  53. paxos/services/profiles.py +444 -0
  54. paxos/services/quote_executions.py +227 -0
  55. paxos/services/quotes.py +123 -0
  56. paxos/services/reward_addresses.py +327 -0
  57. paxos/services/rewards.py +140 -0
  58. paxos/services/rewards_statements.py +127 -0
  59. paxos/services/sandbox_deposits.py +85 -0
  60. paxos/services/sandbox_fiat_transfers.py +81 -0
  61. paxos/services/sandbox_identity.py +304 -0
  62. paxos/services/settlement.py +315 -0
  63. paxos/services/stablecoin_conversion.py +249 -0
  64. paxos/services/statements.py +110 -0
  65. paxos/services/tax_documentation.py +125 -0
  66. paxos/services/tax_forms.py +147 -0
  67. paxos/services/transfers.py +158 -0
  68. paxos/services/travel_rule.py +121 -0
  69. paxos/services/user_audit_logs.py +100 -0
  70. paxos/services/webhooks.py +189 -0
  71. paxos/testing/__init__.py +52 -0
  72. paxos/testing/fixtures.py +225 -0
  73. paxos/testing/mock_server.py +351 -0
  74. paxos_sdk-0.1.0.dist-info/METADATA +472 -0
  75. paxos_sdk-0.1.0.dist-info/RECORD +78 -0
  76. paxos_sdk-0.1.0.dist-info/WHEEL +5 -0
  77. paxos_sdk-0.1.0.dist-info/licenses/LICENSE +191 -0
  78. paxos_sdk-0.1.0.dist-info/top_level.txt +1 -0
paxos/AGENTS.md ADDED
@@ -0,0 +1,306 @@
1
+ # Paxos Python SDK
2
+
3
+ Guidance for coding agents integrating the Paxos Python SDK. Docs: https://docs.paxos.com/sdks (SDK guides) and https://docs.paxos.com (API reference).
4
+
5
+ ## Install and import
6
+
7
+ Requires Python 3.11+ (HTTP transport is httpx).
8
+
9
+ ```bash
10
+ pip install paxos-sdk
11
+ pip install "paxos-sdk[signing]" # only if you use request signing
12
+ ```
13
+
14
+ ```python
15
+ import paxos
16
+ from paxos.enums import Scope
17
+ ```
18
+
19
+ Import paths: `paxos` (`Client`, `AsyncClient`, `RequestOptions`, `ResponseMetadata`, `Decimal`, hook types, all error classes), `paxos.models` (request and response models), `paxos.enums`, `paxos.services` (`*Params` TypedDicts) and `paxos.testing`. Modules whose names start with an underscore are internal.
20
+
21
+ ## Quick start
22
+
23
+ ```python
24
+ import os
25
+ import paxos
26
+ from paxos.enums import Scope
27
+
28
+ client = paxos.Client(
29
+ client_id=os.environ["PAXOS_CLIENT_ID"],
30
+ client_secret=os.environ["PAXOS_CLIENT_SECRET"],
31
+ sandbox=True,
32
+ scopes=[Scope.TRANSFER_READ_TRANSFER],
33
+ )
34
+ transfer = client.transfers.get_transfer("txn_123")
35
+ ```
36
+
37
+ ## Client construction, scopes, sandbox vs production, environment variables
38
+
39
+ ```python
40
+ client = paxos.Client(
41
+ client_id="...",
42
+ client_secret="...",
43
+ scopes=[Scope.TRANSFER_READ_TRANSFER], # required
44
+ sandbox=True, # sandbox environment (omit for production)
45
+ logger=logging.getLogger("paxos"), # debug logging
46
+ signing_key="<private-key-pem-or-hex>", # JWS request signing
47
+ key_id="<registered-key-uuid>", # signing key ID
48
+ before_request=lambda req: None, # hook before each API attempt
49
+ after_response=lambda req, resp: None, # hook after each response
50
+ )
51
+ ```
52
+
53
+ - At least one scope is required: an empty or blank `scopes` raises `ValueError`, and omitting the keyword raises `TypeError`. Use the generated `Scope` constants (plain strings are also accepted). Methods state the scope they need in their doc comment; a few public endpoints need none, but the client still requires one.
54
+ - Credentials do not select the environment: pass `sandbox=True` explicitly. Sandbox and production credentials differ. `sandbox` cannot be combined with `base_url` or `token_url` (set both URLs, without sandbox, for a local or test server; construction raises if only one is set, and an empty string counts as unset).
55
+ - Create one client per application component; this reuses OAuth tokens and connections. Auth (token acquisition, caching, refresh) is automatic. A synchronous `Client` can be shared across threads; it owns a lazy I/O thread, so use `with paxos.Client(...)` or call `close()`. An `AsyncClient` may be shared only among tasks on one event loop: create one per loop or thread, close it with `async with` or `await aclose()` in that loop, and never reuse it across `asyncio.run()` calls.
56
+ - The SDK does not read credentials itself; pass them in. The conventional variable names are:
57
+
58
+ | Variable | Read by | Description |
59
+ |---|---|---|
60
+ | `PAXOS_CLIENT_ID` | your code | OAuth2 client ID |
61
+ | `PAXOS_CLIENT_SECRET` | your code | OAuth2 client secret |
62
+ | `PAXOS_LOG_LEVEL` | SDK | `debug` (any case) to enable debug logging |
63
+
64
+ ## Calling services
65
+
66
+ Services are attributes on the client: `client.<service>.<method>(...)`. Request bodies are dataclasses from `paxos.models`; query params are keyword arguments, and dotted API params use underscores (`created_at.lt` becomes `created_at_lt`). Empty lists and empty map fields are omitted from request bodies; empty objects for nested model fields are sent as given. A query parameter passed as `""` is sent as `key=`; leave it out (or `None`) to omit it (an empty `page_cursor` is the exception and is not sent).
67
+
68
+ ```python
69
+ transfer = client.transfers.get_transfer("txn_123") # returns a Transfer dataclass
70
+ client.crypto_withdrawals.create_crypto_withdrawal(
71
+ body=CreateCryptoWithdrawalRequest(...)
72
+ )
73
+ for t in client.transfers.list_transfers(
74
+ limit=10, profile_ids=["p_123"]
75
+ ): # auto-paginated
76
+ print(t.id)
77
+ ```
78
+
79
+ Response enum fields (for example `transfer.status`) are plain strings that keep values added by the API after this SDK version. Compare against `paxos.enums` constants and always handle an unrecognized value; never treat an unknown status as success or failure.
80
+
81
+ The API omits zero values from responses, so a field can be absent even when the spec marks it required: lists and maps decode as `[]` and `{}`, other absent fields are `None`. Decimals or timestamps may also arrive as `"0"` or the epoch; check the field's meaning before treating a zero as missing.
82
+
83
+ ## Pagination
84
+
85
+ ```python
86
+ for transfer in client.transfers.list_transfers(limit=100, profile_ids=["p_123"]):
87
+ print(transfer.id)
88
+ ```
89
+
90
+ Paginated `list_*` methods return `PageIterator[T]` / `AsyncPageIterator[T]` (iterators, not generators); iteration always terminates, even if the server returns a non-advancing cursor or an empty page alongside one. `.pages()` yields `Page[T]` (`items`, `next_cursor` = the cursor to resume from, `metadata`); an empty first page is yielded once. Mixing item iteration and `pages()` on one iterator raises `ValueError`. A fetch error (after the client's normal retries) finishes the iterator; later calls make no requests.
91
+
92
+ `limit` is a page-size hint, not a total cap, and is re-sent unchanged on every page. Bound the whole iteration with `max_items` and/or `max_duration` (seconds) via `request_options`:
93
+
94
+ ```python
95
+ for transfer in client.transfers.list_transfers(
96
+ request_options=paxos.RequestOptions(
97
+ max_items=250, max_duration=10
98
+ ), # ~3 pages, or 10s
99
+ limit=100,
100
+ profile_ids=["p_123"],
101
+ ):
102
+ print(transfer.id)
103
+ ```
104
+
105
+ Exceeding `max_duration` raises `PaxosTimeoutError`, not a silent truncation. The duration starts on first consumption and counts pauses between items.
106
+
107
+ ## Errors
108
+
109
+ ```python
110
+ try:
111
+ transfer = client.transfers.get_transfer("bad-id")
112
+ except paxos.NotFoundError as e:
113
+ print(f"request_id={e.request_id} detail={e.detail}")
114
+ except paxos.PaxosApiError as e:
115
+ print(f"status={e.status} request_id={e.request_id}")
116
+ except paxos.PaxosError as e:
117
+ print(f"transport failure: {e}")
118
+ ```
119
+
120
+ - Hierarchy: `PaxosError` > `PaxosApiError` > `ValidationError` (400), `UnauthorizedError` (401), `AuthenticationError` (OAuth failures), `ForbiddenError` (403), `NotFoundError` (404), `ConflictError` (409), `UnprocessableError` (422), `RateLimitError` (429), `ServerError` (5xx); and directly under `PaxosError`, with no status: `PaxosTimeoutError` and `NetworkError` (transport failure with no HTTP response; `__cause__` preserved). Both expose `request_id`, the most recent attempt built's `Paxos-Request-Id` (`None` if none); the request may still have reached Paxos, so quote the ID to support.
121
+ - `request_id`, `status`, `detail` and `title` are on every `PaxosError` (`None` when absent; `status` is `None` unless it is a `PaxosApiError`). `paxos.is_api_error(err)` is a `TypeGuard[PaxosApiError]`.
122
+ - The actual HTTP status selects the subtype, even when the error body is malformed or mistyped. The request ID comes from a valid body `request_id`, else the `Paxos-Request-Id` response header, else the outgoing request's ID.
123
+ - A 2xx body that cannot be decoded (including a bad item during pagination) raises `PaxosApiError` with the real status and request ID and a sanitized cause that contains no body text. It is not retried.
124
+ - OAuth HTTP failures and malformed token responses raise `AuthenticationError` with the real `status`, `request_id` and an allowlisted OAuth `code`; messages exclude raw bodies, descriptions and tokens. This is distinct from an endpoint `UnauthorizedError`.
125
+ - Errors on a later pagination page reach the caller with their type, status and request ID; they never look like normal completion.
126
+
127
+ ## Using with fork / gunicorn / Celery prefork
128
+
129
+ - The default `Client` is safe across `fork()`: its I/O loop, thread and connection pool are rebuilt lazily in the child.
130
+ - A `Client` built with a custom `transport=` cannot be used in a forked child: it raises `PaxosError`. Create a new `Client` in the child.
131
+ - Creating the `Client` after the fork (for example in a post-fork hook) is always safe.
132
+ - In a forked child with no proxy settings cached from the parent, the client uses environment-variable proxies only (`HTTPS_PROXY`, `NO_PROXY` and so on) and skips the macOS system proxy lookup, which can crash after `fork()`.
133
+
134
+ ## Money and decimals
135
+
136
+ Use `decimal.Decimal` (also exported as `paxos.Decimal`), constructed from strings: `Decimal("1.23")`. Never use `float` for monetary amounts. Pass decimals directly in typed requests; the SDK writes the API's string format.
137
+
138
+ ## Timestamps
139
+
140
+ Timestamps in models and query params are timezone-aware `datetime` values in UTC. `datetime` holds microseconds, so response fractions beyond that are truncated; request timestamps are canonicalised to UTC `Z`. The API accepts any RFC 3339 offset and up to nanoseconds; stored precision varies by resource (microseconds for Postgres-backed resources, milliseconds for events). Pass `datetime(..., tzinfo=timezone.utc)`; a naive `datetime` raises `ValueError`.
141
+
142
+ ```python
143
+ from datetime import datetime, timezone
144
+
145
+ client.transfers.list_transfers(created_at_lt=datetime(2026, 1, 2, tzinfo=timezone.utc))
146
+ ```
147
+
148
+ ## Per-request options
149
+
150
+ ```python
151
+ opts = paxos.RequestOptions(call_timeout=60, extra_headers={"X-Trace-Id": "abc"})
152
+ transfer = client.transfers.get_transfer("txn_123", request_options=opts)
153
+ ```
154
+
155
+ `RequestOptions`, `ResponseMetadata`, `Page` and `paxos.testing.RecordedRequest` take keyword arguments only.
156
+
157
+ Cancellation: with `AsyncClient`, cancel the calling task; no further attempts are made.
158
+
159
+ ## Retries, timeouts and ref_id/idempotency
160
+
161
+ - Default policy: up to 3 retries with backoff for HTTP 429, 500, 502, 503 and 504. Set `max_retries` on the client or `RequestOptions` (integers 0 to 2147483646; 0 disables ordinary retries). One 401 token refresh is separate and does not count as a retry.
162
+ - HTTP 500, 502, 503 and 504 responses are retried for GET, HEAD, OPTIONS and DELETE, and for POST, PUT and PATCH requests on operations whose ref_id the SDK manages (create operations with a ref_id). Other POST, PUT and PATCH requests, including UpdateIdentity and UpdateAccount, are returned to the caller without a retry because the request may already have taken effect; check the resource's state before retrying such a call yourself.
163
+ - Network failures retry only for GET/HEAD/OPTIONS. An ambiguous network failure on a mutation is surfaced, never replayed. OAuth failures are surfaced without an extra retry loop. Once a rate-limit or server error reaches your code the SDK call is finished.
164
+ - The Paxos API does not send `Retry-After` (or rate-limit headers), so the SDK does not read them; 429 retries use the SDK's own backoff. Do not build retry logic that waits for or parses `Retry-After`.
165
+ - Budgets (seconds): `call_timeout` (default 30) is one budget for OAuth, lock waits, all HTTP attempts, backoff and reading the full response body. Optional `call_attempt_timeout` caps each API or OAuth HTTP attempt (default: no cap). Values must be positive finite numbers (booleans, zero and negatives are rejected). Omission inherits; `None` disables that one budget; request options override client settings.
166
+
167
+ ```python
168
+ client = paxos.Client(
169
+ "id",
170
+ "secret",
171
+ call_timeout=30,
172
+ call_attempt_timeout=10,
173
+ scopes=[Scope.TRANSFER_READ_TRANSFER],
174
+ )
175
+ opts = paxos.RequestOptions(call_timeout=60, call_attempt_timeout=None)
176
+ ```
177
+
178
+ - `ref_id`: for operations that accept one, the SDK fills an omitted or empty `ref_id` once per method call without mutating your request object and reuses it across internal retries. A second call without an ID gets a new one, so this does not give application-level deduplication.
179
+ - For jobs that may restart or be retried by a queue: generate an ID (a UUID is fine) when the job is created and persist it with the payload before the first API call; send it as `ref_id`; after a timeout, transport error or exhausted retries keep the same ID and payload and reconcile via the operation's lookup or list API (for example `list_transfers(ref_ids=[...])`) before resubmitting; treat a conflict as a reason to reconcile, not to mint a new ID; use a new ID only for a genuinely new operation. A timeout or cancellation does not prove the server rejected a mutation.
180
+
181
+ ```python
182
+ from decimal import Decimal
183
+ from paxos.models import CreateCryptoWithdrawalRequest
184
+
185
+ request = CreateCryptoWithdrawalRequest(
186
+ profile_id="p_123",
187
+ asset="BTC",
188
+ crypto_network="BITCOIN",
189
+ destination_address="bc1q...",
190
+ amount=Decimal("0.001"),
191
+ ref_id="saved-withdrawal-001", # loaded with this payload from durable storage
192
+ )
193
+ transfer = client.crypto_withdrawals.create_crypto_withdrawal(body=request)
194
+ ```
195
+
196
+ ## Hooks and authentication errors
197
+
198
+ - `before_request(request)` takes an `httpx.Request` and runs on every API attempt (including retries and the 401 refresh retry), before signing, and not for OAuth token requests. It may add headers and override `Paxos-Request-Id`. Changing the method, URL, body or an SDK-owned header (`Authorization`, `Content-Type`, `Accept`, `Paxos-SDK-Language`, `Paxos-SDK-Version`), or adding `Paxos-Signature`, raises `ValueError` before anything is sent.
199
+ - `after_response(request, response)` runs for every attempt that received a response, before status handling; the body is buffered so hooks may read it. It does not run on network failures. Hook exceptions end the call unchanged, with no retry or token refresh; an after-hook failure takes precedence over the HTTP error.
200
+ - `AsyncClient` accepts async hooks (awaitable callables); async hooks are cancellable, while a blocking hook on a synchronous client cannot be interrupted. One hook of each kind per client.
201
+
202
+ ## Request signing
203
+
204
+ Request signing is configured per OAuth client. Setup follows the guide (https://docs.paxos.com/guides/developer/request-signing), which says request signing "must be activated by Paxos" and to contact Support (https://support.paxos.com). Credentials with the crypto-withdrawal scope also need Paxos Support to register the public key before signing works.
205
+
206
+ 1. Generate a private key with OpenSSL 3 or later (check with `openssl version`; the macOS system `openssl` is LibreSSL and does not support Ed25519). For Ed25519 (EdDSA): `openssl genpkey -algorithm ed25519 -out private.pem`. For P-256 (ES256): `openssl ecparam -name prime256v1 -genkey -noout -out private.pem`
207
+ 2. Derive the public key. For Ed25519: `openssl pkey -in private.pem -pubout -out public.pem`. For P-256: `openssl ec -in private.pem -pubout -out public.pem`
208
+ 3. In the Dashboard, go to Developer > API, open the credential and choose Edit. Click "Add Public Key", enter a nickname, select the algorithm that matches your key (EdDSA or ES256), paste the contents of `public.pem`, click "Save Key", then save the credential with "Save API Credential".
209
+ 4. Copy the Key ID (a UUID) shown on the saved public key.
210
+ 5. Activate signing. For credentials without the crypto-withdrawal scope, turn on "Enable Request Signing" (available once the credential has a public key), save the credential, then contact Support to complete activation. For credentials with the crypto-withdrawal scope, contact Support to register the key with the signing stack, and turn on "Enable Request Signing" only after they confirm.
211
+ 6. Configure the SDK with the private key and the Key ID (requires the optional `signing` extra: `pip install "paxos-sdk[signing]"`):
212
+
213
+ ```python
214
+ import os
215
+ from pathlib import Path
216
+
217
+ client = paxos.Client(
218
+ client_id=os.environ["PAXOS_CLIENT_ID"],
219
+ client_secret=os.environ["PAXOS_CLIENT_SECRET"],
220
+ signing_key=Path("private.pem").read_text(),
221
+ key_id=os.environ["PAXOS_KEY_ID"],
222
+ scopes=[Scope.TRANSFER_READ_TRANSFER],
223
+ )
224
+ ```
225
+
226
+ The options are `signing_key` and `key_id`; pass both together. `paxos.AsyncClient` takes the same options. The private key can be the PEM file contents as written by step 1 (an unencrypted PKCS#8 `-----BEGIN PRIVATE KEY-----` block for either key type, or an unencrypted SEC1 `-----BEGIN EC PRIVATE KEY-----` block for P-256) or, for Ed25519 only, 128 hex characters (the 32-byte seed followed by the matching 32-byte public key). Pass the PEM exactly as openssl writes it (multi-line, with the BEGIN and END lines); reformatted PEM, such as a single line with spaces, may be rejected. Load it from a file or a secret store (keep its newlines if it comes from an environment variable); do not put key literals in source. Encrypted PEM is rejected: decrypt it first. Whatever the format, an invalid key raises `ValueError`.
227
+
228
+ The SDK supports Ed25519 (EdDSA) and P-256 (ES256) keys and picks the algorithm from the key; other key types and curves are rejected.
229
+
230
+ Only API requests are signed; OAuth token requests are not. Each signed request carries a JWS in the `Paxos-Signature` header covering the method, the full transmitted path (including the `/v2` prefix), the exact serialized query string and the body bytes. For example, a boolean query is signed as `include_deactivated=true`, exactly as HTTPX sends it. Signing runs after `before_request`, so it covers the final request.
231
+
232
+ Once signing is enforced for the credential, unsigned or mis-signed requests are rejected with HTTP 401, surfaced as `paxos.UnauthorizedError` with `request_id`. Quote the request ID when contacting Support.
233
+
234
+ ## Raw JSON and response metadata
235
+
236
+ Top-level response models (list items and get/create/update results) have `.raw_json`: a deep-copied parsed JSON `dict` of its own response value, independent of the typed fields, with original decimal strings and unknown fields kept. It is `None` on caller-built objects. Nested-only dataclasses (for example `TransferStatusDetails`) and request bodies have no `raw_json` attribute at all, so reading it raises `AttributeError`. It is excluded from equality, `repr`, hash, pickle and request bodies, and shows up in `vars(obj)`: serialize with `dataclasses.asdict`, not `__dict__`.
237
+
238
+ Capture the request ID, status and body of the terminal response (including API errors) with a holder:
239
+
240
+ ```python
241
+ metadata = paxos.ResponseMetadata()
242
+ try:
243
+ transfer = client.transfers.get_transfer(
244
+ "txn_123", request_options=paxos.RequestOptions(response_metadata=metadata)
245
+ )
246
+ finally:
247
+ print(metadata.request_id, metadata.status_code)
248
+ ```
249
+
250
+ The holder stays empty if there was no terminal response (timeout, network failure). In an auto-paginated call it holds the final page only; an `after_response` hook sees every page. Use one holder per concurrent call. Keep the request ID for support; avoid logging identity or financial payloads.
251
+
252
+ ## Logging
253
+
254
+ ```bash
255
+ PAXOS_LOG_LEVEL=debug python my_app.py
256
+ ```
257
+
258
+ Programmatic (takes precedence over the env var): pass `logger=logging.getLogger("paxos")` to the client.
259
+
260
+ ## Testing and mocking
261
+
262
+ `paxos.testing` ships a local HTTP mock server and fixtures. It also serves `POST /oauth2/token` (not recorded in `calls()`). Each recorded call has `method`, `path` (no query), `query` (parsed, `dict[str, list[str]]`), `headers` and `body`; responses echo the request's `Paxos-Request-Id`, which surfaces as `request_id`. `client_kwargs()` points both the base URL and the token URL at it.
263
+
264
+ ```python
265
+ import paxos
266
+ from paxos.enums import Scope
267
+ from paxos.testing import MockServer, transfer_fixture
268
+
269
+
270
+ def test_my_feature():
271
+ with MockServer() as server:
272
+ server.on("GET", "/transfer/transfers/txn_123").respond(
273
+ 200, transfer_fixture("txn_123")
274
+ )
275
+ client = paxos.Client(
276
+ "id",
277
+ "secret",
278
+ scopes=[Scope.TRANSFER_READ_TRANSFER],
279
+ **server.client_kwargs(),
280
+ )
281
+ assert client.transfers.get_transfer("txn_123").id == "txn_123"
282
+ ```
283
+
284
+ Other helpers: `return_not_found`, `return_rate_limit`, `return_server_error`, `return_validation_error`, `respond_with_headers`, `calls()` and `reset()`. `transport=` accepts an HTTPX `AsyncBaseTransport` (including `MockTransport`) as an alternative.
285
+
286
+ ## Language-specific notes
287
+
288
+ - Async: `AsyncClient` mirrors `Client` with the same method names; call `foo()` on `Client` and `await foo()` on `AsyncClient`. Paginated methods use `for` and `async for` respectively. Neither client exposes methods for the other mode; create one of each if you need both. (Direct service imports use `AsyncProfilesService` and similar `Async...Service` classes with `AsyncClient`.)
289
+
290
+ ```python
291
+ async with paxos.AsyncClient(
292
+ client_id="id",
293
+ client_secret="secret",
294
+ sandbox=True,
295
+ scopes=[Scope.TRANSFER_READ_TRANSFER],
296
+ ) as client:
297
+ transfer = await client.transfers.get_transfer("txn_123")
298
+ async for t in client.transfers.list_transfers(limit=10):
299
+ print(t.id)
300
+ ```
301
+
302
+ - Custom transports must cooperate with asynchronous cancellation; close clients or use context managers.
303
+
304
+ ## Examples and docs
305
+
306
+ SDK guides: https://docs.paxos.com/sdks. API reference: https://docs.paxos.com. The snippets above are complete enough to adapt; for other endpoints follow the same `client.<service>.<method>(...)` pattern.
paxos/__init__.py ADDED
@@ -0,0 +1,61 @@
1
+ """Paxos Python SDK — Idiomatic access to all public Paxos APIs."""
2
+
3
+ from decimal import Decimal
4
+ from ._version import __version__
5
+ from ._client import (
6
+ AfterResponseHook,
7
+ AsyncAfterResponseHook,
8
+ AsyncBeforeRequestHook,
9
+ AsyncClient,
10
+ BeforeRequestHook,
11
+ Client,
12
+ RequestOptions,
13
+ ResponseMetadata,
14
+ )
15
+ from ._pagination import AsyncPageIterator, Page, PageIterator
16
+ from ._errors import (
17
+ PaxosApiError,
18
+ PaxosError,
19
+ AuthenticationError,
20
+ ValidationError,
21
+ UnauthorizedError,
22
+ ForbiddenError,
23
+ NotFoundError,
24
+ ConflictError,
25
+ UnprocessableError,
26
+ RateLimitError,
27
+ ServerError,
28
+ PaxosTimeoutError,
29
+ NetworkError,
30
+ is_api_error,
31
+ )
32
+
33
+ __all__ = [
34
+ "__version__",
35
+ "AfterResponseHook",
36
+ "AsyncAfterResponseHook",
37
+ "AsyncBeforeRequestHook",
38
+ "AsyncClient",
39
+ "AsyncPageIterator",
40
+ "BeforeRequestHook",
41
+ "Client",
42
+ "Decimal",
43
+ "Page",
44
+ "PageIterator",
45
+ "RequestOptions",
46
+ "ResponseMetadata",
47
+ "PaxosApiError",
48
+ "PaxosError",
49
+ "AuthenticationError",
50
+ "ValidationError",
51
+ "UnauthorizedError",
52
+ "ForbiddenError",
53
+ "NotFoundError",
54
+ "ConflictError",
55
+ "UnprocessableError",
56
+ "RateLimitError",
57
+ "ServerError",
58
+ "PaxosTimeoutError",
59
+ "NetworkError",
60
+ "is_api_error",
61
+ ]
paxos/_aio.py ADDED
@@ -0,0 +1,29 @@
1
+ """Asyncio helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ from typing import Awaitable, Optional, TypeVar
7
+
8
+ _T = TypeVar("_T")
9
+
10
+
11
+ def _retrieve(task: asyncio.Future) -> None:
12
+ if not task.cancelled():
13
+ task.exception()
14
+
15
+
16
+ async def wait_closing(awaitable: Awaitable[_T], timeout: Optional[float]) -> _T:
17
+ task = asyncio.ensure_future(awaitable)
18
+ task.add_done_callback(_retrieve)
19
+ try:
20
+ done, _ = await asyncio.wait({task}, timeout=timeout)
21
+ except BaseException:
22
+ task.cancel()
23
+ await asyncio.wait({task})
24
+ raise
25
+ if not done:
26
+ task.cancel()
27
+ await asyncio.wait({task})
28
+ raise asyncio.TimeoutError
29
+ return task.result()