# Python SDK

Install dcloud-sdk, sign in, launch, query, upload, page through lists, handle errors.

`dcloud-sdk` (imported as `dcloud`) calls the Deutsche Cloud API from Python: one method per API
operation with keyword arguments, the same sign-in chain as the `dcloud` CLI, retries, iterators
over paged lists and waiters. It has no dependencies.

## What it is

Every API operation `service.resource.operation` is a method
`client.service.resource.operation()` in `snake_case`, and every field a keyword argument in
`snake_case`: `ec2.instances.run` with `regionId` is `client.ec2.instances.run(region_id=…)`, and
`s3.bucket-objects.upload-url` is `client.s3.bucket_objects.upload_url()`. Each operation's page in
the _API Reference_ shows the call under **Python**; each method's docstring names the IAM action it
needs.

| Needs  | Version                                                  |
| ------ | -------------------------------------------------------- |
| Python | 3.9 or later                                             |
| Typing | Type hints on every argument (`py.typed`)                |
| Calls  | Synchronous; the client is safe to share between threads |

## Install

`dcloud-sdk` is public in Deutsche Cloud's Python registry: no account or token is needed. Replace
`example.com` with the domain your console is under (`console.example.com` → `example.com`);
**My account → CLI & Git → SDKs** in the console shows the line filled in:

```sh
pip install --index-url https://pypi.example.com/simple/ dcloud-sdk
```

`uv pip install --index-url https://pypi.example.com/simple/ dcloud-sdk` and
`uv add --index https://pypi.example.com/simple/ dcloud-sdk` work the same.

A version's files never change, so pin the version and its hash in `requirements.txt` and install
with `--require-hashes`. `https://<your console>/api/sdk` lists every version with its files and
SHA-256 sums.

## Sign in

`Client()` takes the first credentials it finds, in the order the CLI uses:

| Order | Source                                                                                                  |
| ----- | ------------------------------------------------------------------------------------------------------- |
| 1     | `credentials=` passed to the client: `"<key id>:<secret>"`, a `Credentials` or a provider               |
| 2     | `DCLOUD_ACCESS_KEY` (`<key id>:<secret>`)                                                               |
| 3     | `DCLOUD_SESSION_TOKEN`, a token of your `dcloud login` session                                         |
| 4     | `DCLOUD_WEB_IDENTITY_TOKEN_FILE` and `DCLOUD_ROLE_RN`: an OIDC token, exchanged for a key valid an hour |
| 5     | The profile in `~/.dcloud/credentials.json` that `dcloud login` writes (`DCLOUD_PROFILE` picks one)   |

The console address is `endpoint=`, else `DCLOUD_API_URL`, else the profile's. The region is
`region=`, else `DCLOUD_REGION`, else the profile's.

```python
import os

from dcloud import Client

# From the environment: DCLOUD_API_URL and DCLOUD_ACCESS_KEY.
client = Client()

# Or explicitly.
explicit = Client(
    endpoint="https://console.example.com",
    credentials=os.environ["MY_ACCESS_KEY"],
    region="de1",
)
```

Create an access key under **IAM → Access keys**. The SDK can do exactly what that key's IAM user
is allowed to do.

## First call

```python
from dcloud import Client

client = Client()
for bucket in client.s3.buckets.list()["buckets"]:
    print(bucket["name"])
```

A method returns the `data` of the API's `{"success": true, "data": …}` answer: dicts, lists,
strings and numbers as the JSON holds them.

## Launch an instance and wait for it

`ec2.os_images.list` gives the OS images; an image has one id per CPU architecture. A waiter polls
until the resource is in the state, and raises `WaiterError` if it reaches a failure state or runs
out of time. You pay for the instance from launch until it is terminated.

```python
from dcloud import Client

client = Client()

images = client.ec2.os_images.list(architecture="x86_64")
ubuntu = next(image for image in images if image["name"] == "ubuntu-24.04")

instance = client.ec2.instances.run(
    region_id="de1",
    image_id=ubuntu["id"],
    size_class="s-2",
    name="my-app",
)
running = client.ec2.instances.wait_until_running(id=instance["id"])
print("running at", running["publicIp"])

client.ec2.instances.terminate(id=instance["id"])
client.ec2.instances.wait_until_terminated(id=instance["id"])
```

| Resource             | Waiters                                                             |
| -------------------- | ------------------------------------------------------------------- |
| `ec2.instances`      | `wait_until_running`, `wait_until_stopped`, `wait_until_terminated` |
| `ec2.volumes`        | `wait_until_available`, `wait_until_deleted`                        |
| `ec2.vpcs`           | `wait_until_available`, `wait_until_deleted`                        |
| `ec2.nat_gateways`   | `wait_until_available`, `wait_until_deleted`                        |
| `rds.instances`      | `wait_until_available`, `wait_until_deleted`                        |
| `cache.clusters`     | `wait_until_available`, `wait_until_deleted`                        |
| `deploy.deployments` | `wait_until_finished`, `wait_until_live`                            |
| `deploy.apps`        | `wait_until_active`                                                 |
| `eks.clusters`       | `wait_until_active`, `wait_until_deleted`                           |
| `lb.load_balancers`  | `wait_until_active`                                                 |

Each waiter has its own interval and time limit; `max_wait=` and `interval=` (seconds) override them.

## Create a database and run a query

```python
from dcloud import Client

client = Client()

db = client.rds.instances.create(identifier="orders", instance_class="standard-2", db_name="app")
client.rds.instances.wait_until_available(id=db["id"], max_wait=30 * 60)

result = client.rds.data.run_query(id=db["id"], sql="select count(*) from pg_tables")
print(result["columns"], result["rows"])
```

`rds.data.run_query` runs one read-only statement. For your application's own traffic, connect with
a PostgreSQL driver (psycopg) to the endpoint and credentials the database shows.

## Upload a file to a bucket

`s3.bucket_objects.upload_url` returns a pre-signed URL with the method and headers to send. Send
them unchanged: an added or repeated header breaks the signature.

```python
import urllib.request

from dcloud import Client

client = Client()

upload = client.s3.bucket_objects.upload_url(
    name="my-bucket",
    key="reports/2026-11.pdf",
    content_type="application/pdf",
)
with open("2026-11.pdf", "rb") as f:
    request = urllib.request.Request(
        upload["url"],
        data=f.read(),
        method=upload["method"],
        headers=upload["headers"],
    )
urllib.request.urlopen(request)
```

To move many or large files, use an S3 client (boto3, `rclone`) against the bucket's S3 endpoint,
with temporary credentials from `s3.temporary_credentials.create` or a key from
`s3.access_keys.create`.

## Paged lists

A list the API returns a page at a time has an `…_all` method: an iterator over every item that
fetches the next page when the loop needs it. `limit=` sets the page size.

```python
from dcloud import Client

client = Client()

stopped = sum(1 for _ in client.ec2.instances.list_all(state="stopped", limit=100))
print(stopped, "stopped instances")

for entry in client.iam.audit_logs.list_all(outcome="failure"):
    print(entry["action"])
    break  # stop whenever you have enough; no further page is fetched
```

The iterators: `ec2.instances.list_all`, `iam.audit_logs.list_all`, `ecr.images.list_all`,
`ecr.images.list_scans_all`, `ecr.packages.search_all`, `posture.findings.list_all`,
`errors.issues.list_all`, `errors.events.list_all`, `ai.usage.list_all`,
`email.messages.list_all`, `git.commits.list_all`, `rds.data.read_rows_all` and
`ci.jobs.logs_all`. Every other list returns the whole list at once.

## Errors

```python
from dcloud import ApiError, Client

client = Client()

try:
    client.s3.buckets.create(name="my-bucket")
except ApiError as err:
    if err.is_forbidden:
        print(f"missing permission {err.action} on {err.resource}")
    elif err.is_conflict:
        print(err.message)  # the name is taken
    elif err.is_not_found:
        print("not found")
    else:
        print(err.status, err.message, err.issues, err.request_id)
```

| Class           | When                                                                  |
| --------------- | --------------------------------------------------------------------- |
| `ApiError`      | The API answered with an error status                                 |
| `NetworkError`  | No answer: DNS, connection refused or reset, timeout                  |
| `ConfigError`   | No endpoint or credentials, or a credentials file that cannot be read |
| `WaiterError`   | A waiter saw a failure state (`reason == "failure"`) or timed out     |
| `ResponseError` | A successful answer that does not have the documented shape           |

All of them derive from `DcloudError`. An `ApiError` carries:

| Attribute    | Contents                                                                                    |
| ------------ | ------------------------------------------------------------------------------------------- |
| `status`     | The HTTP status                                                                             |
| `message`    | The API's sentence, e.g. `Not allowed: s3:CreateBucket on rn:ews::… Ask an administrator …` |
| `action`     | On a 403, the IAM action that was denied                                                    |
| `resource`   | On a 403, the resource it was denied on                                                     |
| `code`       | A machine-readable reason where the API gives one, e.g. `STEP_UP_REQUIRED`                  |
| `issues`     | On a 400, one `ValidationIssue(path, message)` per invalid field                            |
| `request_id` | The request's id; give it to support, and find it in the audit log                          |
| `operation`  | The operation, e.g. `s3.buckets.create`                                                     |

`is_forbidden`, `is_conflict`, `is_not_found` and `is_throttled` test the status.

## Retries and timeouts

The SDK retries 429, 502, 503 and 504 answers and connection errors, waiting with jittered
exponential backoff and honouring `Retry-After`. GET, PUT and DELETE are retried on all of them;
POST and PATCH only on 429 and on connection errors from before the request was sent, so a create is
never sent twice.

```python
from dcloud import Client, RequestOptions

client = Client(max_attempts=6, retry_base=0.5, retry_max=30.0, timeout=60.0)

# One call: no retries, give up after five seconds.
client.ec2.vpcs.list(request_options=RequestOptions(max_attempts=1, timeout=5.0))
```

`timeout` is per attempt, in seconds (default 120); `max_attempts` counts the first attempt
(default 4).

## Versions

`dcloud.__version__` is the installed version, sent as the User-Agent
`dcloud-sdk-python/<version>`. Versions follow semantic versioning. While the version starts with
`0.`, a change that can break your code (an operation or argument removed, an argument that becomes
required or changes type) raises the minor version (0.2.0 → 0.3.0), and everything else the patch
version. `https://<your console>/api/sdk/changelog` lists what changed in each version: new
operations, new arguments, new iterators and waiters, and every breaking change.

## Not supported

- pypi.org: install from Deutsche Cloud's Python registry as above.
- `asyncio`: the client is synchronous. Run calls in a thread (`asyncio.to_thread`) from async code.
- Typed responses: methods return plain dicts and lists.
- Following a log as it grows (a build log): call the operation again with the position the last
  answer gave.

## Troubleshooting

| Symptom                                    | Cause                                                         | Fix                                                                  |
| ------------------------------------------ | ------------------------------------------------------------- | -------------------------------------------------------------------- |
| `ConfigError: No endpoint`                 | No `endpoint=`, no `DCLOUD_API_URL`, no profile               | Set `DCLOUD_API_URL` to your console's address                       |
| `ConfigError: No credentials`              | None of the five sources is set                               | Set `DCLOUD_ACCESS_KEY`, or run `dcloud login`                      |
| `ApiError` 403 with `action` set           | The key's IAM user lacks that action                          | Attach a policy allowing `err.action` on `err.resource`              |
| `TypeError: unexpected keyword argument`   | A field name in camelCase, or one the operation does not take | Use the `snake_case` name the operation's _API Reference_ page shows |
| Upload answers 403 `SignatureDoesNotMatch` | A header was added to, or changed from, `upload["headers"]`   | Send exactly `upload["method"]` and `upload["headers"]`              |
| `pip` finds no `dcloud-sdk`                | The index URL lacks `/simple/`, or points at another host     | Use `https://<your console>/api/sdk/pypi/simple/`                    |
