|
| 1 | +"""Async REST client for the StackCoin API.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from typing import Any |
| 6 | + |
| 7 | +import httpx |
| 8 | + |
| 9 | +from .errors import StackCoinError |
| 10 | +from .models import ( |
| 11 | + CreateRequestResponse, |
| 12 | + DiscordGuild, |
| 13 | + DiscordGuildsResponse, |
| 14 | + Request, |
| 15 | + RequestActionResponse, |
| 16 | + RequestsResponse, |
| 17 | + SendStkResponse, |
| 18 | + Transaction, |
| 19 | + TransactionsResponse, |
| 20 | + User, |
| 21 | + UsersResponse, |
| 22 | +) |
| 23 | + |
| 24 | + |
| 25 | +class Client: |
| 26 | + """Async client for the StackCoin REST API. |
| 27 | +
|
| 28 | + Usage:: |
| 29 | +
|
| 30 | + async with Client("https://stackcoin.example.com", token="sk-...") as client: |
| 31 | + me = await client.get_me() |
| 32 | + print(me.username, me.balance) |
| 33 | + """ |
| 34 | + |
| 35 | + def __init__( |
| 36 | + self, |
| 37 | + base_url: str, |
| 38 | + token: str, |
| 39 | + *, |
| 40 | + timeout: float = 10.0, |
| 41 | + ) -> None: |
| 42 | + self._http = httpx.AsyncClient( |
| 43 | + base_url=base_url, |
| 44 | + headers={ |
| 45 | + "Authorization": f"Bearer {token}", |
| 46 | + "Accept": "application/json", |
| 47 | + }, |
| 48 | + timeout=timeout, |
| 49 | + ) |
| 50 | + |
| 51 | + # -- context manager -------------------------------------------------- # |
| 52 | + |
| 53 | + async def __aenter__(self) -> Client: |
| 54 | + return self |
| 55 | + |
| 56 | + async def __aexit__( |
| 57 | + self, |
| 58 | + exc_type: type[BaseException] | None, |
| 59 | + exc_val: BaseException | None, |
| 60 | + exc_tb: Any, |
| 61 | + ) -> None: |
| 62 | + await self.close() |
| 63 | + |
| 64 | + async def close(self) -> None: |
| 65 | + """Close the underlying HTTP connection pool.""" |
| 66 | + await self._http.aclose() |
| 67 | + |
| 68 | + # -- shared helpers --------------------------------------------------- # |
| 69 | + |
| 70 | + @staticmethod |
| 71 | + def _raise_for_error(resp: httpx.Response) -> None: |
| 72 | + """Raise :class:`StackCoinError` on any 4xx/5xx response.""" |
| 73 | + if resp.status_code >= 400: |
| 74 | + try: |
| 75 | + body = resp.json() |
| 76 | + except Exception: |
| 77 | + body = {} |
| 78 | + error = body.get("error", f"http_{resp.status_code}") |
| 79 | + message = body.get("message") |
| 80 | + raise StackCoinError(resp.status_code, error, message) |
| 81 | + |
| 82 | + # -- users ------------------------------------------------------------ # |
| 83 | + |
| 84 | + async def get_me(self) -> User: |
| 85 | + """Return the authenticated user's profile.""" |
| 86 | + resp = await self._http.get("/api/user/me") |
| 87 | + self._raise_for_error(resp) |
| 88 | + return User.model_validate(resp.json()) |
| 89 | + |
| 90 | + async def get_user(self, user_id: int) -> User: |
| 91 | + """Return a user by their ID.""" |
| 92 | + resp = await self._http.get(f"/api/user/{user_id}") |
| 93 | + self._raise_for_error(resp) |
| 94 | + return User.model_validate(resp.json()) |
| 95 | + |
| 96 | + async def get_users(self, *, discord_id: str | None = None) -> list[User]: |
| 97 | + """Return a list of users, optionally filtered by Discord ID.""" |
| 98 | + params: dict[str, Any] = {} |
| 99 | + if discord_id is not None: |
| 100 | + params["discord_id"] = discord_id |
| 101 | + resp = await self._http.get("/api/users", params=params) |
| 102 | + self._raise_for_error(resp) |
| 103 | + wrapper = UsersResponse.model_validate(resp.json()) |
| 104 | + return wrapper.users or [] |
| 105 | + |
| 106 | + # -- send ------------------------------------------------------------- # |
| 107 | + |
| 108 | + async def send( |
| 109 | + self, |
| 110 | + to_user_id: int, |
| 111 | + amount: int, |
| 112 | + *, |
| 113 | + label: str | None = None, |
| 114 | + idempotency_key: str | None = None, |
| 115 | + ) -> SendStkResponse: |
| 116 | + """Send STK to another user.""" |
| 117 | + body: dict[str, Any] = {"amount": amount} |
| 118 | + if label is not None: |
| 119 | + body["label"] = label |
| 120 | + headers: dict[str, str] = {} |
| 121 | + if idempotency_key is not None: |
| 122 | + headers["Idempotency-Key"] = idempotency_key |
| 123 | + resp = await self._http.post( |
| 124 | + f"/api/user/{to_user_id}/send", |
| 125 | + json=body, |
| 126 | + headers=headers, |
| 127 | + ) |
| 128 | + self._raise_for_error(resp) |
| 129 | + return SendStkResponse.model_validate(resp.json()) |
| 130 | + |
| 131 | + # -- requests --------------------------------------------------------- # |
| 132 | + |
| 133 | + async def create_request( |
| 134 | + self, |
| 135 | + to_user_id: int, |
| 136 | + amount: int, |
| 137 | + *, |
| 138 | + label: str | None = None, |
| 139 | + idempotency_key: str | None = None, |
| 140 | + ) -> CreateRequestResponse: |
| 141 | + """Create a STK request to another user.""" |
| 142 | + body: dict[str, Any] = {"amount": amount} |
| 143 | + if label is not None: |
| 144 | + body["label"] = label |
| 145 | + headers: dict[str, str] = {} |
| 146 | + if idempotency_key is not None: |
| 147 | + headers["Idempotency-Key"] = idempotency_key |
| 148 | + resp = await self._http.post( |
| 149 | + f"/api/user/{to_user_id}/request", |
| 150 | + json=body, |
| 151 | + headers=headers, |
| 152 | + ) |
| 153 | + self._raise_for_error(resp) |
| 154 | + return CreateRequestResponse.model_validate(resp.json()) |
| 155 | + |
| 156 | + async def get_request(self, request_id: int) -> Request: |
| 157 | + """Return a single request by its ID.""" |
| 158 | + resp = await self._http.get(f"/api/request/{request_id}") |
| 159 | + self._raise_for_error(resp) |
| 160 | + return Request.model_validate(resp.json()) |
| 161 | + |
| 162 | + async def get_requests(self, *, status: str | None = None) -> list[Request]: |
| 163 | + """Return requests for the authenticated user, optionally filtered by status.""" |
| 164 | + params: dict[str, Any] = {} |
| 165 | + if status is not None: |
| 166 | + params["status"] = status |
| 167 | + resp = await self._http.get("/api/requests", params=params) |
| 168 | + self._raise_for_error(resp) |
| 169 | + wrapper = RequestsResponse.model_validate(resp.json()) |
| 170 | + return wrapper.requests or [] |
| 171 | + |
| 172 | + async def accept_request(self, request_id: int) -> RequestActionResponse: |
| 173 | + """Accept a pending STK request.""" |
| 174 | + resp = await self._http.post(f"/api/requests/{request_id}/accept") |
| 175 | + self._raise_for_error(resp) |
| 176 | + return RequestActionResponse.model_validate(resp.json()) |
| 177 | + |
| 178 | + async def deny_request(self, request_id: int) -> RequestActionResponse: |
| 179 | + """Deny a pending STK request.""" |
| 180 | + resp = await self._http.post(f"/api/requests/{request_id}/deny") |
| 181 | + self._raise_for_error(resp) |
| 182 | + return RequestActionResponse.model_validate(resp.json()) |
| 183 | + |
| 184 | + # -- transactions ----------------------------------------------------- # |
| 185 | + |
| 186 | + async def get_transactions(self) -> list[Transaction]: |
| 187 | + """Return transactions for the authenticated user.""" |
| 188 | + resp = await self._http.get("/api/transactions") |
| 189 | + self._raise_for_error(resp) |
| 190 | + wrapper = TransactionsResponse.model_validate(resp.json()) |
| 191 | + return wrapper.transactions or [] |
| 192 | + |
| 193 | + async def get_transaction(self, transaction_id: int) -> Transaction: |
| 194 | + """Return a single transaction by its ID.""" |
| 195 | + resp = await self._http.get(f"/api/transaction/{transaction_id}") |
| 196 | + self._raise_for_error(resp) |
| 197 | + return Transaction.model_validate(resp.json()) |
| 198 | + |
| 199 | + # -- events ----------------------------------------------------------- # |
| 200 | + |
| 201 | + async def get_events(self, *, since_id: int = 0) -> list[dict[str, Any]]: |
| 202 | + """Return events since the given ID. |
| 203 | +
|
| 204 | + Events are not yet in the OpenAPI spec, so this returns raw dicts. |
| 205 | + """ |
| 206 | + params: dict[str, Any] = {} |
| 207 | + if since_id: |
| 208 | + params["since_id"] = since_id |
| 209 | + resp = await self._http.get("/api/events", params=params) |
| 210 | + self._raise_for_error(resp) |
| 211 | + data = resp.json() |
| 212 | + return data.get("events", data) if isinstance(data, dict) else data |
| 213 | + |
| 214 | + # -- discord guilds --------------------------------------------------- # |
| 215 | + |
| 216 | + async def get_discord_guilds(self) -> list[DiscordGuild]: |
| 217 | + """Return all Discord guilds.""" |
| 218 | + resp = await self._http.get("/api/discord/guilds") |
| 219 | + self._raise_for_error(resp) |
| 220 | + wrapper = DiscordGuildsResponse.model_validate(resp.json()) |
| 221 | + return wrapper.guilds or [] |
| 222 | + |
| 223 | + async def get_discord_guild(self, snowflake: str) -> DiscordGuild: |
| 224 | + """Return a single Discord guild by its snowflake ID.""" |
| 225 | + resp = await self._http.get(f"/api/discord/guild/{snowflake}") |
| 226 | + self._raise_for_error(resp) |
| 227 | + return DiscordGuild.model_validate(resp.json()) |
0 commit comments