upside-python-sdk 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Upside
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,205 @@
1
+ Metadata-Version: 2.4
2
+ Name: upside-python-sdk
3
+ Version: 0.1.0
4
+ Summary: Python SDK for the Upside decentralized perpetuals exchange (REST + WebSocket).
5
+ License: MIT
6
+ License-File: LICENSE
7
+ Keywords: upside,perpetuals,dex,trading,eip712,websocket
8
+ Author: Upside
9
+ Author-email: dev@upsidemax.xyz
10
+ Requires-Python: >=3.9,<4.0
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.9
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Requires-Dist: eth-account (>=0.10,<0.14)
20
+ Requires-Dist: eth-utils (>=2.3.0)
21
+ Requires-Dist: requests (>=2.31.0)
22
+ Requires-Dist: typing-extensions (>=4.5.0) ; python_version < "3.11"
23
+ Requires-Dist: websocket-client (>=1.7.0,<2.0.0)
24
+ Project-URL: Documentation, https://docs.upsidemax.xyz
25
+ Project-URL: Homepage, https://docs.upsidemax.xyz
26
+ Project-URL: Repository, https://github.com/upsidemax/upside-python-sdk
27
+ Description-Content-Type: text/markdown
28
+
29
+ # Upside Python SDK
30
+
31
+ A Python client for the [Upside](https://docs.upsidemax.xyz) decentralized
32
+ perpetuals exchange — REST reads (`POST /info`), signed writes (`POST /exchange`),
33
+ and realtime WebSocket streams.
34
+
35
+ - **EIP-712 request signing** (secp256k1) with the Agent and Typed paths — no API keys.
36
+ - **Synchronous REST** over `requests`, **threaded WebSocket** over `websocket-client`.
37
+ - Raw-dict responses, `TypedDict` inputs, full type hints (ships `py.typed`).
38
+ - Agent (API-wallet) delegation, TP/SL, leverage/margin, and collateral actions.
39
+
40
+ > The default environment is the **QA testnet** (`https://dev.upsidemax.xyz`).
41
+ > Contract IDs, scales, and tick/step sizes are server-assigned — always read
42
+ > them from `configs`, never hardcode.
43
+
44
+ ## Installation
45
+
46
+ ```bash
47
+ pip install upside-python-sdk
48
+ ```
49
+
50
+ Requires Python 3.9+. Runtime dependencies: `requests`, `websocket-client`,
51
+ `eth-account`, `eth-utils`.
52
+
53
+ ## Quick start
54
+
55
+ ```python
56
+ from upside import Info, Exchange
57
+ from upside.utils import constants
58
+
59
+ # --- reads (no signing) ---
60
+ info = Info(base_url=constants.QA_API_URL)
61
+ cfg = info.configs()
62
+ contract = next(c for c in cfg["contracts"] if c["status"] == "Active")
63
+ asset = contract["contractId"]
64
+ print(info.market_state(asset))
65
+
66
+ # --- writes (EIP-712 signed) ---
67
+ exchange = Exchange("0x<private-key>", base_url=constants.QA_API_URL)
68
+
69
+ # Register (QA requires an invite code from the Upside team). A 10,000 USDC
70
+ # test airdrop lands within ~10s.
71
+ exchange.register_account(invite_code="<invite-code>")
72
+
73
+ # Place a resting limit buy. Prices/sizes are raw integer strings — scale them
74
+ # with the contract's priceScale / qtyScale from configs.
75
+ exchange.order(asset=asset, is_buy=True, size="10", price="50")
76
+ ```
77
+
78
+ ## Reading data — `Info`
79
+
80
+ All methods return the raw parsed JSON. See
81
+ [docs.upsidemax.xyz/info](https://docs.upsidemax.xyz/info/overview) for response shapes.
82
+
83
+ ```python
84
+ info.configs() # contracts, coins, scales, tiers (cache this)
85
+ info.l2_book(asset) # full order book snapshot
86
+ info.market_state(asset) # mark/oracle/last price, funding
87
+ info.candle_snapshot(asset, "1m", start, end) # historical OHLCV
88
+ info.user_account(account_id, market_deployer_id)
89
+ info.user_orders(account_id, market_deployer_id, contract_id=0)
90
+ info.orders_by_ids(market_deployer_id, ["8280"])
91
+ info.orders_by_cloids(account_id, market_deployer_id, ["1778844423064"])
92
+ info.user_agents(account_id)
93
+ info.user_market_deployers(account_id)
94
+ info.share_group_state()
95
+ ```
96
+
97
+ ## Trading — `Exchange`
98
+
99
+ ```python
100
+ from upside import Cloid
101
+
102
+ exchange.order(asset=1, is_buy=True, size="10", price="50", cloid=Cloid.from_int(1001))
103
+ exchange.market_order(asset=1, is_buy=False, size="5")
104
+ exchange.bulk_orders([...]) # up to 10 orders, one signature
105
+ exchange.cancel(asset=1, oid=15)
106
+ exchange.cancel_by_cloid(asset=1, cloid=1001)
107
+ exchange.cancel_all(asset=1)
108
+ exchange.modify(asset=1, oid=15, price="151", size="8")
109
+
110
+ exchange.update_leverage(asset=1, leverage=20)
111
+ exchange.update_margin_mode(asset=1, is_cross=False, is_hedge=True)
112
+ exchange.update_isolated_margin(asset=1, ntli=5000)
113
+
114
+ exchange.tp_sl(asset=1, tp_price="90000", sl_price="80000")
115
+ exchange.cancel_tp_sl(asset=1)
116
+ exchange.cancel_conditional(oid=123)
117
+
118
+ exchange.lock_collateral(market_deployer_id=1, coin_id=1, amount="1000")
119
+ exchange.transfer_between_deployers(1, 2, coin_id=1, amount="1000")
120
+ ```
121
+
122
+ ### Order placement is asynchronous
123
+
124
+ A batch returns `{"status": "accepted", "response": {"type": "order", "data": {"count": n}}}`
125
+ — **not** the resting order id. Read the resulting state from
126
+ `Info.user_orders` / `orders_by_cloids`, or the `orderUpdates` / `userFills`
127
+ WebSocket channels. Cancels, modifies, and margin actions respond synchronously.
128
+
129
+ ### HTTP 200 ≠ success
130
+
131
+ Gateway failures (bad signature, reused nonce, rate limit) raise `ClientError`
132
+ (4xx) / `ServerError` (5xx). Business rejections come back as HTTP 200 — a per-item
133
+ `error` string in `statuses[]`, or a non-zero `errorCode` in `response.data`.
134
+ Always inspect them.
135
+
136
+ ## Agent (API-wallet) delegation
137
+
138
+ Keep the master key offline; authorize a hot agent key to sign trades. The
139
+ server routes agent-signed actions to the master account.
140
+
141
+ ```python
142
+ response, agent_key = master.approve_agent(agent_name="bot1") # generates a fresh key
143
+ agent = Exchange(agent_key, base_url=constants.QA_API_URL, account_id=master.account_id)
144
+ agent.order(asset=1, is_buy=True, size="10", price="50")
145
+ master.revoke_agent(agent.address)
146
+ ```
147
+
148
+ ## WebSocket streams
149
+
150
+ ```python
151
+ info = Info(base_url=constants.QA_API_URL) # WS starts automatically
152
+
153
+ sid = info.subscribe({"type": "l2Book", "asset": "1"}, lambda m: print(m["data"]["bookVersion"]))
154
+ info.subscribe({"type": "trades", "asset": "1"}, print)
155
+ info.subscribe({"type": "orderUpdates", "user": "0x<address>"}, print) # private: pass the wallet address
156
+ info.subscribe({"type": "userFills", "user": "0x<address>"}, print)
157
+
158
+ info.unsubscribe({"type": "l2Book", "asset": "1"}, sid)
159
+ info.close()
160
+ ```
161
+
162
+ Channels: `l2Book`, `bbo`, `trades`, `candle`, `config` (public) and
163
+ `orderUpdates`, `openOrders`, `userFills` (per-address). The client pings every
164
+ 30s and auto-reconnects, replaying subscriptions. WebSocket does **not** push
165
+ position or balance changes — poll `userAccount` for those.
166
+
167
+ ## Signing
168
+
169
+ Every `/exchange` write is authorized by an EIP-712 signature over a fixed
170
+ domain (`Exchange` / `1` / chainId `9767` / zero verifying contract). The SDK
171
+ handles both paths automatically:
172
+
173
+ - **Typed path** — `registerAccount`, `approveAgent`, `revokeAgent`,
174
+ `lockCollateral`, `unlockCollateral`, `transferBetweenDeployers`.
175
+ - **Agent path** — every other action (canonical-JSON `actionHash`).
176
+
177
+ Nonces are strictly increasing millisecond timestamps managed per `Exchange`
178
+ instance (`NonceManager`). See
179
+ [docs.upsidemax.xyz/guide/authentication](https://docs.upsidemax.xyz/guide/authentication).
180
+
181
+ ## Examples
182
+
183
+ Runnable scripts live in [`examples/`](examples). Copy `config.json.example` to
184
+ `config.json`, set your test wallet and invite code, then:
185
+
186
+ ```bash
187
+ python examples/01_register_and_airdrop.py
188
+ python examples/03_place_and_cancel_order.py
189
+ python examples/06_websocket_streams.py
190
+ ```
191
+
192
+ ## Development
193
+
194
+ ```bash
195
+ make install # poetry install
196
+ make test # pytest
197
+ make lint # black --check + ruff
198
+ make typecheck # mypy
199
+ make check # all of the above
200
+ ```
201
+
202
+ ## License
203
+
204
+ MIT — see [LICENSE](LICENSE).
205
+
@@ -0,0 +1,176 @@
1
+ # Upside Python SDK
2
+
3
+ A Python client for the [Upside](https://docs.upsidemax.xyz) decentralized
4
+ perpetuals exchange — REST reads (`POST /info`), signed writes (`POST /exchange`),
5
+ and realtime WebSocket streams.
6
+
7
+ - **EIP-712 request signing** (secp256k1) with the Agent and Typed paths — no API keys.
8
+ - **Synchronous REST** over `requests`, **threaded WebSocket** over `websocket-client`.
9
+ - Raw-dict responses, `TypedDict` inputs, full type hints (ships `py.typed`).
10
+ - Agent (API-wallet) delegation, TP/SL, leverage/margin, and collateral actions.
11
+
12
+ > The default environment is the **QA testnet** (`https://dev.upsidemax.xyz`).
13
+ > Contract IDs, scales, and tick/step sizes are server-assigned — always read
14
+ > them from `configs`, never hardcode.
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ pip install upside-python-sdk
20
+ ```
21
+
22
+ Requires Python 3.9+. Runtime dependencies: `requests`, `websocket-client`,
23
+ `eth-account`, `eth-utils`.
24
+
25
+ ## Quick start
26
+
27
+ ```python
28
+ from upside import Info, Exchange
29
+ from upside.utils import constants
30
+
31
+ # --- reads (no signing) ---
32
+ info = Info(base_url=constants.QA_API_URL)
33
+ cfg = info.configs()
34
+ contract = next(c for c in cfg["contracts"] if c["status"] == "Active")
35
+ asset = contract["contractId"]
36
+ print(info.market_state(asset))
37
+
38
+ # --- writes (EIP-712 signed) ---
39
+ exchange = Exchange("0x<private-key>", base_url=constants.QA_API_URL)
40
+
41
+ # Register (QA requires an invite code from the Upside team). A 10,000 USDC
42
+ # test airdrop lands within ~10s.
43
+ exchange.register_account(invite_code="<invite-code>")
44
+
45
+ # Place a resting limit buy. Prices/sizes are raw integer strings — scale them
46
+ # with the contract's priceScale / qtyScale from configs.
47
+ exchange.order(asset=asset, is_buy=True, size="10", price="50")
48
+ ```
49
+
50
+ ## Reading data — `Info`
51
+
52
+ All methods return the raw parsed JSON. See
53
+ [docs.upsidemax.xyz/info](https://docs.upsidemax.xyz/info/overview) for response shapes.
54
+
55
+ ```python
56
+ info.configs() # contracts, coins, scales, tiers (cache this)
57
+ info.l2_book(asset) # full order book snapshot
58
+ info.market_state(asset) # mark/oracle/last price, funding
59
+ info.candle_snapshot(asset, "1m", start, end) # historical OHLCV
60
+ info.user_account(account_id, market_deployer_id)
61
+ info.user_orders(account_id, market_deployer_id, contract_id=0)
62
+ info.orders_by_ids(market_deployer_id, ["8280"])
63
+ info.orders_by_cloids(account_id, market_deployer_id, ["1778844423064"])
64
+ info.user_agents(account_id)
65
+ info.user_market_deployers(account_id)
66
+ info.share_group_state()
67
+ ```
68
+
69
+ ## Trading — `Exchange`
70
+
71
+ ```python
72
+ from upside import Cloid
73
+
74
+ exchange.order(asset=1, is_buy=True, size="10", price="50", cloid=Cloid.from_int(1001))
75
+ exchange.market_order(asset=1, is_buy=False, size="5")
76
+ exchange.bulk_orders([...]) # up to 10 orders, one signature
77
+ exchange.cancel(asset=1, oid=15)
78
+ exchange.cancel_by_cloid(asset=1, cloid=1001)
79
+ exchange.cancel_all(asset=1)
80
+ exchange.modify(asset=1, oid=15, price="151", size="8")
81
+
82
+ exchange.update_leverage(asset=1, leverage=20)
83
+ exchange.update_margin_mode(asset=1, is_cross=False, is_hedge=True)
84
+ exchange.update_isolated_margin(asset=1, ntli=5000)
85
+
86
+ exchange.tp_sl(asset=1, tp_price="90000", sl_price="80000")
87
+ exchange.cancel_tp_sl(asset=1)
88
+ exchange.cancel_conditional(oid=123)
89
+
90
+ exchange.lock_collateral(market_deployer_id=1, coin_id=1, amount="1000")
91
+ exchange.transfer_between_deployers(1, 2, coin_id=1, amount="1000")
92
+ ```
93
+
94
+ ### Order placement is asynchronous
95
+
96
+ A batch returns `{"status": "accepted", "response": {"type": "order", "data": {"count": n}}}`
97
+ — **not** the resting order id. Read the resulting state from
98
+ `Info.user_orders` / `orders_by_cloids`, or the `orderUpdates` / `userFills`
99
+ WebSocket channels. Cancels, modifies, and margin actions respond synchronously.
100
+
101
+ ### HTTP 200 ≠ success
102
+
103
+ Gateway failures (bad signature, reused nonce, rate limit) raise `ClientError`
104
+ (4xx) / `ServerError` (5xx). Business rejections come back as HTTP 200 — a per-item
105
+ `error` string in `statuses[]`, or a non-zero `errorCode` in `response.data`.
106
+ Always inspect them.
107
+
108
+ ## Agent (API-wallet) delegation
109
+
110
+ Keep the master key offline; authorize a hot agent key to sign trades. The
111
+ server routes agent-signed actions to the master account.
112
+
113
+ ```python
114
+ response, agent_key = master.approve_agent(agent_name="bot1") # generates a fresh key
115
+ agent = Exchange(agent_key, base_url=constants.QA_API_URL, account_id=master.account_id)
116
+ agent.order(asset=1, is_buy=True, size="10", price="50")
117
+ master.revoke_agent(agent.address)
118
+ ```
119
+
120
+ ## WebSocket streams
121
+
122
+ ```python
123
+ info = Info(base_url=constants.QA_API_URL) # WS starts automatically
124
+
125
+ sid = info.subscribe({"type": "l2Book", "asset": "1"}, lambda m: print(m["data"]["bookVersion"]))
126
+ info.subscribe({"type": "trades", "asset": "1"}, print)
127
+ info.subscribe({"type": "orderUpdates", "user": "0x<address>"}, print) # private: pass the wallet address
128
+ info.subscribe({"type": "userFills", "user": "0x<address>"}, print)
129
+
130
+ info.unsubscribe({"type": "l2Book", "asset": "1"}, sid)
131
+ info.close()
132
+ ```
133
+
134
+ Channels: `l2Book`, `bbo`, `trades`, `candle`, `config` (public) and
135
+ `orderUpdates`, `openOrders`, `userFills` (per-address). The client pings every
136
+ 30s and auto-reconnects, replaying subscriptions. WebSocket does **not** push
137
+ position or balance changes — poll `userAccount` for those.
138
+
139
+ ## Signing
140
+
141
+ Every `/exchange` write is authorized by an EIP-712 signature over a fixed
142
+ domain (`Exchange` / `1` / chainId `9767` / zero verifying contract). The SDK
143
+ handles both paths automatically:
144
+
145
+ - **Typed path** — `registerAccount`, `approveAgent`, `revokeAgent`,
146
+ `lockCollateral`, `unlockCollateral`, `transferBetweenDeployers`.
147
+ - **Agent path** — every other action (canonical-JSON `actionHash`).
148
+
149
+ Nonces are strictly increasing millisecond timestamps managed per `Exchange`
150
+ instance (`NonceManager`). See
151
+ [docs.upsidemax.xyz/guide/authentication](https://docs.upsidemax.xyz/guide/authentication).
152
+
153
+ ## Examples
154
+
155
+ Runnable scripts live in [`examples/`](examples). Copy `config.json.example` to
156
+ `config.json`, set your test wallet and invite code, then:
157
+
158
+ ```bash
159
+ python examples/01_register_and_airdrop.py
160
+ python examples/03_place_and_cancel_order.py
161
+ python examples/06_websocket_streams.py
162
+ ```
163
+
164
+ ## Development
165
+
166
+ ```bash
167
+ make install # poetry install
168
+ make test # pytest
169
+ make lint # black --check + ruff
170
+ make typecheck # mypy
171
+ make check # all of the above
172
+ ```
173
+
174
+ ## License
175
+
176
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,61 @@
1
+ [tool.poetry]
2
+ name = "upside-python-sdk"
3
+ version = "0.1.0"
4
+ description = "Python SDK for the Upside decentralized perpetuals exchange (REST + WebSocket)."
5
+ authors = ["Upside <dev@upsidemax.xyz>"]
6
+ license = "MIT"
7
+ readme = "README.md"
8
+ homepage = "https://docs.upsidemax.xyz"
9
+ repository = "https://github.com/upsidemax/upside-python-sdk"
10
+ documentation = "https://docs.upsidemax.xyz"
11
+ keywords = ["upside", "perpetuals", "dex", "trading", "eip712", "websocket"]
12
+ packages = [{ include = "upside", from = "src" }]
13
+
14
+ [tool.poetry.dependencies]
15
+ python = "^3.9"
16
+ requests = ">=2.31.0"
17
+ websocket-client = "^1.7.0"
18
+ eth-account = ">=0.10,<0.14"
19
+ eth-utils = ">=2.3.0"
20
+ typing-extensions = { version = ">=4.5.0", python = "<3.11" }
21
+
22
+ [tool.poetry.group.dev.dependencies]
23
+ pytest = "^8.3.0"
24
+ pytest-cov = "^5.0.0"
25
+ responses = "^0.25.0"
26
+ black = "^24.10.0"
27
+ ruff = "^0.7.0"
28
+ mypy = "^1.13.0"
29
+ types-requests = ">=2.31.0"
30
+ pre-commit = "^3.8.0"
31
+
32
+ [build-system]
33
+ requires = ["poetry-core>=1.9.0"]
34
+ build-backend = "poetry.core.masonry.api"
35
+
36
+ [tool.black]
37
+ line-length = 120
38
+ target-version = ["py39"]
39
+
40
+ [tool.ruff]
41
+ line-length = 120
42
+ target-version = "py39"
43
+
44
+ [tool.ruff.lint]
45
+ # UP (pyupgrade) is intentionally excluded: the SDK targets Python 3.9 and uses
46
+ # typing.List/Optional style consistent with the reference SDKs.
47
+ select = ["E", "F", "W", "I", "B"]
48
+ ignore = ["E501"]
49
+
50
+ [tool.mypy]
51
+ python_version = "3.9"
52
+ warn_unused_ignores = true
53
+ warn_return_any = true
54
+ no_implicit_optional = true
55
+ strict_equality = true
56
+ check_untyped_defs = true
57
+ ignore_missing_imports = true
58
+
59
+ [tool.pytest.ini_options]
60
+ addopts = "--strict-markers -ra"
61
+ testpaths = ["tests"]
@@ -0,0 +1,42 @@
1
+ """Upside Python SDK — REST (`/info`, `/exchange`) and WebSocket client.
2
+
3
+ Quick start::
4
+
5
+ from upside import Info, Exchange
6
+ from upside.utils import constants
7
+
8
+ info = Info(base_url=constants.QA_API_URL)
9
+ print(info.configs())
10
+
11
+ exchange = Exchange(private_key, base_url=constants.QA_API_URL)
12
+ exchange.order(asset=1, is_buy=True, size="10", price="50")
13
+
14
+ See https://docs.upsidemax.xyz for the full API reference.
15
+ """
16
+
17
+ from .api import API
18
+ from .exchange import Exchange
19
+ from .info import Info
20
+ from .utils import constants
21
+ from .utils.error import APIError, ClientError, ServerError, UpsideError, WebsocketError
22
+ from .utils.signing import NonceManager
23
+ from .utils.types import Cloid
24
+ from .websocket_manager import WebsocketManager
25
+
26
+ __version__ = "0.1.0"
27
+
28
+ __all__ = [
29
+ "API",
30
+ "Info",
31
+ "Exchange",
32
+ "WebsocketManager",
33
+ "NonceManager",
34
+ "Cloid",
35
+ "constants",
36
+ "UpsideError",
37
+ "APIError",
38
+ "ClientError",
39
+ "ServerError",
40
+ "WebsocketError",
41
+ "__version__",
42
+ ]
@@ -0,0 +1,61 @@
1
+ """Base HTTP transport shared by :class:`~upside.info.Info` and
2
+ :class:`~upside.exchange.Exchange`.
3
+
4
+ Everything is a JSON ``POST`` to ``/info`` or ``/exchange`` over one persistent
5
+ session. Gateway-level failures (non-2xx, or a body with ``"status": "error"``)
6
+ raise :class:`~upside.utils.error.ClientError` / ``ServerError``; business-level
7
+ outcomes (per-order ``statuses[].error``, non-zero ``errorCode``) are returned
8
+ verbatim for the caller to inspect.
9
+ """
10
+
11
+ import logging
12
+ from json import JSONDecodeError
13
+ from typing import Any, Optional, cast
14
+
15
+ import requests
16
+
17
+ from .utils import constants
18
+ from .utils.error import ClientError, ServerError
19
+ from .utils.types import Json
20
+
21
+
22
+ class API:
23
+ """Thin POST-only client with status-based exception mapping."""
24
+
25
+ def __init__(self, base_url: Optional[str] = None, timeout: Optional[float] = None) -> None:
26
+ self.base_url = (base_url or constants.QA_API_URL).rstrip("/")
27
+ self.timeout = timeout
28
+ self.session = requests.Session()
29
+ self.session.headers.update({"Content-Type": "application/json"})
30
+ self._logger = logging.getLogger("upside")
31
+
32
+ def post(self, url_path: str, payload: Optional[Any] = None) -> Json:
33
+ """POST ``payload`` to ``url_path`` and return the parsed JSON body."""
34
+ url = self.base_url + url_path
35
+ response = self.session.post(url, json=payload or {}, timeout=self.timeout)
36
+ return self._handle_response(response)
37
+
38
+ def _handle_response(self, response: requests.Response) -> Json:
39
+ try:
40
+ body = response.json()
41
+ except (JSONDecodeError, ValueError):
42
+ body = None
43
+
44
+ if response.ok and not (isinstance(body, dict) and body.get("status") == "error"):
45
+ if body is None:
46
+ raise ServerError(response.status_code, message=f"non-JSON response: {response.text[:200]}")
47
+ return cast(Json, body)
48
+
49
+ code = message = request_id = None
50
+ if isinstance(body, dict):
51
+ code = body.get("code")
52
+ message = body.get("message")
53
+ request_id = body.get("requestId")
54
+ else:
55
+ message = response.text[:500] or None
56
+
57
+ error_cls = ClientError if 400 <= response.status_code < 500 else ServerError
58
+ raise error_cls(response.status_code, code=code, message=message, request_id=request_id)
59
+
60
+ def close(self) -> None:
61
+ self.session.close()