squarecloud-api 4.0.0__tar.gz → 5.0.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.
- squarecloud_api-5.0.0/.gitignore +7 -0
- squarecloud_api-5.0.0/PKG-INFO +292 -0
- squarecloud_api-5.0.0/README.md +268 -0
- squarecloud_api-5.0.0/pyproject.toml +70 -0
- squarecloud_api-5.0.0/src/squarecloud/__init__.py +29 -0
- squarecloud_api-5.0.0/src/squarecloud/client.py +1532 -0
- squarecloud_api-5.0.0/src/squarecloud/errors.py +112 -0
- squarecloud_api-5.0.0/src/squarecloud/types.py +482 -0
- squarecloud_api-4.0.0/PKG-INFO +0 -72
- squarecloud_api-4.0.0/README.md +0 -54
- squarecloud_api-4.0.0/pyproject.toml +0 -148
- squarecloud_api-4.0.0/src/squarecloud/__init__.py +0 -50
- squarecloud_api-4.0.0/src/squarecloud/app.py +0 -764
- squarecloud_api-4.0.0/src/squarecloud/client.py +0 -1149
- squarecloud_api-4.0.0/src/squarecloud/data/__init__.py +0 -44
- squarecloud_api-4.0.0/src/squarecloud/data/app.py +0 -41
- squarecloud_api-4.0.0/src/squarecloud/data/base.py +0 -15
- squarecloud_api-4.0.0/src/squarecloud/data/base_database.py +0 -8
- squarecloud_api-4.0.0/src/squarecloud/data/certificate.py +0 -58
- squarecloud_api-4.0.0/src/squarecloud/data/database.py +0 -10
- squarecloud_api-4.0.0/src/squarecloud/data/database_info.py +0 -17
- squarecloud_api-4.0.0/src/squarecloud/data/deploy_data.py +0 -11
- squarecloud_api-4.0.0/src/squarecloud/data/dns_record.py +0 -8
- squarecloud_api-4.0.0/src/squarecloud/data/domain_analytics.py +0 -62
- squarecloud_api-4.0.0/src/squarecloud/data/file_info.py +0 -30
- squarecloud_api-4.0.0/src/squarecloud/data/language.py +0 -6
- squarecloud_api-4.0.0/src/squarecloud/data/logs.py +0 -15
- squarecloud_api-4.0.0/src/squarecloud/data/plan.py +0 -23
- squarecloud_api-4.0.0/src/squarecloud/data/snapshot.py +0 -34
- squarecloud_api-4.0.0/src/squarecloud/data/snapshot_info.py +0 -16
- squarecloud_api-4.0.0/src/squarecloud/data/status.py +0 -46
- squarecloud_api-4.0.0/src/squarecloud/data/upload.py +0 -37
- squarecloud_api-4.0.0/src/squarecloud/data/user.py +0 -26
- squarecloud_api-4.0.0/src/squarecloud/data/workspace.py +0 -53
- squarecloud_api-4.0.0/src/squarecloud/errors.py +0 -238
- squarecloud_api-4.0.0/src/squarecloud/file.py +0 -60
- squarecloud_api-4.0.0/src/squarecloud/http/__init__.py +0 -4
- squarecloud_api-4.0.0/src/squarecloud/http/endpoints.py +0 -584
- squarecloud_api-4.0.0/src/squarecloud/http/http_client.py +0 -1122
- squarecloud_api-4.0.0/src/squarecloud/listeners/__init__.py +0 -140
- squarecloud_api-4.0.0/src/squarecloud/listeners/capture_listener.py +0 -115
- squarecloud_api-4.0.0/src/squarecloud/listeners/request_listener.py +0 -74
- squarecloud_api-4.0.0/src/squarecloud/logger.py +0 -58
- squarecloud_api-4.0.0/src/squarecloud/utils.py +0 -75
- {squarecloud_api-4.0.0 → squarecloud_api-5.0.0}/LICENSE +0 -0
- {squarecloud_api-4.0.0 → squarecloud_api-5.0.0}/src/squarecloud/py.typed +0 -0
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: squarecloud-api
|
|
3
|
+
Version: 5.0.0
|
|
4
|
+
Summary: The official Python SDK for the Square Cloud API
|
|
5
|
+
Project-URL: Homepage, https://squarecloud.app
|
|
6
|
+
Project-URL: Documentation, https://docs.squarecloud.app/en/sdks/py/client
|
|
7
|
+
Project-URL: Repository, https://github.com/squarecloudofc/sdk-api-py
|
|
8
|
+
Project-URL: Changelog, https://github.com/squarecloudofc/sdk-api-py/releases
|
|
9
|
+
Author-email: Square Cloud <support@squarecloud.app>
|
|
10
|
+
Maintainer-email: Robert Nogueira <robertlucasnogueira@gmail.com>
|
|
11
|
+
License-Expression: MIT
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Keywords: api,hosting,sdk,squarecloud
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.11
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
<div align="center">
|
|
26
|
+
<img alt="Square Cloud Banner" src="https://cdn.squarecloud.app/png/github-readme.png">
|
|
27
|
+
</div>
|
|
28
|
+
|
|
29
|
+
<h1 align="center">squarecloud-api</h1>
|
|
30
|
+
|
|
31
|
+
<p align="center">The official Python SDK for the <a href="https://squarecloud.app" target="_blank">Square Cloud</a> API.</p>
|
|
32
|
+
|
|
33
|
+
<div align="center">
|
|
34
|
+
<a href="https://pypi.org/project/squarecloud-api/"><img alt="PyPI Version" src="https://img.shields.io/pypi/v/squarecloud-api"></a>
|
|
35
|
+
<img alt="License" src="https://img.shields.io/pypi/l/squarecloud-api">
|
|
36
|
+
<img alt="Downloads" src="https://img.shields.io/pypi/dm/squarecloud-api">
|
|
37
|
+
</div>
|
|
38
|
+
|
|
39
|
+
- **Zero runtime dependencies**: only the standard library (`http.client`, `json`, `ssl`), with one keep-alive connection per thread.
|
|
40
|
+
- Runs on **Python 3.11+**, sync (`SquareCloud`) and async (`AsyncSquareCloud`), fully typed (`TypedDict` responses, `py.typed`).
|
|
41
|
+
- Covers all **67 operations** of the Square Cloud API, checked against the pinned OpenAPI spec on every CI run.
|
|
42
|
+
- Uploads and snapshot downloads **stream**; realtime logs and status come as an **iterator** (or `async for`).
|
|
43
|
+
- **One error type**, `SquareCloudAPIError`, for every API, network and local failure.
|
|
44
|
+
|
|
45
|
+
[Documentation](https://docs.squarecloud.app/en/sdks/py/client) · [Releases](https://github.com/squarecloudofc/sdk-api-py/releases) · [Migration guide](MIGRATION.md)
|
|
46
|
+
|
|
47
|
+
## Installation
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
pip install squarecloud-api
|
|
51
|
+
uv add squarecloud-api
|
|
52
|
+
poetry add squarecloud-api
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Requires Python 3.11 or newer.
|
|
56
|
+
|
|
57
|
+
## API key
|
|
58
|
+
|
|
59
|
+
Create one at [squarecloud.app/account/security](https://squarecloud.app/account/security). A key can be limited to scopes (`apps:read`, `apps:deploy`, ...) and to specific apps or databases. A call outside those limits raises `SquareCloudAPIError` with 403 `MISSING_SCOPE` or `RESOURCE_NOT_ALLOWED`, and list endpoints return only the resources the key can see. An unknown, revoked or expired key is 401 `ACCESS_DENIED`.
|
|
60
|
+
|
|
61
|
+
## Quick start
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
import os
|
|
65
|
+
from squarecloud import SquareCloud
|
|
66
|
+
|
|
67
|
+
with SquareCloud(os.environ['SQUARECLOUD_API_KEY']) as client:
|
|
68
|
+
me = client.account.me()
|
|
69
|
+
print(me['user']['name'], [app['name'] for app in me['applications']])
|
|
70
|
+
|
|
71
|
+
app_id = me['applications'][0]['id']
|
|
72
|
+
client.apps.restart(app_id)
|
|
73
|
+
print(client.apps.logs(app_id))
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
The same API with `await`:
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
import asyncio
|
|
80
|
+
import os
|
|
81
|
+
|
|
82
|
+
from squarecloud import AsyncSquareCloud
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
async def main() -> None:
|
|
86
|
+
async with AsyncSquareCloud(os.environ['SQUARECLOUD_API_KEY']) as client:
|
|
87
|
+
statuses = await client.apps.status_all()
|
|
88
|
+
print([s['id'] for s in statuses if s['running']])
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
asyncio.run(main())
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
More in [`examples/`](examples): [apps](examples/apps.py), [realtime](examples/realtime.py), [snapshots](examples/snapshots.py), [databases](examples/databases.py), [workspaces](examples/workspaces.py), [async client](examples/async_client.py).
|
|
95
|
+
|
|
96
|
+
## Configuration
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
import os
|
|
100
|
+
|
|
101
|
+
from squarecloud import BASE_URL, SquareCloud, __version__
|
|
102
|
+
|
|
103
|
+
client = SquareCloud(
|
|
104
|
+
os.environ['SQUARECLOUD_API_KEY'],
|
|
105
|
+
base_url=BASE_URL, # the options are keyword-only; these are the defaults
|
|
106
|
+
timeout=30.0,
|
|
107
|
+
max_retries=2,
|
|
108
|
+
transport=None,
|
|
109
|
+
user_agent=f'squarecloud-sdk-py/{__version__}',
|
|
110
|
+
)
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
| Option | Default | Notes |
|
|
114
|
+
|---|---|---|
|
|
115
|
+
| `api_key` | required | Sent raw in `Authorization`. An empty or whitespace-only key raises `ValueError`. |
|
|
116
|
+
| `base_url` | `BASE_URL` = `https://api.squarecloud.app/v2` | A trailing `/` is stripped. |
|
|
117
|
+
| `timeout` | `30.0` | Seconds per socket operation. `<= 0` disables every timeout, floors included. See [Retries, timeouts and rate limits](#retries-timeouts-and-rate-limits). |
|
|
118
|
+
| `max_retries` | `2` | Negative counts as 0. |
|
|
119
|
+
| `transport` | `HTTPTransport(timeout)` | Plug your own HTTP client (see below). |
|
|
120
|
+
| `user_agent` | `squarecloud-sdk-py/<version>` | Replaces the whole `User-Agent` header. |
|
|
121
|
+
|
|
122
|
+
`AsyncSquareCloud` takes the same arguments. Both clients are thread-safe; call `close()` (or use `with` / `async with`) to close their connections. The version is `squarecloud.__version__`.
|
|
123
|
+
|
|
124
|
+
### Custom transport
|
|
125
|
+
|
|
126
|
+
`transport=` accepts any callable `transport(method, url, headers, body, timeout, stream)` that returns an object with `status`, `read()`, `readline()` and `close()` (an `http.client.HTTPResponse` qualifies). Use it for proxies, tracing or tests. `body` is `bytes`, an iterable of `bytes` chunks (with `Content-Length` already set) or `None`. `timeout` is the per-socket-operation timeout (raised for the held calls), or `None` for uploads, large file writes and the realtime stream, which a custom transport should bound on connect itself. The default `HTTPTransport(timeout)` still bounds their connect, and asks for gzip on every call except the streamed ones (realtime and snapshot downloads).
|
|
127
|
+
|
|
128
|
+
### Logging
|
|
129
|
+
|
|
130
|
+
The SDK logs each request at `DEBUG` on the `squarecloud` logger (method, path and status; never bodies or keys) and attaches only a `NullHandler`:
|
|
131
|
+
|
|
132
|
+
```python
|
|
133
|
+
import logging
|
|
134
|
+
|
|
135
|
+
logging.basicConfig()
|
|
136
|
+
logging.getLogger('squarecloud').setLevel(logging.DEBUG)
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
## API
|
|
140
|
+
|
|
141
|
+
Every app id may also be the composite `'<appId>-<workspaceId>'` to act on an app shared with you through a workspace. Optional modifiers are keyword-only.
|
|
142
|
+
|
|
143
|
+
| Group | Methods |
|
|
144
|
+
|---|---|
|
|
145
|
+
| `account` | `me()`, `snapshots(*, scope=None)` |
|
|
146
|
+
| `service` | `status()` (public route: the API does not check the key, but the client still needs a non-empty one) |
|
|
147
|
+
| `ai` | `chat(request)` (OpenAI-compatible, non-streaming) |
|
|
148
|
+
| `apps` | `create(file)`, `get(id)`, `delete(id)`, `status_all(*, workspace_id=None)`, `status(id, *, raw=False)`, `start(id)`, `stop(id)`, `restart(id)`, `logs(id)`, `metrics(id)`, `realtime(id)`, `domains()`, `load_balancers()`, `commit(id, file, *, path=None, filename=None)` |
|
|
149
|
+
| `apps.deploys` | `set_webhook(id, access_token)`, `link_github_app(id, repository, branch)`, `unlink_github_app(id)`, `list(id)`, `current(id)` |
|
|
150
|
+
| `apps.envs` | `get(id)`, `set(id, envs)`, `replace(id, envs)`, `delete(id, keys)` |
|
|
151
|
+
| `apps.files` | `list(id, path=None)`, `read(id, path)` → `bytes`, `write(id, path, content)`, `move(id, path, to)`, `delete(id, path)` |
|
|
152
|
+
| `apps.snapshots` | `list(id)`, `create(id)`, `restore(id, name, version_id)` |
|
|
153
|
+
| `apps.network` | `analytics(id, start, end, **filters)`, `errors(id, start, end, *, include_4xx=False)`, `logs(id, start, end)`, `performance(id, start, end)`, `dns(id)`, `set_domain(id, domain)`, `purge_cache(id)` |
|
|
154
|
+
| `databases` | `create(name, *, type, version, memory)`, `get(id)`, `update(id, *, name=None, ram=None)`, `delete(id)`, `start(id)`, `stop(id)`, `status(id, *, raw=False)`, `metrics(id)`, `status_all()`, `certificate(id)`, `reset_credentials(id, 'password' \| 'certificate')` → the new password, or `''` |
|
|
155
|
+
| `databases.snapshots` | `list(id)`, `create(id)`, `restore(id, name, version_id)` |
|
|
156
|
+
| `workspaces` | `create(name)`, `list()`, `get(id)`, `delete(id)`, `leave(id)` |
|
|
157
|
+
| `workspaces.members` | `add(workspace_id, code, group)`, `update(workspace_id, member_id, group)`, `remove(workspace_id, member_id)`, `invite_code()` |
|
|
158
|
+
| `workspaces.apps` | `add(workspace_id, app_id)`, `remove(workspace_id, app_id)` |
|
|
159
|
+
| client | `download_snapshot(url, dest)`, `close()` |
|
|
160
|
+
|
|
161
|
+
`AsyncSquareCloud` has the same groups and methods, each returning a coroutine (it runs the sync call in `asyncio.to_thread`), except `close()`, which is sync, and `apps.realtime(id)`, which returns an `AsyncRealtime` to use with `async for`. Field names are the API's own (`created_at`, `content_type`, `include_4xx`...), so the [API reference](https://docs.squarecloud.app/api-reference) applies as-is. Responses are `TypedDict`s from `squarecloud.types`: plain dicts, so fields the API adds later are kept. A string result is never `None` (`''` when the API sends nothing). `start`/`end` take an ISO 8601 string (sent as is) or a `datetime` (sent as UTC; a naive `datetime` is local time). The `analytics` filters are keyword-only: `country`, `ip`, `path`, `status`, `os`, `browser`, `protocol`, `referer`, `provider`, `content_type`, `bot`. `provider` takes the `'NAME (ASN)'` form the `providers` buckets report (`provider='GOOGLE (15169)'`); an invalid filter is 400 `INVALID_FILTER`. `metrics()` returns up to 24 h of 5-minute points, newest first. `status()` formats `cpu` and `ram` as strings (`'120.4MB'`); with `raw=True` they are numbers. Empty, `.` and `..` ids are rejected with `INVALID_ID` before sending, because they would reach another route. `apps.network.analytics`, `errors` and `performance` return `None` for a window with no traffic.
|
|
162
|
+
|
|
163
|
+
## Usage
|
|
164
|
+
|
|
165
|
+
### Uploads
|
|
166
|
+
|
|
167
|
+
`apps.create` and `apps.commit` take a path, `bytes` or a binary file object, and stream it: a path or a seekable file is never loaded into memory. A commit unpacks a `.zip` at `path` (the app root by default); any other file lands at `path/<filename>`. The filename is `filename=`, else the file's own name, else `app.zip` on create and `commit.zip` on commit. A zip over 100 MB fails locally with `FILE_TOO_LARGE` before anything is sent. Uploads have no timeout.
|
|
168
|
+
|
|
169
|
+
```python
|
|
170
|
+
created = client.apps.create('bot.zip')
|
|
171
|
+
client.apps.commit(created['id'], 'patch.zip', path='/src')
|
|
172
|
+
client.apps.commit(created['id'], b'print(1)', path='/src', filename='main.py')
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
### Files
|
|
176
|
+
|
|
177
|
+
```python
|
|
178
|
+
client.apps.files.write(app_id, '/config.json', '{"debug": false}') # str or bytes
|
|
179
|
+
data: bytes = client.apps.files.read(app_id, '/config.json')
|
|
180
|
+
client.apps.files.move(app_id, '/config.json', '/config.old.json')
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
A `str` travels as text; `bytes` travel base64-encoded (binary-safe, about 1.33x on the wire). Empty content (`''` or `b''`) creates an empty file. Content over 10 MB fails locally with `FILE_TOO_LARGE`, and content over 1 MiB is sent without a timeout, like an upload; invalid content is 400 `INVALID_CONTENT`. `read` always asks for base64 and returns the decoded `bytes` (at most 10 MB, else 413 `FILE_TOO_LARGE`). `list` of a missing directory is 404 `FILE_NOT_FOUND`, and a blocked path is 403 `BLOCKED_PATH`. Paths are at most 256 characters.
|
|
184
|
+
|
|
185
|
+
### Snapshots
|
|
186
|
+
|
|
187
|
+
`create` returns `{'pending': True}` while the API is still generating the snapshot (HTTP 202 `SNAPSHOT_PROCESSING`). It then appears in `list` on its own, usually within 2 minutes: poll `list`, and never call `create` again, which is limited to one per 180 seconds and counts against the plan's daily snapshot quota.
|
|
188
|
+
|
|
189
|
+
```python
|
|
190
|
+
snapshot = client.apps.snapshots.create(app_id)
|
|
191
|
+
if not snapshot['pending']:
|
|
192
|
+
client.download_snapshot(snapshot['url'], 'backups/') # -> backups/<name>.zip
|
|
193
|
+
|
|
194
|
+
latest = max(client.apps.snapshots.list(app_id), key=lambda s: s['modified'])
|
|
195
|
+
client.apps.snapshots.restore(app_id, latest['name'], latest['version_id'])
|
|
196
|
+
client.download_snapshot(latest['url'], 'backups/')
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
Each listed item carries the API's `version_id` (what `restore` needs) and a signed download `url`, passed through as sent. `download_snapshot` never sends the API key to the snapshot host, streams to a `.part` file next to the target and renames it when complete, and bounds each read with `timeout`.
|
|
200
|
+
|
|
201
|
+
### Realtime
|
|
202
|
+
|
|
203
|
+
```python
|
|
204
|
+
with client.apps.realtime(app_id) as stream:
|
|
205
|
+
for event in stream:
|
|
206
|
+
if event['event'] == 'logs':
|
|
207
|
+
print(event['stream'], event['line']) # stdout | stderr
|
|
208
|
+
elif event['event'] == 'status':
|
|
209
|
+
print(event['status'].get('cpu')) # always the full, merged state
|
|
210
|
+
else: # 'system' or 'error'
|
|
211
|
+
print(event['data']) # a code such as REALTIME_DISCONNECTED
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
Every event has `event`, `data` (the raw frame text) and `id`. The HTTP status is checked before streaming, so 429 `REALTIME_MAX_CONNECTIONS` raises. A dropped connection, or the API's `REALTIME_RECONNECT` hand-off, reopens up to 3 times in a row (a `logs` or `status` event resets the count), at most one open per 5.5 s to stay under the API's pace of one per 5 s; past that it raises `NETWORK_ERROR`. The open is timed until the response headers arrive; the stream itself is not. The loop ends on a clean close (10-minute server limit), on `REALTIME_DISCONNECTED`, or on `stream.close()` (safe from any thread, also mid-wait). With `AsyncSquareCloud`: `async with client.apps.realtime(app_id) as stream: async for event in stream: ...`. Max 5 concurrent streams per account and 30 per app.
|
|
215
|
+
|
|
216
|
+
### GitHub deploys
|
|
217
|
+
|
|
218
|
+
```python
|
|
219
|
+
# A GitHub webhook: returns its URL ('' when removed with '@')
|
|
220
|
+
url = client.apps.deploys.set_webhook(app_id, 'ghp_xxx')
|
|
221
|
+
|
|
222
|
+
# Or the Square Cloud GitHub App
|
|
223
|
+
repo = client.apps.deploys.link_github_app(app_id, 'octocat/hello-world', 'main')
|
|
224
|
+
print(repo['id'], repo['full_name'], repo['branch'])
|
|
225
|
+
|
|
226
|
+
current = client.apps.deploys.current(app_id) # {} when nothing is set
|
|
227
|
+
client.apps.deploys.unlink_github_app(app_id)
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
Linking needs scope `apps:deploy` and a GitHub App installation on your account (403 `GITHUB_NOT_CONNECTED` otherwise). The repository must belong to a GitHub App installation your connected GitHub account holds (403 `REPOSITORY_NOT_AVAILABLE` otherwise), and that account needs write access to it (403 `REPOSITORY_PERMISSION_REQUIRED`). 502 `FAILED_TO_FETCH` means GitHub did not confirm the branch; it is safe to retry. A repository and branch can be linked to one app across all accounts (409 `REPOSITORY_BRANCH_ALREADY_CONFIGURED`; the other app's id appears only in `message`, and only when that app is yours). Re-linking needs an unlink first (400 `GIT_ALREADY_CONFIGURED`), and unlinking without a link is 400 `GIT_NOT_CONFIGURED`. Link and unlink share a limit of 3 calls per 60 s.
|
|
231
|
+
|
|
232
|
+
## Errors
|
|
233
|
+
|
|
234
|
+
Every API and network failure raises `SquareCloudAPIError` with `status`, `code`, `message`, `method`, `path` (`'/v2/apps/...'`, never the query string) and `cause`. Local file problems, such as a missing upload path or an unwritable download destination, raise `OSError`.
|
|
235
|
+
|
|
236
|
+
```python
|
|
237
|
+
from squarecloud import SquareCloudAPIError
|
|
238
|
+
|
|
239
|
+
try:
|
|
240
|
+
client.apps.start(app_id)
|
|
241
|
+
except SquareCloudAPIError as e:
|
|
242
|
+
print(e) # POST /v2/apps/<id>/start: HTTP 404 APP_NOT_FOUND
|
|
243
|
+
if e.code == 'MISSING_SCOPE':
|
|
244
|
+
...
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
- No response: `status` `0` with `code` `NETWORK_ERROR` (original exception in `cause`) or `TIMEOUT`.
|
|
248
|
+
- Local checks, nothing sent: `status` `0` with `FILE_TOO_LARGE`, or `INVALID_ID` for an id that is empty, `.` or `..`.
|
|
249
|
+
- `message` is the server's explanation, or `''` when it sent only a code. A body without a code (a proxy page, a failed snapshot download) is `UNKNOWN_ERROR`, with the server's message when it sent one and `HTTP <status>` otherwise; a 2xx body that is not JSON is `UNKNOWN_ERROR` with `Invalid JSON in HTTP <status> response`.
|
|
250
|
+
- Start, stop and restart refusals are 409 with only a code (`message` is `''`): `CONTAINER_ALREADY_STARTED`, `CONTAINER_ALREADY_STOPPED`, `CONTAINER_TEMPORARILY_SUSPENDED` (apps), `CONTAINER_NOT_FOUND`, `CONTAINER_INSUFFICIENT_DISK_SPACE`, `CONTAINER_NETWORK_CONFLICT` or `ACTION_FAILED`. They are errors: check `e.code` if an already started or stopped resource is fine for you. A 2xx reply whose body is `{"status": "error"}` also raises; a 202 `SNAPSHOT_PROCESSING` stays `{'pending': True}`.
|
|
251
|
+
- `ai.chat()` errors, auth, 429 and 503 included, carry the OpenAI error's lowercase `code` (`access_denied`, `upgrade_required`, `rate_limit_exceeded`, `server_overloaded`, `database_unavailable`, ...), or its `type` when there is no code.
|
|
252
|
+
- The `SquareCloudAPIError` docstring lists every known API code. The list grows: treat an unknown code as a generic failure of its HTTP status.
|
|
253
|
+
- `str(e)` is `<METHOD> <path>: HTTP <status> <CODE>: <message>`, without `HTTP <status>` when the status is `0` and without `: <message>` when it is empty.
|
|
254
|
+
|
|
255
|
+
## Retries, timeouts and rate limits
|
|
256
|
+
|
|
257
|
+
- **Timeouts:** `timeout` (30 s) applies per socket operation. Calls the server holds open wait at least 120 s (`start`/`stop`/`restart` of apps and databases, `databases.create`, snapshot `create`/`restore`), and so does `ai.chat()`, whose gateway has one 90 s deadline for the whole request and answers 503 `server_overloaded` past it; a larger `timeout` wins. `timeout <= 0` disables every timeout, floors included. Uploads and `files.write` above 1 MiB have no timeout; `realtime()` is timed only until it opens.
|
|
258
|
+
- **Retries:** the SDK retries only what is safe: network errors on `GET` (including a body cut off mid-read, realtime opens and `download_snapshot()` before the response), and 503 `UPLOAD_BUSY`/`ANALYTICS_BUSY` (plus `DATABASE_UNAVAILABLE` on `GET`), up to `max_retries` (2) times with exponential backoff (500 ms·2ⁿ, jitter, max 8 s). Timeouts, 429 and the AI's 503 `server_overloaded` (safe for you to retry) are never retried. `DATABASE_UNAVAILABLE` is not retried on other methods because it can fire after a mutation was applied; retrying an idempotent one (a `files.write`, an `envs.replace`, a `stop`) is up to you.
|
|
259
|
+
- **Rate limits:** every account has a global limit of requests per 60 s, set by its plan ([values](https://docs.squarecloud.app/en/api-reference/limitations-and-restrictions)). Going over it, or over a route's own limit, returns 429 `RATE_LIMITED` or `KEEP_CALM`. `RATE_LIMITED` can block the account, API key or IP for about 30 minutes; it is also the limit of the network endpoints and `account.snapshots()`. `RATE_LIMIT` and `RATE_LIMIT_EXCEEDED` are its deprecated names. The API sends no `Retry-After`, which is why the SDK never retries a 429.
|
|
260
|
+
|
|
261
|
+
## Development
|
|
262
|
+
|
|
263
|
+
```bash
|
|
264
|
+
uv sync
|
|
265
|
+
uv run ruff format --check && uv run ruff check && uv run mypy && uv run pytest # offline
|
|
266
|
+
uv build
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
The offline suites (`tests/test_transport.py`, `tests/test_http.py`, `tests/test_streams.py`, `tests/test_conformance.py`) use a mock transport or a loopback server and never reach the API. The live suite runs all 67 operations against the real API:
|
|
270
|
+
|
|
271
|
+
```bash
|
|
272
|
+
SQUARECLOUD_API_KEY=... uv run pytest -m live -s
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
> **Warning:** the live suite creates and deletes real resources (an app, a database and a workspace named `sdk-live-py-<timestamp>`) on the key's account. It is skipped without `SQUARECLOUD_API_KEY` and never runs in CI. Requests are spaced 2.1 s apart; run the JS, Python and Go live suites one after another, never at the same time.
|
|
276
|
+
|
|
277
|
+
## Contributing
|
|
278
|
+
|
|
279
|
+
Issues and pull requests are welcome at [squarecloudofc/sdk-api-py](https://github.com/squarecloudofc/sdk-api-py).
|
|
280
|
+
|
|
281
|
+
## License
|
|
282
|
+
|
|
283
|
+
MIT, see [LICENSE](LICENSE).
|
|
284
|
+
|
|
285
|
+
## Authors
|
|
286
|
+
|
|
287
|
+
Maintained by [Square Cloud](https://squarecloud.app).
|
|
288
|
+
|
|
289
|
+
Contributors:
|
|
290
|
+
|
|
291
|
+
- Robert Nogueira ([@robert-nogueira](https://github.com/robert-nogueira))
|
|
292
|
+
- Jhonatan Jeferson ([@Jhonatan-Jeferson](https://github.com/Jhonatan-Jeferson))
|
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
<div align="center">
|
|
2
|
+
<img alt="Square Cloud Banner" src="https://cdn.squarecloud.app/png/github-readme.png">
|
|
3
|
+
</div>
|
|
4
|
+
|
|
5
|
+
<h1 align="center">squarecloud-api</h1>
|
|
6
|
+
|
|
7
|
+
<p align="center">The official Python SDK for the <a href="https://squarecloud.app" target="_blank">Square Cloud</a> API.</p>
|
|
8
|
+
|
|
9
|
+
<div align="center">
|
|
10
|
+
<a href="https://pypi.org/project/squarecloud-api/"><img alt="PyPI Version" src="https://img.shields.io/pypi/v/squarecloud-api"></a>
|
|
11
|
+
<img alt="License" src="https://img.shields.io/pypi/l/squarecloud-api">
|
|
12
|
+
<img alt="Downloads" src="https://img.shields.io/pypi/dm/squarecloud-api">
|
|
13
|
+
</div>
|
|
14
|
+
|
|
15
|
+
- **Zero runtime dependencies**: only the standard library (`http.client`, `json`, `ssl`), with one keep-alive connection per thread.
|
|
16
|
+
- Runs on **Python 3.11+**, sync (`SquareCloud`) and async (`AsyncSquareCloud`), fully typed (`TypedDict` responses, `py.typed`).
|
|
17
|
+
- Covers all **67 operations** of the Square Cloud API, checked against the pinned OpenAPI spec on every CI run.
|
|
18
|
+
- Uploads and snapshot downloads **stream**; realtime logs and status come as an **iterator** (or `async for`).
|
|
19
|
+
- **One error type**, `SquareCloudAPIError`, for every API, network and local failure.
|
|
20
|
+
|
|
21
|
+
[Documentation](https://docs.squarecloud.app/en/sdks/py/client) · [Releases](https://github.com/squarecloudofc/sdk-api-py/releases) · [Migration guide](MIGRATION.md)
|
|
22
|
+
|
|
23
|
+
## Installation
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
pip install squarecloud-api
|
|
27
|
+
uv add squarecloud-api
|
|
28
|
+
poetry add squarecloud-api
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Requires Python 3.11 or newer.
|
|
32
|
+
|
|
33
|
+
## API key
|
|
34
|
+
|
|
35
|
+
Create one at [squarecloud.app/account/security](https://squarecloud.app/account/security). A key can be limited to scopes (`apps:read`, `apps:deploy`, ...) and to specific apps or databases. A call outside those limits raises `SquareCloudAPIError` with 403 `MISSING_SCOPE` or `RESOURCE_NOT_ALLOWED`, and list endpoints return only the resources the key can see. An unknown, revoked or expired key is 401 `ACCESS_DENIED`.
|
|
36
|
+
|
|
37
|
+
## Quick start
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
import os
|
|
41
|
+
from squarecloud import SquareCloud
|
|
42
|
+
|
|
43
|
+
with SquareCloud(os.environ['SQUARECLOUD_API_KEY']) as client:
|
|
44
|
+
me = client.account.me()
|
|
45
|
+
print(me['user']['name'], [app['name'] for app in me['applications']])
|
|
46
|
+
|
|
47
|
+
app_id = me['applications'][0]['id']
|
|
48
|
+
client.apps.restart(app_id)
|
|
49
|
+
print(client.apps.logs(app_id))
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
The same API with `await`:
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
import asyncio
|
|
56
|
+
import os
|
|
57
|
+
|
|
58
|
+
from squarecloud import AsyncSquareCloud
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
async def main() -> None:
|
|
62
|
+
async with AsyncSquareCloud(os.environ['SQUARECLOUD_API_KEY']) as client:
|
|
63
|
+
statuses = await client.apps.status_all()
|
|
64
|
+
print([s['id'] for s in statuses if s['running']])
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
asyncio.run(main())
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
More in [`examples/`](examples): [apps](examples/apps.py), [realtime](examples/realtime.py), [snapshots](examples/snapshots.py), [databases](examples/databases.py), [workspaces](examples/workspaces.py), [async client](examples/async_client.py).
|
|
71
|
+
|
|
72
|
+
## Configuration
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
import os
|
|
76
|
+
|
|
77
|
+
from squarecloud import BASE_URL, SquareCloud, __version__
|
|
78
|
+
|
|
79
|
+
client = SquareCloud(
|
|
80
|
+
os.environ['SQUARECLOUD_API_KEY'],
|
|
81
|
+
base_url=BASE_URL, # the options are keyword-only; these are the defaults
|
|
82
|
+
timeout=30.0,
|
|
83
|
+
max_retries=2,
|
|
84
|
+
transport=None,
|
|
85
|
+
user_agent=f'squarecloud-sdk-py/{__version__}',
|
|
86
|
+
)
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
| Option | Default | Notes |
|
|
90
|
+
|---|---|---|
|
|
91
|
+
| `api_key` | required | Sent raw in `Authorization`. An empty or whitespace-only key raises `ValueError`. |
|
|
92
|
+
| `base_url` | `BASE_URL` = `https://api.squarecloud.app/v2` | A trailing `/` is stripped. |
|
|
93
|
+
| `timeout` | `30.0` | Seconds per socket operation. `<= 0` disables every timeout, floors included. See [Retries, timeouts and rate limits](#retries-timeouts-and-rate-limits). |
|
|
94
|
+
| `max_retries` | `2` | Negative counts as 0. |
|
|
95
|
+
| `transport` | `HTTPTransport(timeout)` | Plug your own HTTP client (see below). |
|
|
96
|
+
| `user_agent` | `squarecloud-sdk-py/<version>` | Replaces the whole `User-Agent` header. |
|
|
97
|
+
|
|
98
|
+
`AsyncSquareCloud` takes the same arguments. Both clients are thread-safe; call `close()` (or use `with` / `async with`) to close their connections. The version is `squarecloud.__version__`.
|
|
99
|
+
|
|
100
|
+
### Custom transport
|
|
101
|
+
|
|
102
|
+
`transport=` accepts any callable `transport(method, url, headers, body, timeout, stream)` that returns an object with `status`, `read()`, `readline()` and `close()` (an `http.client.HTTPResponse` qualifies). Use it for proxies, tracing or tests. `body` is `bytes`, an iterable of `bytes` chunks (with `Content-Length` already set) or `None`. `timeout` is the per-socket-operation timeout (raised for the held calls), or `None` for uploads, large file writes and the realtime stream, which a custom transport should bound on connect itself. The default `HTTPTransport(timeout)` still bounds their connect, and asks for gzip on every call except the streamed ones (realtime and snapshot downloads).
|
|
103
|
+
|
|
104
|
+
### Logging
|
|
105
|
+
|
|
106
|
+
The SDK logs each request at `DEBUG` on the `squarecloud` logger (method, path and status; never bodies or keys) and attaches only a `NullHandler`:
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
import logging
|
|
110
|
+
|
|
111
|
+
logging.basicConfig()
|
|
112
|
+
logging.getLogger('squarecloud').setLevel(logging.DEBUG)
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
## API
|
|
116
|
+
|
|
117
|
+
Every app id may also be the composite `'<appId>-<workspaceId>'` to act on an app shared with you through a workspace. Optional modifiers are keyword-only.
|
|
118
|
+
|
|
119
|
+
| Group | Methods |
|
|
120
|
+
|---|---|
|
|
121
|
+
| `account` | `me()`, `snapshots(*, scope=None)` |
|
|
122
|
+
| `service` | `status()` (public route: the API does not check the key, but the client still needs a non-empty one) |
|
|
123
|
+
| `ai` | `chat(request)` (OpenAI-compatible, non-streaming) |
|
|
124
|
+
| `apps` | `create(file)`, `get(id)`, `delete(id)`, `status_all(*, workspace_id=None)`, `status(id, *, raw=False)`, `start(id)`, `stop(id)`, `restart(id)`, `logs(id)`, `metrics(id)`, `realtime(id)`, `domains()`, `load_balancers()`, `commit(id, file, *, path=None, filename=None)` |
|
|
125
|
+
| `apps.deploys` | `set_webhook(id, access_token)`, `link_github_app(id, repository, branch)`, `unlink_github_app(id)`, `list(id)`, `current(id)` |
|
|
126
|
+
| `apps.envs` | `get(id)`, `set(id, envs)`, `replace(id, envs)`, `delete(id, keys)` |
|
|
127
|
+
| `apps.files` | `list(id, path=None)`, `read(id, path)` → `bytes`, `write(id, path, content)`, `move(id, path, to)`, `delete(id, path)` |
|
|
128
|
+
| `apps.snapshots` | `list(id)`, `create(id)`, `restore(id, name, version_id)` |
|
|
129
|
+
| `apps.network` | `analytics(id, start, end, **filters)`, `errors(id, start, end, *, include_4xx=False)`, `logs(id, start, end)`, `performance(id, start, end)`, `dns(id)`, `set_domain(id, domain)`, `purge_cache(id)` |
|
|
130
|
+
| `databases` | `create(name, *, type, version, memory)`, `get(id)`, `update(id, *, name=None, ram=None)`, `delete(id)`, `start(id)`, `stop(id)`, `status(id, *, raw=False)`, `metrics(id)`, `status_all()`, `certificate(id)`, `reset_credentials(id, 'password' \| 'certificate')` → the new password, or `''` |
|
|
131
|
+
| `databases.snapshots` | `list(id)`, `create(id)`, `restore(id, name, version_id)` |
|
|
132
|
+
| `workspaces` | `create(name)`, `list()`, `get(id)`, `delete(id)`, `leave(id)` |
|
|
133
|
+
| `workspaces.members` | `add(workspace_id, code, group)`, `update(workspace_id, member_id, group)`, `remove(workspace_id, member_id)`, `invite_code()` |
|
|
134
|
+
| `workspaces.apps` | `add(workspace_id, app_id)`, `remove(workspace_id, app_id)` |
|
|
135
|
+
| client | `download_snapshot(url, dest)`, `close()` |
|
|
136
|
+
|
|
137
|
+
`AsyncSquareCloud` has the same groups and methods, each returning a coroutine (it runs the sync call in `asyncio.to_thread`), except `close()`, which is sync, and `apps.realtime(id)`, which returns an `AsyncRealtime` to use with `async for`. Field names are the API's own (`created_at`, `content_type`, `include_4xx`...), so the [API reference](https://docs.squarecloud.app/api-reference) applies as-is. Responses are `TypedDict`s from `squarecloud.types`: plain dicts, so fields the API adds later are kept. A string result is never `None` (`''` when the API sends nothing). `start`/`end` take an ISO 8601 string (sent as is) or a `datetime` (sent as UTC; a naive `datetime` is local time). The `analytics` filters are keyword-only: `country`, `ip`, `path`, `status`, `os`, `browser`, `protocol`, `referer`, `provider`, `content_type`, `bot`. `provider` takes the `'NAME (ASN)'` form the `providers` buckets report (`provider='GOOGLE (15169)'`); an invalid filter is 400 `INVALID_FILTER`. `metrics()` returns up to 24 h of 5-minute points, newest first. `status()` formats `cpu` and `ram` as strings (`'120.4MB'`); with `raw=True` they are numbers. Empty, `.` and `..` ids are rejected with `INVALID_ID` before sending, because they would reach another route. `apps.network.analytics`, `errors` and `performance` return `None` for a window with no traffic.
|
|
138
|
+
|
|
139
|
+
## Usage
|
|
140
|
+
|
|
141
|
+
### Uploads
|
|
142
|
+
|
|
143
|
+
`apps.create` and `apps.commit` take a path, `bytes` or a binary file object, and stream it: a path or a seekable file is never loaded into memory. A commit unpacks a `.zip` at `path` (the app root by default); any other file lands at `path/<filename>`. The filename is `filename=`, else the file's own name, else `app.zip` on create and `commit.zip` on commit. A zip over 100 MB fails locally with `FILE_TOO_LARGE` before anything is sent. Uploads have no timeout.
|
|
144
|
+
|
|
145
|
+
```python
|
|
146
|
+
created = client.apps.create('bot.zip')
|
|
147
|
+
client.apps.commit(created['id'], 'patch.zip', path='/src')
|
|
148
|
+
client.apps.commit(created['id'], b'print(1)', path='/src', filename='main.py')
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
### Files
|
|
152
|
+
|
|
153
|
+
```python
|
|
154
|
+
client.apps.files.write(app_id, '/config.json', '{"debug": false}') # str or bytes
|
|
155
|
+
data: bytes = client.apps.files.read(app_id, '/config.json')
|
|
156
|
+
client.apps.files.move(app_id, '/config.json', '/config.old.json')
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
A `str` travels as text; `bytes` travel base64-encoded (binary-safe, about 1.33x on the wire). Empty content (`''` or `b''`) creates an empty file. Content over 10 MB fails locally with `FILE_TOO_LARGE`, and content over 1 MiB is sent without a timeout, like an upload; invalid content is 400 `INVALID_CONTENT`. `read` always asks for base64 and returns the decoded `bytes` (at most 10 MB, else 413 `FILE_TOO_LARGE`). `list` of a missing directory is 404 `FILE_NOT_FOUND`, and a blocked path is 403 `BLOCKED_PATH`. Paths are at most 256 characters.
|
|
160
|
+
|
|
161
|
+
### Snapshots
|
|
162
|
+
|
|
163
|
+
`create` returns `{'pending': True}` while the API is still generating the snapshot (HTTP 202 `SNAPSHOT_PROCESSING`). It then appears in `list` on its own, usually within 2 minutes: poll `list`, and never call `create` again, which is limited to one per 180 seconds and counts against the plan's daily snapshot quota.
|
|
164
|
+
|
|
165
|
+
```python
|
|
166
|
+
snapshot = client.apps.snapshots.create(app_id)
|
|
167
|
+
if not snapshot['pending']:
|
|
168
|
+
client.download_snapshot(snapshot['url'], 'backups/') # -> backups/<name>.zip
|
|
169
|
+
|
|
170
|
+
latest = max(client.apps.snapshots.list(app_id), key=lambda s: s['modified'])
|
|
171
|
+
client.apps.snapshots.restore(app_id, latest['name'], latest['version_id'])
|
|
172
|
+
client.download_snapshot(latest['url'], 'backups/')
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
Each listed item carries the API's `version_id` (what `restore` needs) and a signed download `url`, passed through as sent. `download_snapshot` never sends the API key to the snapshot host, streams to a `.part` file next to the target and renames it when complete, and bounds each read with `timeout`.
|
|
176
|
+
|
|
177
|
+
### Realtime
|
|
178
|
+
|
|
179
|
+
```python
|
|
180
|
+
with client.apps.realtime(app_id) as stream:
|
|
181
|
+
for event in stream:
|
|
182
|
+
if event['event'] == 'logs':
|
|
183
|
+
print(event['stream'], event['line']) # stdout | stderr
|
|
184
|
+
elif event['event'] == 'status':
|
|
185
|
+
print(event['status'].get('cpu')) # always the full, merged state
|
|
186
|
+
else: # 'system' or 'error'
|
|
187
|
+
print(event['data']) # a code such as REALTIME_DISCONNECTED
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
Every event has `event`, `data` (the raw frame text) and `id`. The HTTP status is checked before streaming, so 429 `REALTIME_MAX_CONNECTIONS` raises. A dropped connection, or the API's `REALTIME_RECONNECT` hand-off, reopens up to 3 times in a row (a `logs` or `status` event resets the count), at most one open per 5.5 s to stay under the API's pace of one per 5 s; past that it raises `NETWORK_ERROR`. The open is timed until the response headers arrive; the stream itself is not. The loop ends on a clean close (10-minute server limit), on `REALTIME_DISCONNECTED`, or on `stream.close()` (safe from any thread, also mid-wait). With `AsyncSquareCloud`: `async with client.apps.realtime(app_id) as stream: async for event in stream: ...`. Max 5 concurrent streams per account and 30 per app.
|
|
191
|
+
|
|
192
|
+
### GitHub deploys
|
|
193
|
+
|
|
194
|
+
```python
|
|
195
|
+
# A GitHub webhook: returns its URL ('' when removed with '@')
|
|
196
|
+
url = client.apps.deploys.set_webhook(app_id, 'ghp_xxx')
|
|
197
|
+
|
|
198
|
+
# Or the Square Cloud GitHub App
|
|
199
|
+
repo = client.apps.deploys.link_github_app(app_id, 'octocat/hello-world', 'main')
|
|
200
|
+
print(repo['id'], repo['full_name'], repo['branch'])
|
|
201
|
+
|
|
202
|
+
current = client.apps.deploys.current(app_id) # {} when nothing is set
|
|
203
|
+
client.apps.deploys.unlink_github_app(app_id)
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
Linking needs scope `apps:deploy` and a GitHub App installation on your account (403 `GITHUB_NOT_CONNECTED` otherwise). The repository must belong to a GitHub App installation your connected GitHub account holds (403 `REPOSITORY_NOT_AVAILABLE` otherwise), and that account needs write access to it (403 `REPOSITORY_PERMISSION_REQUIRED`). 502 `FAILED_TO_FETCH` means GitHub did not confirm the branch; it is safe to retry. A repository and branch can be linked to one app across all accounts (409 `REPOSITORY_BRANCH_ALREADY_CONFIGURED`; the other app's id appears only in `message`, and only when that app is yours). Re-linking needs an unlink first (400 `GIT_ALREADY_CONFIGURED`), and unlinking without a link is 400 `GIT_NOT_CONFIGURED`. Link and unlink share a limit of 3 calls per 60 s.
|
|
207
|
+
|
|
208
|
+
## Errors
|
|
209
|
+
|
|
210
|
+
Every API and network failure raises `SquareCloudAPIError` with `status`, `code`, `message`, `method`, `path` (`'/v2/apps/...'`, never the query string) and `cause`. Local file problems, such as a missing upload path or an unwritable download destination, raise `OSError`.
|
|
211
|
+
|
|
212
|
+
```python
|
|
213
|
+
from squarecloud import SquareCloudAPIError
|
|
214
|
+
|
|
215
|
+
try:
|
|
216
|
+
client.apps.start(app_id)
|
|
217
|
+
except SquareCloudAPIError as e:
|
|
218
|
+
print(e) # POST /v2/apps/<id>/start: HTTP 404 APP_NOT_FOUND
|
|
219
|
+
if e.code == 'MISSING_SCOPE':
|
|
220
|
+
...
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
- No response: `status` `0` with `code` `NETWORK_ERROR` (original exception in `cause`) or `TIMEOUT`.
|
|
224
|
+
- Local checks, nothing sent: `status` `0` with `FILE_TOO_LARGE`, or `INVALID_ID` for an id that is empty, `.` or `..`.
|
|
225
|
+
- `message` is the server's explanation, or `''` when it sent only a code. A body without a code (a proxy page, a failed snapshot download) is `UNKNOWN_ERROR`, with the server's message when it sent one and `HTTP <status>` otherwise; a 2xx body that is not JSON is `UNKNOWN_ERROR` with `Invalid JSON in HTTP <status> response`.
|
|
226
|
+
- Start, stop and restart refusals are 409 with only a code (`message` is `''`): `CONTAINER_ALREADY_STARTED`, `CONTAINER_ALREADY_STOPPED`, `CONTAINER_TEMPORARILY_SUSPENDED` (apps), `CONTAINER_NOT_FOUND`, `CONTAINER_INSUFFICIENT_DISK_SPACE`, `CONTAINER_NETWORK_CONFLICT` or `ACTION_FAILED`. They are errors: check `e.code` if an already started or stopped resource is fine for you. A 2xx reply whose body is `{"status": "error"}` also raises; a 202 `SNAPSHOT_PROCESSING` stays `{'pending': True}`.
|
|
227
|
+
- `ai.chat()` errors, auth, 429 and 503 included, carry the OpenAI error's lowercase `code` (`access_denied`, `upgrade_required`, `rate_limit_exceeded`, `server_overloaded`, `database_unavailable`, ...), or its `type` when there is no code.
|
|
228
|
+
- The `SquareCloudAPIError` docstring lists every known API code. The list grows: treat an unknown code as a generic failure of its HTTP status.
|
|
229
|
+
- `str(e)` is `<METHOD> <path>: HTTP <status> <CODE>: <message>`, without `HTTP <status>` when the status is `0` and without `: <message>` when it is empty.
|
|
230
|
+
|
|
231
|
+
## Retries, timeouts and rate limits
|
|
232
|
+
|
|
233
|
+
- **Timeouts:** `timeout` (30 s) applies per socket operation. Calls the server holds open wait at least 120 s (`start`/`stop`/`restart` of apps and databases, `databases.create`, snapshot `create`/`restore`), and so does `ai.chat()`, whose gateway has one 90 s deadline for the whole request and answers 503 `server_overloaded` past it; a larger `timeout` wins. `timeout <= 0` disables every timeout, floors included. Uploads and `files.write` above 1 MiB have no timeout; `realtime()` is timed only until it opens.
|
|
234
|
+
- **Retries:** the SDK retries only what is safe: network errors on `GET` (including a body cut off mid-read, realtime opens and `download_snapshot()` before the response), and 503 `UPLOAD_BUSY`/`ANALYTICS_BUSY` (plus `DATABASE_UNAVAILABLE` on `GET`), up to `max_retries` (2) times with exponential backoff (500 ms·2ⁿ, jitter, max 8 s). Timeouts, 429 and the AI's 503 `server_overloaded` (safe for you to retry) are never retried. `DATABASE_UNAVAILABLE` is not retried on other methods because it can fire after a mutation was applied; retrying an idempotent one (a `files.write`, an `envs.replace`, a `stop`) is up to you.
|
|
235
|
+
- **Rate limits:** every account has a global limit of requests per 60 s, set by its plan ([values](https://docs.squarecloud.app/en/api-reference/limitations-and-restrictions)). Going over it, or over a route's own limit, returns 429 `RATE_LIMITED` or `KEEP_CALM`. `RATE_LIMITED` can block the account, API key or IP for about 30 minutes; it is also the limit of the network endpoints and `account.snapshots()`. `RATE_LIMIT` and `RATE_LIMIT_EXCEEDED` are its deprecated names. The API sends no `Retry-After`, which is why the SDK never retries a 429.
|
|
236
|
+
|
|
237
|
+
## Development
|
|
238
|
+
|
|
239
|
+
```bash
|
|
240
|
+
uv sync
|
|
241
|
+
uv run ruff format --check && uv run ruff check && uv run mypy && uv run pytest # offline
|
|
242
|
+
uv build
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
The offline suites (`tests/test_transport.py`, `tests/test_http.py`, `tests/test_streams.py`, `tests/test_conformance.py`) use a mock transport or a loopback server and never reach the API. The live suite runs all 67 operations against the real API:
|
|
246
|
+
|
|
247
|
+
```bash
|
|
248
|
+
SQUARECLOUD_API_KEY=... uv run pytest -m live -s
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
> **Warning:** the live suite creates and deletes real resources (an app, a database and a workspace named `sdk-live-py-<timestamp>`) on the key's account. It is skipped without `SQUARECLOUD_API_KEY` and never runs in CI. Requests are spaced 2.1 s apart; run the JS, Python and Go live suites one after another, never at the same time.
|
|
252
|
+
|
|
253
|
+
## Contributing
|
|
254
|
+
|
|
255
|
+
Issues and pull requests are welcome at [squarecloudofc/sdk-api-py](https://github.com/squarecloudofc/sdk-api-py).
|
|
256
|
+
|
|
257
|
+
## License
|
|
258
|
+
|
|
259
|
+
MIT, see [LICENSE](LICENSE).
|
|
260
|
+
|
|
261
|
+
## Authors
|
|
262
|
+
|
|
263
|
+
Maintained by [Square Cloud](https://squarecloud.app).
|
|
264
|
+
|
|
265
|
+
Contributors:
|
|
266
|
+
|
|
267
|
+
- Robert Nogueira ([@robert-nogueira](https://github.com/robert-nogueira))
|
|
268
|
+
- Jhonatan Jeferson ([@Jhonatan-Jeferson](https://github.com/Jhonatan-Jeferson))
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "squarecloud-api"
|
|
3
|
+
dynamic = ["version"] # from __version__ in src/squarecloud/client.py
|
|
4
|
+
description = "The official Python SDK for the Square Cloud API"
|
|
5
|
+
authors = [{ name = "Square Cloud", email = "support@squarecloud.app" }]
|
|
6
|
+
maintainers = [{ name = "Robert Nogueira", email = "robertlucasnogueira@gmail.com" }]
|
|
7
|
+
license = "MIT"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.11"
|
|
11
|
+
dependencies = []
|
|
12
|
+
keywords = ["squarecloud", "api", "sdk", "hosting"]
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Programming Language :: Python :: 3",
|
|
15
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
16
|
+
"Programming Language :: Python :: 3.11",
|
|
17
|
+
"Programming Language :: Python :: 3.12",
|
|
18
|
+
"Programming Language :: Python :: 3.13",
|
|
19
|
+
"Programming Language :: Python :: 3.14",
|
|
20
|
+
"Operating System :: OS Independent",
|
|
21
|
+
"Typing :: Typed",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
[project.urls]
|
|
25
|
+
Homepage = "https://squarecloud.app"
|
|
26
|
+
Documentation = "https://docs.squarecloud.app/en/sdks/py/client"
|
|
27
|
+
Repository = "https://github.com/squarecloudofc/sdk-api-py"
|
|
28
|
+
Changelog = "https://github.com/squarecloudofc/sdk-api-py/releases"
|
|
29
|
+
|
|
30
|
+
[build-system]
|
|
31
|
+
requires = ["hatchling>=1.27"]
|
|
32
|
+
build-backend = "hatchling.build"
|
|
33
|
+
|
|
34
|
+
[tool.hatch.version]
|
|
35
|
+
path = "src/squarecloud/client.py"
|
|
36
|
+
|
|
37
|
+
[tool.hatch.build.targets.wheel]
|
|
38
|
+
packages = ["src/squarecloud"]
|
|
39
|
+
|
|
40
|
+
[tool.hatch.build.targets.sdist]
|
|
41
|
+
include = ["src/squarecloud", "README.md", "LICENSE"]
|
|
42
|
+
|
|
43
|
+
[dependency-groups]
|
|
44
|
+
dev = ["pytest>=8", "ruff>=0.14", "mypy>=1.18"]
|
|
45
|
+
|
|
46
|
+
[tool.pytest.ini_options]
|
|
47
|
+
testpaths = ["tests"]
|
|
48
|
+
addopts = "-q -m 'not live'"
|
|
49
|
+
faulthandler_timeout = 60 # dumps the stacks of a hung test
|
|
50
|
+
markers = ["live: hits the real API (needs SQUARECLOUD_API_KEY)"]
|
|
51
|
+
|
|
52
|
+
[tool.ruff]
|
|
53
|
+
line-length = 88
|
|
54
|
+
target-version = "py311"
|
|
55
|
+
|
|
56
|
+
[tool.ruff.format]
|
|
57
|
+
quote-style = "single"
|
|
58
|
+
|
|
59
|
+
[tool.ruff.lint]
|
|
60
|
+
select = ["E", "F", "I", "B", "UP", "S", "SIM", "RUF"]
|
|
61
|
+
ignore = ["S101", "S311"] # S311: jitter is not crypto
|
|
62
|
+
|
|
63
|
+
[tool.ruff.lint.per-file-ignores]
|
|
64
|
+
"tests/*" = ["S", "B"]
|
|
65
|
+
|
|
66
|
+
[tool.mypy]
|
|
67
|
+
python_version = "3.11"
|
|
68
|
+
strict = true
|
|
69
|
+
warn_return_any = false
|
|
70
|
+
files = ["src", "tests", "examples"]
|