squarecloud-api 5.0.0__tar.gz → 5.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.
Files changed (25) hide show
  1. squarecloud_api-5.1.0/PKG-INFO +329 -0
  2. squarecloud_api-5.1.0/README.md +305 -0
  3. {squarecloud_api-5.0.0 → squarecloud_api-5.1.0}/src/squarecloud/__init__.py +13 -1
  4. squarecloud_api-5.1.0/src/squarecloud/_group.py +46 -0
  5. squarecloud_api-5.1.0/src/squarecloud/_transport.py +234 -0
  6. squarecloud_api-5.1.0/src/squarecloud/_wire.py +231 -0
  7. squarecloud_api-5.1.0/src/squarecloud/client.py +424 -0
  8. squarecloud_api-5.1.0/src/squarecloud/errors.py +161 -0
  9. squarecloud_api-5.1.0/src/squarecloud/realtime.py +208 -0
  10. squarecloud_api-5.1.0/src/squarecloud/resources/__init__.py +2 -0
  11. squarecloud_api-5.1.0/src/squarecloud/resources/account.py +112 -0
  12. squarecloud_api-5.1.0/src/squarecloud/resources/apps.py +839 -0
  13. squarecloud_api-5.1.0/src/squarecloud/resources/databases.py +248 -0
  14. squarecloud_api-5.1.0/src/squarecloud/resources/snapshots.py +152 -0
  15. squarecloud_api-5.1.0/src/squarecloud/resources/workspaces.py +227 -0
  16. squarecloud_api-5.1.0/src/squarecloud/types.py +618 -0
  17. squarecloud_api-5.0.0/PKG-INFO +0 -292
  18. squarecloud_api-5.0.0/README.md +0 -268
  19. squarecloud_api-5.0.0/src/squarecloud/client.py +0 -1532
  20. squarecloud_api-5.0.0/src/squarecloud/errors.py +0 -112
  21. squarecloud_api-5.0.0/src/squarecloud/types.py +0 -482
  22. {squarecloud_api-5.0.0 → squarecloud_api-5.1.0}/.gitignore +0 -0
  23. {squarecloud_api-5.0.0 → squarecloud_api-5.1.0}/LICENSE +0 -0
  24. {squarecloud_api-5.0.0 → squarecloud_api-5.1.0}/pyproject.toml +0 -0
  25. {squarecloud_api-5.0.0 → squarecloud_api-5.1.0}/src/squarecloud/py.typed +0 -0
@@ -0,0 +1,329 @@
1
+ Metadata-Version: 2.5
2
+ Name: squarecloud-api
3
+ Version: 5.1.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**, and one reused connection per thread.
40
+ - Runs on **Python 3.11+**, with a sync `SquareCloud` client, an async `AsyncSquareCloud` client and typed responses.
41
+ - Covers all **69 operations** of the Square Cloud API, checked against the pinned OpenAPI spec on every CI run.
42
+ - Uploads and snapshot downloads **stream** from and to disk, and realtime logs and status arrive through an **iterator** or `async for`.
43
+ - **One error type**, `SquareCloudAPIError`, for every API error, network failure and failed local check.
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). You can limit a key to scopes, such as `apps:read` or `apps:deploy`, and to specific applications or databases. A call outside those limits raises `SquareCloudAPIError` with 403 `MISSING_SCOPE` or `RESOURCE_NOT_ALLOWED`, and list calls return only the resources the key can see. An unknown, revoked or expired key gets 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 calls 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 as is in `Authorization`. An empty or blank key raises `ValueError`. |
116
+ | `base_url` | `BASE_URL` = `https://api.squarecloud.app/v2` | A trailing `/` is removed. |
117
+ | `timeout` | `30.0` | Seconds each connect, send or read may take. A value of 0 or less disables every timeout, including the 120-second minimum of slow calls. See [Retries, timeouts and rate limits](#retries-timeouts-and-rate-limits). |
118
+ | `max_retries` | `2` | A negative value counts as 0. |
119
+ | `transport` | `HTTPTransport(timeout)` | Your own HTTP transport. See [Custom transport](#custom-transport). |
120
+ | `user_agent` | `squarecloud-sdk-py/<version>` | Replaces the whole `User-Agent` header. |
121
+
122
+ `AsyncSquareCloud` takes the same arguments. Both clients are safe to share between threads. Call `close()`, or use `with` or `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` already has that shape. Use it for proxies, tracing or tests.
127
+
128
+ - `body` is `bytes`, an iterable of `bytes` chunks with `Content-Length` already in `headers`, or `None`.
129
+ - `timeout` is how many seconds each connect, send or read may take, raised to 120 for the calls the API holds open. It is `None` for uploads, large file writes and the realtime feed, so bound their connect yourself.
130
+ - `stream` means the caller reads the body bit by bit and may call `close()` from another thread to stop it.
131
+
132
+ The default `HTTPTransport(timeout)` bounds that connect for you. It asks for compressed responses on every call except the streamed ones, which are the realtime feed and snapshot downloads.
133
+
134
+ ### Logging
135
+
136
+ The SDK logs each request at `DEBUG` on the `squarecloud` logger, with the method, path and status but never a body or a key. It attaches only a `NullHandler`:
137
+
138
+ ```python
139
+ import logging
140
+
141
+ logging.basicConfig()
142
+ logging.getLogger('squarecloud').setLevel(logging.DEBUG)
143
+ ```
144
+
145
+ ## API
146
+
147
+ Every application id can also be the composite `'<appId>-<workspaceId>'`, to act on an application someone shared with you through a workspace. Optional arguments are keyword-only, except the `path` of `apps.files.list`.
148
+
149
+ | Group | Methods |
150
+ |---|---|
151
+ | `account` | `me()`, `snapshots(*, scope=None)` |
152
+ | `service` | `status()`, for which the API does not check the key, although the client still needs a non-empty one |
153
+ | `ai` | `chat(request)`, OpenAI-compatible and without streaming |
154
+ | `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, *, range=None)`, `realtime(id)`, `domains()`, `load_balancers()`, `commit(id, file, *, path=None, filename=None)` |
155
+ | `apps.deploys` | `set_webhook(id, access_token)`, `link_github_app(id, repository, branch)`, `unlink_github_app(id)`, `list(id)`, `current(id)` |
156
+ | `apps.envs` | `get(id)`, `set(id, envs)`, `replace(id, envs)`, `delete(id, keys)` |
157
+ | `apps.files` | `list(id, path=None)`, `read(id, path)` → `bytes`, `write(id, path, content)`, `move(id, path, to)`, `delete(id, path)` |
158
+ | `apps.snapshots` | `list(id)`, `create(id)`, `restore(id, name, version_id)` → `{'pending': bool}`, `restore_state(id)` |
159
+ | `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)` |
160
+ | `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, *, range=None)`, `status_all()`, `certificate(id)`, `reset_credentials(id, 'password' \| 'certificate')` → the new password, or `''` |
161
+ | `databases.snapshots` | `list(id)`, `create(id)`, `restore(id, name, version_id)` → `{'pending': bool}`, `restore_state(id)` |
162
+ | `workspaces` | `create(name)`, `list()`, `get(id)`, `delete(id)`, `leave(id)` |
163
+ | `workspaces.members` | `add(workspace_id, code, group)`, `update(workspace_id, member_id, group)`, `remove(workspace_id, member_id)`, `invite_code()` |
164
+ | `workspaces.apps` | `add(workspace_id, app_id)`, `remove(workspace_id, app_id)` |
165
+ | client | `download_snapshot(url, dest)`, `close()` |
166
+
167
+ `AsyncSquareCloud` has the same groups and methods, and each one returns a coroutine that runs the sync call in a worker thread. The exceptions are `close()`, which is sync, and `apps.realtime(id)`, which returns an `AsyncRealtime` for `async for`.
168
+
169
+ Responses are `TypedDict`s from `squarecloud.types`. They are plain dicts that keep any field the API adds later. Field names are the API's own, such as `created_at`, `content_type` and `include_4xx`, so the [API reference](https://docs.squarecloud.app/api-reference) applies as is. A string result is never `None`. It is `''` when the API sends nothing.
170
+
171
+ - `start` and `end` take an ISO 8601 string, which is sent as is, or a `datetime`, which is sent in UTC. A naive `datetime` is read as local time.
172
+ - The `analytics` filters are keyword-only: `country`, `ip`, `path`, `status`, `os`, `browser`, `protocol`, `referer`, `provider`, `content_type` and `bot`. `provider` takes the `'NAME (ASN)'` form that the `providers` buckets report, such as `provider='GOOGLE (15169)'`. An invalid filter is 400 `INVALID_FILTER`.
173
+ - `apps.network.analytics`, `errors` and `performance` return `None` for a window with no traffic.
174
+ - `metrics()` returns points newest first. By default it covers 24 hours with one point every 5 minutes, or every 10 minutes for applications below 512 MB. `range='7d'` gives hourly points with the hour's peaks in `cpu_max` and `ram_max` on Pro and Enterprise plans, for databases and for applications of 512 MB or more. Other plans and smaller applications get the 24-hour answer without an error, and an unknown `range` is 400 `INVALID_PARAMETERS`. `disk` (bytes read and written, like `net`) and `storage` are `None` on a point without a reading.
175
+ - `status()` formats `cpu` and `ram` as strings such as `'120.4MB'`. With `raw=True` they are numbers.
176
+ - An id that is empty, `.` or `..` fails locally with `INVALID_ID` before anything is sent, because it would address a different resource.
177
+
178
+ ## Usage
179
+
180
+ ### Uploads
181
+
182
+ `apps.create` and `apps.commit` take a path, `bytes` or a binary file object, and stream it, so a path or a seekable file is never loaded into memory. A commit unpacks a `.zip` into `path`, the application 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 file over 100 MB fails locally with `FILE_TOO_LARGE` before anything is sent. Uploads have no timeout.
183
+
184
+ ```python
185
+ created = client.apps.create('bot.zip')
186
+ client.apps.commit(created['id'], 'patch.zip', path='/src')
187
+ client.apps.commit(created['id'], b'print(1)', path='/src', filename='main.py')
188
+ ```
189
+
190
+ ### Files
191
+
192
+ ```python
193
+ client.apps.files.write(app_id, '/config.json', '{"debug": false}') # str or bytes
194
+ data: bytes = client.apps.files.read(app_id, '/config.json')
195
+ client.apps.files.move(app_id, '/config.json', '/config.old.json')
196
+ ```
197
+
198
+ A `str` is sent as text. `bytes` are sent base64-encoded, which keeps binary content intact and takes about 1.33 times the size 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. Content the API cannot decode is 400 `INVALID_CONTENT`. `read` always asks for base64 and returns the decoded `bytes`, and a file over 10 MB is 413 `FILE_TOO_LARGE`. `list` of a missing directory is 404 `FILE_NOT_FOUND`, and a protected path is 403 `BLOCKED_PATH`. Paths are at most 256 characters.
199
+
200
+ ### Snapshots
201
+
202
+ `create` returns `{'pending': True}` while the API is still generating the snapshot, which it signals with HTTP 202 `SNAPSHOT_PROCESSING`. The snapshot then appears in `list` on its own, usually within 2 minutes. Poll `list` and do not call `create` again, because it allows one call every 180 seconds and each call counts against your plan's daily snapshot quota. An API key without `snapshots:read` gets `{'pending': False}` with `url` and `key` set to `''`.
203
+
204
+ `restore` returns `{'pending': True}` when the restore is not done after about 90 seconds, which the API signals with HTTP 202 `SNAPSHOT_RESTORE_PROCESSING`. The restore keeps running in the background. Follow it with `restore_state` and do not call `restore` again. `restore_state` reports `queued` or `running` with the current `step`, then `success`, or `error` with a `code`, for 1 hour after the restore ends, and `none` when there is no recent restore. It allows 30 calls per minute.
205
+
206
+ ```python
207
+ import time
208
+
209
+ snapshot = client.apps.snapshots.create(app_id)
210
+ if not snapshot['pending']:
211
+ client.download_snapshot(snapshot['url'], 'backups/') # -> backups/<name>.zip
212
+
213
+ latest = max(client.apps.snapshots.list(app_id), key=lambda s: s['modified'])
214
+ client.download_snapshot(latest['url'], 'backups/')
215
+
216
+ restored = client.apps.snapshots.restore(app_id, latest['name'], latest['version_id'])
217
+ if restored['pending']:
218
+ state = client.apps.snapshots.restore_state(app_id)
219
+ while state['state'] in ('queued', 'running'):
220
+ time.sleep(5)
221
+ state = client.apps.snapshots.restore_state(app_id)
222
+ print(state['state'], state.get('code', '')) # success, or error with a code
223
+ ```
224
+
225
+ Each listed snapshot carries the API's `version_id`, which `restore` needs, and a signed download `url`, both passed through as sent. The `url` from `list` and `create` is valid for 1 hour. When snapshot storage cannot answer, a listing fails with 503 `SNAPSHOTS_UNAVAILABLE`, so try again in about 30 seconds.
226
+
227
+ A restore can fail with 400 `MISSING_PARAMETERS`, `INVALID_SNAPSHOT_ID` or `INVALID_VERSION_ID`, and on databases also with `SNAPSHOT_DATABASE_MISMATCH`. It can fail with 404 `APP_NOT_FOUND`, `DATABASE_NOT_FOUND`, `SNAPSHOT_NOT_FOUND`, `SNAPSHOT_RESTORE_FAILED`, `SNAPSHOT_CORRUPT`, `RESTORE_INTERRUPTED` or `CONTAINER_NOT_FOUND`, with 409 `RESTORE_IN_PROGRESS` or `SNAPSHOT_IN_PROGRESS`, with 413 `PAYLOAD_TOO_LARGE`, and with 503 `CLUSTER_MAINTENANCE_TRY_LATER`, which snapshot `create` can return too.
228
+
229
+ `download_snapshot` never sends your API key with the download. It streams to a `.part` file next to the target and renames it once complete, and each read waits at most `timeout`.
230
+
231
+ ### Realtime
232
+
233
+ ```python
234
+ with client.apps.realtime(app_id) as stream:
235
+ for event in stream:
236
+ if event['event'] == 'logs':
237
+ print(event['stream'], event['line']) # stdout | stderr
238
+ elif event['event'] == 'status':
239
+ print(event['status'].get('cpu')) # always the full, merged state
240
+ else: # 'system' or 'error'
241
+ print(event['data']) # a code such as REALTIME_DISCONNECTED
242
+ ```
243
+
244
+ Every event has `event`, `data` (the raw text of the event) and `id`. The HTTP status is checked before any event, so 429 `REALTIME_MAX_CONNECTIONS` raises right away. If the connection drops, or the API hands the feed over with `REALTIME_RECONNECT`, the feed reopens on its own up to 3 times in a row, and a `logs` or `status` event resets that count. It opens at most once every 5.5 seconds, to stay under the API's limit of one open every 5 seconds. Past 3 reopens it raises `NETWORK_ERROR`.
245
+
246
+ The client's `timeout` applies only until the feed opens. The loop ends when the API closes the feed after its 10-minute limit, on `REALTIME_DISCONNECTED`, or when you call `stream.close()`, which is safe from any thread and also stops a wait. With `AsyncSquareCloud`, use `async with client.apps.realtime(app_id) as stream:` and `async for event in stream:`. Each account can have up to 5 open feeds, and each application up to 30.
247
+
248
+ ### GitHub deploys
249
+
250
+ ```python
251
+ # A GitHub webhook: returns its URL ('' when removed with '@')
252
+ url = client.apps.deploys.set_webhook(app_id, 'ghp_xxx')
253
+
254
+ # Or the Square Cloud GitHub App
255
+ repo = client.apps.deploys.link_github_app(app_id, 'octocat/hello-world', 'main')
256
+ print(repo['id'], repo['full_name'], repo['branch'])
257
+
258
+ current = client.apps.deploys.current(app_id) # {} when nothing is set
259
+ client.apps.deploys.unlink_github_app(app_id)
260
+ ```
261
+
262
+ Linking needs the `apps:deploy` scope and a GitHub App installation on your account, or it fails with 403 `GITHUB_NOT_CONNECTED`. The repository must belong to a GitHub App installation that your connected GitHub account holds, or it fails with 403 `REPOSITORY_NOT_AVAILABLE`. That account also needs write access to the repository, or it fails with 403 `REPOSITORY_PERMISSION_REQUIRED`. 502 `FAILED_TO_FETCH` means GitHub did not confirm the branch, and it is safe to try again.
263
+
264
+ A repository and branch can be linked to only one application across all accounts. Another link fails with 409 `REPOSITORY_BRANCH_ALREADY_CONFIGURED`, and the other application's id appears in `message` only when that application is yours. To link again, unlink first, or the call fails with 400 `GIT_ALREADY_CONFIGURED`. Unlinking without a link fails with 400 `GIT_NOT_CONFIGURED`. Link and unlink share a limit of 3 calls per minute.
265
+
266
+ ## Errors
267
+
268
+ Every API and network failure raises `SquareCloudAPIError` with `status`, `code`, `message`, `method`, `path` and `cause`. The `path` looks like `'/v2/apps/...'` and never includes the query string. Local file problems, such as a missing upload path or a download destination you cannot write to, raise `OSError`.
269
+
270
+ ```python
271
+ from squarecloud import SquareCloudAPIError
272
+
273
+ try:
274
+ client.apps.start(app_id)
275
+ except SquareCloudAPIError as e:
276
+ print(e) # POST /v2/apps/<id>/start: HTTP 404 APP_NOT_FOUND
277
+ if e.code == 'MISSING_SCOPE':
278
+ ...
279
+ ```
280
+
281
+ - When no response arrives, `status` is `0` and `code` is `NETWORK_ERROR`, with the original exception in `cause`, or `TIMEOUT`.
282
+ - When a local check stops the call before anything is sent, `status` is `0` and `code` is `FILE_TOO_LARGE`, or `INVALID_ID` for an id that is empty, `.` or `..`.
283
+ - `message` is the server's explanation, or `''` when it sent only a code. A body without a code, such as a proxy page or a failed snapshot download, gives `UNKNOWN_ERROR` with the server's message when it sent one and `HTTP <status>` otherwise. A successful response whose body is not JSON gives `UNKNOWN_ERROR` with `Invalid JSON in HTTP <status> response`.
284
+ - A refused start, stop or restart is a 409 with only a code, so `message` is `''`. The code is `CONTAINER_ALREADY_STARTED`, `CONTAINER_ALREADY_STOPPED`, `CONTAINER_TEMPORARILY_SUSPENDED` (applications only), `CONTAINER_NOT_FOUND`, `CONTAINER_INSUFFICIENT_DISK_SPACE`, `CONTAINER_NETWORK_CONFLICT`, `ACTION_FAILED` or `RESTORE_IN_PROGRESS`. These are errors, so check `e.code` when a resource that is already started or stopped is fine for you.
285
+ - 409 `RESTORE_IN_PROGRESS` also answers a delete, start, stop, restart or snapshot `create` while a restore runs. Try again when the restore ends.
286
+ - A successful response whose body is `{"status": "error"}` also raises. The 202 answers `SNAPSHOT_PROCESSING` and `SNAPSHOT_RESTORE_PROCESSING` are not errors and return `{'pending': True}`.
287
+ - Errors from `ai.chat()`, including authentication, 429 and 503, carry the lowercase `code` of the OpenAI format, such as `access_denied`, `upgrade_required`, `rate_limit_exceeded`, `server_overloaded` or `database_unavailable`, or its `type` when there is no code.
288
+ - The `SquareCloudAPIError` docstring lists every known API code. The API can add codes, so treat an unknown code as a generic failure of its HTTP status.
289
+ - `str(e)` is `<METHOD> <path>: HTTP <status> <CODE>: <message>`. The `HTTP <status>` part is left out when the status is `0`, and the `: <message>` part when the message is empty.
290
+
291
+ ## Retries, timeouts and rate limits
292
+
293
+ - **Timeouts.** `timeout`, 30 seconds by default, applies to each connect, send and read. Calls the API holds open wait at least 120 seconds: `start`, `stop` and `restart` of applications and databases, `databases.create`, and snapshot `create` and `restore`. So does `ai.chat()`, which answers within 90 seconds or fails with 503 `server_overloaded`. A larger `timeout` wins, and a `timeout` of 0 or less disables every timeout, including that minimum. Uploads and `files.write` calls over 1 MiB have no timeout, and `realtime()` is timed only until it opens.
294
+ - **Retries.** The SDK retries only what is safe to repeat, up to `max_retries` times, which is 2 by default. It retries network errors on `GET`, including a body cut off mid-read, realtime opens, and `download_snapshot()` before the download starts. It also retries 503 `UPLOAD_BUSY` and `ANALYTICS_BUSY` on any method, and 503 `DATABASE_UNAVAILABLE` on `GET`. Each wait is 500 ms × 2ⁿ, where n counts the retries from 0, capped at 8 seconds and randomly shortened by up to half.
295
+ - **Never retried.** Timeouts, any 429, the AI's 503 `server_overloaded` (safe for you to retry), 503 `SNAPSHOTS_UNAVAILABLE` and `CLUSTER_MAINTENANCE_TRY_LATER`, and 409 `RESTORE_IN_PROGRESS`, `SNAPSHOT_IN_PROGRESS` and `ENV_BUSY`. `ENV_BUSY` means another write to the environment variables is in progress. `DATABASE_UNAVAILABLE` is not retried on other methods because the change may already have been applied, so retrying an idempotent call such as `files.write`, `envs.replace` or `stop` is up to you.
296
+ - **Rate limits.** Every account has a global limit of requests per minute, set by its plan ([values](https://docs.squarecloud.app/en/api-reference/limitations-and-restrictions)). Going over it, or over the limit of a single call, returns 429 `RATE_LIMITED` or `KEEP_CALM`. `RATE_LIMITED` can block the account, API key or IP for about 30 minutes, and it is also the limit of the `apps.network` calls and of `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.
297
+
298
+ ## Development
299
+
300
+ ```bash
301
+ uv sync
302
+ uv run ruff format --check && uv run ruff check && uv run mypy && uv run pytest # offline
303
+ uv build
304
+ ```
305
+
306
+ The offline suites (`tests/test_transport.py`, `tests/test_http.py`, `tests/test_streams.py`, `tests/test_conformance.py`, `tests/test_surface.py`) use a mock transport or a loopback server and never reach the API. The live suite runs all 69 operations against the real API:
307
+
308
+ ```bash
309
+ SQUARECLOUD_API_KEY=... uv run pytest -m live -s
310
+ ```
311
+
312
+ > **Warning:** the live suite creates and deletes real resources on the key's account: an application, a database and a workspace named `sdk-live-py-<timestamp>`. It is skipped without `SQUARECLOUD_API_KEY` and never runs in CI. Requests are spaced 2.1 seconds apart. Run the JS, Python and Go live suites one after another, never at the same time.
313
+
314
+ ## Contributing
315
+
316
+ Issues and pull requests are welcome at [squarecloudofc/sdk-api-py](https://github.com/squarecloudofc/sdk-api-py).
317
+
318
+ ## License
319
+
320
+ MIT, see [LICENSE](LICENSE).
321
+
322
+ ## Authors
323
+
324
+ Maintained by [Square Cloud](https://squarecloud.app).
325
+
326
+ Contributors:
327
+
328
+ - Robert Nogueira ([@robert-nogueira](https://github.com/robert-nogueira))
329
+ - Jhonatan Jeferson ([@Jhonatan-Jeferson](https://github.com/Jhonatan-Jeferson))
@@ -0,0 +1,305 @@
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**, and one reused connection per thread.
16
+ - Runs on **Python 3.11+**, with a sync `SquareCloud` client, an async `AsyncSquareCloud` client and typed responses.
17
+ - Covers all **69 operations** of the Square Cloud API, checked against the pinned OpenAPI spec on every CI run.
18
+ - Uploads and snapshot downloads **stream** from and to disk, and realtime logs and status arrive through an **iterator** or `async for`.
19
+ - **One error type**, `SquareCloudAPIError`, for every API error, network failure and failed local check.
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). You can limit a key to scopes, such as `apps:read` or `apps:deploy`, and to specific applications or databases. A call outside those limits raises `SquareCloudAPIError` with 403 `MISSING_SCOPE` or `RESOURCE_NOT_ALLOWED`, and list calls return only the resources the key can see. An unknown, revoked or expired key gets 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 calls 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 as is in `Authorization`. An empty or blank key raises `ValueError`. |
92
+ | `base_url` | `BASE_URL` = `https://api.squarecloud.app/v2` | A trailing `/` is removed. |
93
+ | `timeout` | `30.0` | Seconds each connect, send or read may take. A value of 0 or less disables every timeout, including the 120-second minimum of slow calls. See [Retries, timeouts and rate limits](#retries-timeouts-and-rate-limits). |
94
+ | `max_retries` | `2` | A negative value counts as 0. |
95
+ | `transport` | `HTTPTransport(timeout)` | Your own HTTP transport. See [Custom transport](#custom-transport). |
96
+ | `user_agent` | `squarecloud-sdk-py/<version>` | Replaces the whole `User-Agent` header. |
97
+
98
+ `AsyncSquareCloud` takes the same arguments. Both clients are safe to share between threads. Call `close()`, or use `with` or `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` already has that shape. Use it for proxies, tracing or tests.
103
+
104
+ - `body` is `bytes`, an iterable of `bytes` chunks with `Content-Length` already in `headers`, or `None`.
105
+ - `timeout` is how many seconds each connect, send or read may take, raised to 120 for the calls the API holds open. It is `None` for uploads, large file writes and the realtime feed, so bound their connect yourself.
106
+ - `stream` means the caller reads the body bit by bit and may call `close()` from another thread to stop it.
107
+
108
+ The default `HTTPTransport(timeout)` bounds that connect for you. It asks for compressed responses on every call except the streamed ones, which are the realtime feed and snapshot downloads.
109
+
110
+ ### Logging
111
+
112
+ The SDK logs each request at `DEBUG` on the `squarecloud` logger, with the method, path and status but never a body or a key. It attaches only a `NullHandler`:
113
+
114
+ ```python
115
+ import logging
116
+
117
+ logging.basicConfig()
118
+ logging.getLogger('squarecloud').setLevel(logging.DEBUG)
119
+ ```
120
+
121
+ ## API
122
+
123
+ Every application id can also be the composite `'<appId>-<workspaceId>'`, to act on an application someone shared with you through a workspace. Optional arguments are keyword-only, except the `path` of `apps.files.list`.
124
+
125
+ | Group | Methods |
126
+ |---|---|
127
+ | `account` | `me()`, `snapshots(*, scope=None)` |
128
+ | `service` | `status()`, for which the API does not check the key, although the client still needs a non-empty one |
129
+ | `ai` | `chat(request)`, OpenAI-compatible and without streaming |
130
+ | `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, *, range=None)`, `realtime(id)`, `domains()`, `load_balancers()`, `commit(id, file, *, path=None, filename=None)` |
131
+ | `apps.deploys` | `set_webhook(id, access_token)`, `link_github_app(id, repository, branch)`, `unlink_github_app(id)`, `list(id)`, `current(id)` |
132
+ | `apps.envs` | `get(id)`, `set(id, envs)`, `replace(id, envs)`, `delete(id, keys)` |
133
+ | `apps.files` | `list(id, path=None)`, `read(id, path)` → `bytes`, `write(id, path, content)`, `move(id, path, to)`, `delete(id, path)` |
134
+ | `apps.snapshots` | `list(id)`, `create(id)`, `restore(id, name, version_id)` → `{'pending': bool}`, `restore_state(id)` |
135
+ | `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)` |
136
+ | `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, *, range=None)`, `status_all()`, `certificate(id)`, `reset_credentials(id, 'password' \| 'certificate')` → the new password, or `''` |
137
+ | `databases.snapshots` | `list(id)`, `create(id)`, `restore(id, name, version_id)` → `{'pending': bool}`, `restore_state(id)` |
138
+ | `workspaces` | `create(name)`, `list()`, `get(id)`, `delete(id)`, `leave(id)` |
139
+ | `workspaces.members` | `add(workspace_id, code, group)`, `update(workspace_id, member_id, group)`, `remove(workspace_id, member_id)`, `invite_code()` |
140
+ | `workspaces.apps` | `add(workspace_id, app_id)`, `remove(workspace_id, app_id)` |
141
+ | client | `download_snapshot(url, dest)`, `close()` |
142
+
143
+ `AsyncSquareCloud` has the same groups and methods, and each one returns a coroutine that runs the sync call in a worker thread. The exceptions are `close()`, which is sync, and `apps.realtime(id)`, which returns an `AsyncRealtime` for `async for`.
144
+
145
+ Responses are `TypedDict`s from `squarecloud.types`. They are plain dicts that keep any field the API adds later. Field names are the API's own, such as `created_at`, `content_type` and `include_4xx`, so the [API reference](https://docs.squarecloud.app/api-reference) applies as is. A string result is never `None`. It is `''` when the API sends nothing.
146
+
147
+ - `start` and `end` take an ISO 8601 string, which is sent as is, or a `datetime`, which is sent in UTC. A naive `datetime` is read as local time.
148
+ - The `analytics` filters are keyword-only: `country`, `ip`, `path`, `status`, `os`, `browser`, `protocol`, `referer`, `provider`, `content_type` and `bot`. `provider` takes the `'NAME (ASN)'` form that the `providers` buckets report, such as `provider='GOOGLE (15169)'`. An invalid filter is 400 `INVALID_FILTER`.
149
+ - `apps.network.analytics`, `errors` and `performance` return `None` for a window with no traffic.
150
+ - `metrics()` returns points newest first. By default it covers 24 hours with one point every 5 minutes, or every 10 minutes for applications below 512 MB. `range='7d'` gives hourly points with the hour's peaks in `cpu_max` and `ram_max` on Pro and Enterprise plans, for databases and for applications of 512 MB or more. Other plans and smaller applications get the 24-hour answer without an error, and an unknown `range` is 400 `INVALID_PARAMETERS`. `disk` (bytes read and written, like `net`) and `storage` are `None` on a point without a reading.
151
+ - `status()` formats `cpu` and `ram` as strings such as `'120.4MB'`. With `raw=True` they are numbers.
152
+ - An id that is empty, `.` or `..` fails locally with `INVALID_ID` before anything is sent, because it would address a different resource.
153
+
154
+ ## Usage
155
+
156
+ ### Uploads
157
+
158
+ `apps.create` and `apps.commit` take a path, `bytes` or a binary file object, and stream it, so a path or a seekable file is never loaded into memory. A commit unpacks a `.zip` into `path`, the application 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 file over 100 MB fails locally with `FILE_TOO_LARGE` before anything is sent. Uploads have no timeout.
159
+
160
+ ```python
161
+ created = client.apps.create('bot.zip')
162
+ client.apps.commit(created['id'], 'patch.zip', path='/src')
163
+ client.apps.commit(created['id'], b'print(1)', path='/src', filename='main.py')
164
+ ```
165
+
166
+ ### Files
167
+
168
+ ```python
169
+ client.apps.files.write(app_id, '/config.json', '{"debug": false}') # str or bytes
170
+ data: bytes = client.apps.files.read(app_id, '/config.json')
171
+ client.apps.files.move(app_id, '/config.json', '/config.old.json')
172
+ ```
173
+
174
+ A `str` is sent as text. `bytes` are sent base64-encoded, which keeps binary content intact and takes about 1.33 times the size 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. Content the API cannot decode is 400 `INVALID_CONTENT`. `read` always asks for base64 and returns the decoded `bytes`, and a file over 10 MB is 413 `FILE_TOO_LARGE`. `list` of a missing directory is 404 `FILE_NOT_FOUND`, and a protected path is 403 `BLOCKED_PATH`. Paths are at most 256 characters.
175
+
176
+ ### Snapshots
177
+
178
+ `create` returns `{'pending': True}` while the API is still generating the snapshot, which it signals with HTTP 202 `SNAPSHOT_PROCESSING`. The snapshot then appears in `list` on its own, usually within 2 minutes. Poll `list` and do not call `create` again, because it allows one call every 180 seconds and each call counts against your plan's daily snapshot quota. An API key without `snapshots:read` gets `{'pending': False}` with `url` and `key` set to `''`.
179
+
180
+ `restore` returns `{'pending': True}` when the restore is not done after about 90 seconds, which the API signals with HTTP 202 `SNAPSHOT_RESTORE_PROCESSING`. The restore keeps running in the background. Follow it with `restore_state` and do not call `restore` again. `restore_state` reports `queued` or `running` with the current `step`, then `success`, or `error` with a `code`, for 1 hour after the restore ends, and `none` when there is no recent restore. It allows 30 calls per minute.
181
+
182
+ ```python
183
+ import time
184
+
185
+ snapshot = client.apps.snapshots.create(app_id)
186
+ if not snapshot['pending']:
187
+ client.download_snapshot(snapshot['url'], 'backups/') # -> backups/<name>.zip
188
+
189
+ latest = max(client.apps.snapshots.list(app_id), key=lambda s: s['modified'])
190
+ client.download_snapshot(latest['url'], 'backups/')
191
+
192
+ restored = client.apps.snapshots.restore(app_id, latest['name'], latest['version_id'])
193
+ if restored['pending']:
194
+ state = client.apps.snapshots.restore_state(app_id)
195
+ while state['state'] in ('queued', 'running'):
196
+ time.sleep(5)
197
+ state = client.apps.snapshots.restore_state(app_id)
198
+ print(state['state'], state.get('code', '')) # success, or error with a code
199
+ ```
200
+
201
+ Each listed snapshot carries the API's `version_id`, which `restore` needs, and a signed download `url`, both passed through as sent. The `url` from `list` and `create` is valid for 1 hour. When snapshot storage cannot answer, a listing fails with 503 `SNAPSHOTS_UNAVAILABLE`, so try again in about 30 seconds.
202
+
203
+ A restore can fail with 400 `MISSING_PARAMETERS`, `INVALID_SNAPSHOT_ID` or `INVALID_VERSION_ID`, and on databases also with `SNAPSHOT_DATABASE_MISMATCH`. It can fail with 404 `APP_NOT_FOUND`, `DATABASE_NOT_FOUND`, `SNAPSHOT_NOT_FOUND`, `SNAPSHOT_RESTORE_FAILED`, `SNAPSHOT_CORRUPT`, `RESTORE_INTERRUPTED` or `CONTAINER_NOT_FOUND`, with 409 `RESTORE_IN_PROGRESS` or `SNAPSHOT_IN_PROGRESS`, with 413 `PAYLOAD_TOO_LARGE`, and with 503 `CLUSTER_MAINTENANCE_TRY_LATER`, which snapshot `create` can return too.
204
+
205
+ `download_snapshot` never sends your API key with the download. It streams to a `.part` file next to the target and renames it once complete, and each read waits at most `timeout`.
206
+
207
+ ### Realtime
208
+
209
+ ```python
210
+ with client.apps.realtime(app_id) as stream:
211
+ for event in stream:
212
+ if event['event'] == 'logs':
213
+ print(event['stream'], event['line']) # stdout | stderr
214
+ elif event['event'] == 'status':
215
+ print(event['status'].get('cpu')) # always the full, merged state
216
+ else: # 'system' or 'error'
217
+ print(event['data']) # a code such as REALTIME_DISCONNECTED
218
+ ```
219
+
220
+ Every event has `event`, `data` (the raw text of the event) and `id`. The HTTP status is checked before any event, so 429 `REALTIME_MAX_CONNECTIONS` raises right away. If the connection drops, or the API hands the feed over with `REALTIME_RECONNECT`, the feed reopens on its own up to 3 times in a row, and a `logs` or `status` event resets that count. It opens at most once every 5.5 seconds, to stay under the API's limit of one open every 5 seconds. Past 3 reopens it raises `NETWORK_ERROR`.
221
+
222
+ The client's `timeout` applies only until the feed opens. The loop ends when the API closes the feed after its 10-minute limit, on `REALTIME_DISCONNECTED`, or when you call `stream.close()`, which is safe from any thread and also stops a wait. With `AsyncSquareCloud`, use `async with client.apps.realtime(app_id) as stream:` and `async for event in stream:`. Each account can have up to 5 open feeds, and each application up to 30.
223
+
224
+ ### GitHub deploys
225
+
226
+ ```python
227
+ # A GitHub webhook: returns its URL ('' when removed with '@')
228
+ url = client.apps.deploys.set_webhook(app_id, 'ghp_xxx')
229
+
230
+ # Or the Square Cloud GitHub App
231
+ repo = client.apps.deploys.link_github_app(app_id, 'octocat/hello-world', 'main')
232
+ print(repo['id'], repo['full_name'], repo['branch'])
233
+
234
+ current = client.apps.deploys.current(app_id) # {} when nothing is set
235
+ client.apps.deploys.unlink_github_app(app_id)
236
+ ```
237
+
238
+ Linking needs the `apps:deploy` scope and a GitHub App installation on your account, or it fails with 403 `GITHUB_NOT_CONNECTED`. The repository must belong to a GitHub App installation that your connected GitHub account holds, or it fails with 403 `REPOSITORY_NOT_AVAILABLE`. That account also needs write access to the repository, or it fails with 403 `REPOSITORY_PERMISSION_REQUIRED`. 502 `FAILED_TO_FETCH` means GitHub did not confirm the branch, and it is safe to try again.
239
+
240
+ A repository and branch can be linked to only one application across all accounts. Another link fails with 409 `REPOSITORY_BRANCH_ALREADY_CONFIGURED`, and the other application's id appears in `message` only when that application is yours. To link again, unlink first, or the call fails with 400 `GIT_ALREADY_CONFIGURED`. Unlinking without a link fails with 400 `GIT_NOT_CONFIGURED`. Link and unlink share a limit of 3 calls per minute.
241
+
242
+ ## Errors
243
+
244
+ Every API and network failure raises `SquareCloudAPIError` with `status`, `code`, `message`, `method`, `path` and `cause`. The `path` looks like `'/v2/apps/...'` and never includes the query string. Local file problems, such as a missing upload path or a download destination you cannot write to, raise `OSError`.
245
+
246
+ ```python
247
+ from squarecloud import SquareCloudAPIError
248
+
249
+ try:
250
+ client.apps.start(app_id)
251
+ except SquareCloudAPIError as e:
252
+ print(e) # POST /v2/apps/<id>/start: HTTP 404 APP_NOT_FOUND
253
+ if e.code == 'MISSING_SCOPE':
254
+ ...
255
+ ```
256
+
257
+ - When no response arrives, `status` is `0` and `code` is `NETWORK_ERROR`, with the original exception in `cause`, or `TIMEOUT`.
258
+ - When a local check stops the call before anything is sent, `status` is `0` and `code` is `FILE_TOO_LARGE`, or `INVALID_ID` for an id that is empty, `.` or `..`.
259
+ - `message` is the server's explanation, or `''` when it sent only a code. A body without a code, such as a proxy page or a failed snapshot download, gives `UNKNOWN_ERROR` with the server's message when it sent one and `HTTP <status>` otherwise. A successful response whose body is not JSON gives `UNKNOWN_ERROR` with `Invalid JSON in HTTP <status> response`.
260
+ - A refused start, stop or restart is a 409 with only a code, so `message` is `''`. The code is `CONTAINER_ALREADY_STARTED`, `CONTAINER_ALREADY_STOPPED`, `CONTAINER_TEMPORARILY_SUSPENDED` (applications only), `CONTAINER_NOT_FOUND`, `CONTAINER_INSUFFICIENT_DISK_SPACE`, `CONTAINER_NETWORK_CONFLICT`, `ACTION_FAILED` or `RESTORE_IN_PROGRESS`. These are errors, so check `e.code` when a resource that is already started or stopped is fine for you.
261
+ - 409 `RESTORE_IN_PROGRESS` also answers a delete, start, stop, restart or snapshot `create` while a restore runs. Try again when the restore ends.
262
+ - A successful response whose body is `{"status": "error"}` also raises. The 202 answers `SNAPSHOT_PROCESSING` and `SNAPSHOT_RESTORE_PROCESSING` are not errors and return `{'pending': True}`.
263
+ - Errors from `ai.chat()`, including authentication, 429 and 503, carry the lowercase `code` of the OpenAI format, such as `access_denied`, `upgrade_required`, `rate_limit_exceeded`, `server_overloaded` or `database_unavailable`, or its `type` when there is no code.
264
+ - The `SquareCloudAPIError` docstring lists every known API code. The API can add codes, so treat an unknown code as a generic failure of its HTTP status.
265
+ - `str(e)` is `<METHOD> <path>: HTTP <status> <CODE>: <message>`. The `HTTP <status>` part is left out when the status is `0`, and the `: <message>` part when the message is empty.
266
+
267
+ ## Retries, timeouts and rate limits
268
+
269
+ - **Timeouts.** `timeout`, 30 seconds by default, applies to each connect, send and read. Calls the API holds open wait at least 120 seconds: `start`, `stop` and `restart` of applications and databases, `databases.create`, and snapshot `create` and `restore`. So does `ai.chat()`, which answers within 90 seconds or fails with 503 `server_overloaded`. A larger `timeout` wins, and a `timeout` of 0 or less disables every timeout, including that minimum. Uploads and `files.write` calls over 1 MiB have no timeout, and `realtime()` is timed only until it opens.
270
+ - **Retries.** The SDK retries only what is safe to repeat, up to `max_retries` times, which is 2 by default. It retries network errors on `GET`, including a body cut off mid-read, realtime opens, and `download_snapshot()` before the download starts. It also retries 503 `UPLOAD_BUSY` and `ANALYTICS_BUSY` on any method, and 503 `DATABASE_UNAVAILABLE` on `GET`. Each wait is 500 ms × 2ⁿ, where n counts the retries from 0, capped at 8 seconds and randomly shortened by up to half.
271
+ - **Never retried.** Timeouts, any 429, the AI's 503 `server_overloaded` (safe for you to retry), 503 `SNAPSHOTS_UNAVAILABLE` and `CLUSTER_MAINTENANCE_TRY_LATER`, and 409 `RESTORE_IN_PROGRESS`, `SNAPSHOT_IN_PROGRESS` and `ENV_BUSY`. `ENV_BUSY` means another write to the environment variables is in progress. `DATABASE_UNAVAILABLE` is not retried on other methods because the change may already have been applied, so retrying an idempotent call such as `files.write`, `envs.replace` or `stop` is up to you.
272
+ - **Rate limits.** Every account has a global limit of requests per minute, set by its plan ([values](https://docs.squarecloud.app/en/api-reference/limitations-and-restrictions)). Going over it, or over the limit of a single call, returns 429 `RATE_LIMITED` or `KEEP_CALM`. `RATE_LIMITED` can block the account, API key or IP for about 30 minutes, and it is also the limit of the `apps.network` calls and of `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.
273
+
274
+ ## Development
275
+
276
+ ```bash
277
+ uv sync
278
+ uv run ruff format --check && uv run ruff check && uv run mypy && uv run pytest # offline
279
+ uv build
280
+ ```
281
+
282
+ The offline suites (`tests/test_transport.py`, `tests/test_http.py`, `tests/test_streams.py`, `tests/test_conformance.py`, `tests/test_surface.py`) use a mock transport or a loopback server and never reach the API. The live suite runs all 69 operations against the real API:
283
+
284
+ ```bash
285
+ SQUARECLOUD_API_KEY=... uv run pytest -m live -s
286
+ ```
287
+
288
+ > **Warning:** the live suite creates and deletes real resources on the key's account: an application, a database and a workspace named `sdk-live-py-<timestamp>`. It is skipped without `SQUARECLOUD_API_KEY` and never runs in CI. Requests are spaced 2.1 seconds apart. Run the JS, Python and Go live suites one after another, never at the same time.
289
+
290
+ ## Contributing
291
+
292
+ Issues and pull requests are welcome at [squarecloudofc/sdk-api-py](https://github.com/squarecloudofc/sdk-api-py).
293
+
294
+ ## License
295
+
296
+ MIT, see [LICENSE](LICENSE).
297
+
298
+ ## Authors
299
+
300
+ Maintained by [Square Cloud](https://squarecloud.app).
301
+
302
+ Contributors:
303
+
304
+ - Robert Nogueira ([@robert-nogueira](https://github.com/robert-nogueira))
305
+ - Jhonatan Jeferson ([@Jhonatan-Jeferson](https://github.com/Jhonatan-Jeferson))