# Customer API
Rent and manage your GPU servers using `https://www.swissgpu.ch/api/v1`. Every endpoint in the endpoint table requires an API token with the listed permission. Account details, rentals, operations and billing records belong to the token’s account only.
[Catalogue offers and pricing](https://www.swissgpu.ch/docs/offers-api) and [published notices](https://www.swissgpu.ch/status) remain public. The [OpenAPI schema (JSON)](https://www.swissgpu.ch/api/v1/openapi.json) lists customer request and response fields. If API access is unavailable in your account, use the website or contact support.

## On this page

- [1. Create a token](#setup)

- [2. Check credit, capacity and prices](#quickstart)

- [3. Rent a server](#create)

- [4. Wait for setup](#wait)

- [5. Connect with SSH](#rental-fields)

- [6. End the rental](#terminate)

- [Reinstall a server](#reinstall)

- [Shared IPv4](#ipv4)

- [Endpoints and permissions](#reference)

- [Credit and transactions](#billing)

- [Retries and errors](#retries)

- [Integrating with an agent](#automation)
[Markdown guide](https://www.swissgpu.ch/docs/customer-api.md) · [OpenAPI schema](https://www.swissgpu.ch/api/v1/openapi.json) · [Resource index](https://www.swissgpu.ch/llms.txt)

## 1. Create a token

- Create an account, verify your email and add credit on the website.

- Open [Account → API access](https://www.swissgpu.ch/account). Choose a name, expiry and only the permissions your application needs. Confirm with your account password or your Google/GitHub sign-in.

- Copy the token into your application’s secret storage. The secret is shown only once.
Send `Authorization: Bearer YOUR_TOKEN` over HTTPS. Browser cookies do not authorize these endpoints. Keep tokens and server passwords out of URLs, source control, browser storage, logs and support messages. Revoke a lost token from your account. Signing out does not revoke tokens; resetting your SwissGPU account password does.
Permissions apply to your account, not just one rental. Include `rentals:read` with any rental-changing permission so you can check the result. Funding and token management use the website.
For the full walkthrough, select `account:read`, `rentals:read`, `rentals:create` and `rentals:terminate`. Add `rentals:reinstall` only if you will use the reinstall example. Billing examples additionally need `billing:read`. Add `rentals:ipv4` to change IPv4 on an existing rental; existing tokens do not gain this permission automatically. Selecting IPv4 during creation or reinstall uses that action’s permission.

## 2. Check credit, capacity and prices
Examples use Bash, curl 7.76 or newer, and Python 3. Keep the same terminal open. Secrets are entered at prompts; IDs, prices and timestamps are illustrative. Use the values returned for your account.

```
# Run these examples in Bash (on macOS, run bash first).
umask 077
BASE='https://www.swissgpu.ch/api/v1'
read -r -s -p 'API token: ' CUSTOMER_TOKEN
printf '\n'

# Pass the header through stdin, not a command-line argument.
api() {
  printf 'header = "Authorization: Bearer %s"\n' "$CUSTOMER_TOKEN" |
    curl --config - --silent --show-error --fail-with-body "$@"
}

api "$BASE/me"
api "$BASE/capacity"
api "$BASE/images"
curl --silent --show-error "$BASE/offers"
```

The `api()` helper sends your bearer token through stdin, keeping it out of command arguments. HTTP errors return a nonzero exit code and their response body. Check each response before continuing; never share the token with an agent.
`/me` returns `id`, `email`, `name`, `credit_cents` and `currency: "CHF"`. For example, `credit_cents: 10000` means CHF 100.00. Capacity looks like `{"RTX4090":true,"RTX5090":false}` with an entry for every supported GPU; it contains no fleet counts. A true value is not a reservation. Images currently returns `["ubuntu:26.04"]`. Use an image returned by this endpoint. Installation currently uses a server password.

## 3. Rent a server
This step starts a paid rental and charges an installation fee when accepted. Read the [prices and fees](https://www.swissgpu.ch/docs/pricing) before submitting it.
Choose the GPU, image and maximum acceptable hourly rate. Public pricing uses CHF/hour, whereas authenticated money fields use integer CHF cents: CHF 0.50/hour becomes `max_hourly_cents: 50`. Use the offer’s on-demand `hourly_price` or a deliberate ceiling. The server checks the actual rate when claiming capacity; it will not accept a higher rate than your ceiling.

```
# Creates a private file; refuses to overwrite an existing request.
if python3 - <<'PY'
import getpass, json, os
payload = {
    "gpu": "RTX4090",
    "image": "ubuntu:26.04",
    "password": getpass.getpass("New server password: "),
    "max_hourly_cents": 50,
    "ipv4": False,
}
fd = os.open("rental-request.json", os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, "w") as output:
    json.dump(payload, output)
PY
then
CREATE_KEY='my-first-rental-001'
printf 'Save this request key for retries: %s\n' "$CREATE_KEY"
api --include --request POST "$BASE/rentals" \
  --header 'Content-Type: application/json' \
  --header "Idempotency-Key: $CREATE_KEY" \
  --data-binary @rental-request.json
else
  printf 'Request file was not created; no API request sent.\n' >&2
fi
```

Set `ipv4` to `true` to request optional shared IPv4 after setup. Omission or `false` keeps IPv6 only. The choice follows a queued rental until installation completes; it never enables forwarding to the installer or a previous tenant. An unavailable option is rejected. IPv4 fees are separate from `max_hourly_cents`; see [Shared IPv4](#ipv4).
Choose a server password of 8–128 characters with a capital letter, number and special character. Do not reuse your account password or API token. Required create fields are `gpu`, `image`, `password` and `max_hourly_cents`. GPU identifiers are case-sensitive (for example `RTX4090`); unknown fields are rejected. You choose a GPU model, not a physical server. Server replacement is not available through this API.
A successfully accepted create returns HTTP `202 Accepted` and an operation:

```
{
  "id": "11111111-1111-4111-8111-111111111111",
  "rental_id": "22222222-2222-4222-8222-222222222222",
  "action": "create",
  "state": "running",
  "status_url": "/api/v1/operations/11111111-1111-4111-8111-111111111111",
  "created_at": "2026-11-15T12:00:00Z",
  "guidance": {
    "next_action": "wait",
    "poll_after_seconds": 30,
    "message": "Allow around 20–30 minutes for installation; some installations take longer. Unchanged progress or unavailable SSH alone does not mean failure. Keep polling; do not restart, reinstall, terminate, or create a replacement merely because setup is still running. Thirty minutes is not an automatic failure deadline. Connect only when the rental state is ready."
  }
}
```

## 4. Wait for setup
HTTP 202 means accepted, not ready. Save the operation ID, rental ID and request key. Poll the returned `status_url` on the same host and follow `guidance.next_action`. Wait at least `guidance.poll_after_seconds` between polls (normally 30 seconds), or longer if `Retry-After` requires it. A null polling delay means stop. On `contact_support`, stop automation even if the operation still says `running`.
Setup normally takes 20–30 minutes, sometimes longer; this is not a failure deadline. Unavailable SSH or unchanged progress alone is not a reason to restart, reinstall, terminate or create a replacement. Connect when the rental is `ready`. For failure or attention, contact support with the rental and operation IDs.

```
# Replace both IDs with the values from your accepted response.
OPERATION_ID='11111111-1111-4111-8111-111111111111'
RENTAL_ID='22222222-2222-4222-8222-222222222222'
api "$BASE/operations/$OPERATION_ID"
api "$BASE/rentals/$RENTAL_ID"

# Once the accepted response is safely recorded, remove the password file.
rm rental-request.json
```

If the create response is lost, keep the password file and retry the exact POST with the same `CREATE_KEY`. See [Retries and errors](#retries) for uncertain requests.

## 5. Connect with SSH
An operation tracks one action. Its `state` is `running` (keep waiting), `succeeded` (action completed), `failed` (action failed), or `attention` (stop automated retries and contact support). A failed operation does not itself confirm that a rental has ended: read the rental before deciding what to do next.
A rental describes the server and billing lifecycle. Its `state` is `installing`, `ready`, `attention`, `releasing` or `ended`. During setup, `progress` moves through `preparing`, `installing` and `checking`. Read `GET /rentals/{rental_id}` after the operation succeeds. A ready response looks like this (all identifiers and addresses below are illustrative):

```
{
  "id": "22222222-2222-4222-8222-222222222222",
  "gpu": "RTX4090",
  "state": "ready",
  "revision": "33333333-3333-4333-8333-333333333333",
  "image": "ubuntu:26.04",
  "progress": "ready",
  "hourly_cents": 50,
  "currency": "CHF",
  "started_at": "2026-11-15T12:00:00Z",
  "ended_at": null,
  "billing_stopped_at": null,
  "release_completed_at": null,
  "guidance": {
    "next_action": "connect",
    "poll_after_seconds": null,
    "message": "Your server is ready. Connect using the current connection details and your chosen password."
  },
  "connection": {
    "username": "ubuntu",
    "hostname": "example.swissgpu.ch",
    "ipv6": "2001:db8::10",
    "ipv4": null
  }
}
```

Connect only when `state` is `ready` and `connection` is present. Use `connection.username` and `connection.hostname` with SSH port 22. Your local network needs IPv6 for the default connection. Enter the server password you chose during creation; passwords are never returned by the API.

```
# Replace the username and hostname with your rental's connection fields.
ssh -6 ubuntu@example.swissgpu.ch
```

If shared IPv4 has been enabled, `connection.ipv4` contains `hostname`, `address`, `ssh_port`, `first_port` and `last_port`. Use its hostname and assigned SSH port instead. A null IPv4 object means no verified IPv4 connection is available. Select it during creation or reinstall, or use the [IPv4 controls](#ipv4) below. See the [SSH guide](https://www.swissgpu.ch/docs/ssh) for host-key checks and troubleshooting.

```
# Only when connection.ipv4 is present; replace all example values.
ssh -4 -p 22000 ubuntu@ipv4.example.swissgpu.ch
```

Rental response field reference |  | Field | Meaning
 | `id` | Opaque rental identifier. Keep it for the lifetime of this rental.
 | `gpu, image` | Assigned GPU model and installation image; either can be null when unavailable.
 | `state` | Current rental lifecycle state, distinct from the operation state.
 | `progress` | Setup stage, ready or attention; null when no setup progress applies.
 | `guidance` | State-specific next_action, poll_after_seconds and a plain-language message. Follow contact_support even while an operation is running.
 | `revision` | Installation identifier to review before reinstalling. May be null.
 | `hourly_cents, currency` | Agreed GPU rate in integer CHF cents per hour. Additional fees are separate.
 | `started_at, ended_at` | Rental start and end timestamps in UTC; may be null. These are distinct from the documented start of hourly charging.
 | `billing_stopped_at` | UTC billing cutoff, or null if none is recorded.
 | `release_completed_at` | UTC physical release completion, or null while incomplete.
 | `connection` | Verified connection object, or null when unavailable. It contains no password.
 | `connection.username, connection.hostname` | SSH username and default IPv6 hostname; use port 22.
 | `connection.ipv6` | Verified IPv6 address, or null.
 | `connection.ipv4` | Optional verified shared IPv4 object. Use its hostname or address and ssh_port; first_port and last_port describe the assigned public port range.

## 6. End the rental
Back up your data first. Termination releases the server and your data will be erased. Powering off the operating system or closing SSH does not end billing. Send a DELETE with no request body and a new saved key:

```
TERMINATE_KEY='my-first-rental-stop-001'
api --include --request DELETE "$BASE/rentals/$RENTAL_ID" \
  --header "Idempotency-Key: $TERMINATE_KEY"
```

Save the returned operation ID, then poll that operation and read the rental again. Accepted termination records the billing cutoff in `billing_stopped_at`; `release_completed_at` records completed release. Final charges may settle afterward. These are separate events: an example of the relevant fields after completed release is:

```
{
  "state": "ended",
  "billing_stopped_at": "2026-11-15T14:00:00Z",
  "release_completed_at": "2026-11-15T14:00:12Z",
  "connection": null
}
```

If the DELETE response is lost, repeat the same DELETE with the same key. If the operation needs attention or the cutoff is missing, contact support with the IDs; do not assume billing stopped.

## Reinstall a server
This optional action applies to an active rental, before termination. It erases the disk and incurs another installation fee. Back up your data, read the rental, and review its current `revision`. Use that exact value as `expected_revision` to ensure you erase the installation you reviewed.

```
# Creates a private request file and refuses to overwrite an existing one.
read -r -p 'Current rental revision: ' REVISION
if python3 - "$REVISION" <<'PYTHON'
import getpass, json, os, sys
payload = {
    "image": "ubuntu:26.04",
    "password": getpass.getpass("New server password: "),
    "erase_disk": True,
    "expected_revision": sys.argv[1],
    "ipv4": False,
}
fd = os.open("reinstall-request.json", os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, "w") as output:
    json.dump(payload, output)
PYTHON
then
REINSTALL_KEY='my-first-reinstall-001'
api --include --request POST "$BASE/rentals/$RENTAL_ID/reinstall" \
  --header 'Content-Type: application/json' \
  --header "Idempotency-Key: $REINSTALL_KEY" \
  --data-binary @reinstall-request.json
else
  printf 'Request file was not created; no API request sent.\n' >&2
fi
```

Poll the returned operation as in step 4. Retain the request file until acceptance is safely recorded, then remove it with `rm reinstall-request.json`. A `stale_revision` error means the reviewed installation no longer matches. Fetch and review the rental again; do not automatically substitute its newer revision or authorize another erase.

## Shared IPv4
IPv6 is included. Optional shared IPv4 costs CHF 0.50 per started rolling 24-hour period, charged after forwarding is verified. Disabling stops renewal, with no prorated refund; re-enabling within the same customer’s paid period reuses that period. Starting an unpaid period needs 50 cents of credit; setup selection also needs the installation fee. Reinstallation closes the previous grant: set `ipv4: true` again if wanted, or enable it after the new installation is ready.
Shared IPv4 provides 100 assigned public TCP ports, including the assigned SSH port. UDP and shared public ports 80/443 are unavailable. Your application must listen on IPv4 and your server firewall must allow it. Use only verified `connection.ipv4` details to connect.
Read `GET /rentals/{id}/ipv4` with `rentals:read`. It returns `requested` (saved setup choice), `desired_enabled` (accepted intent), `state`, `can_enable`, `self_service`, `customer_blocked`, `daily_fee_cents`, `paid_until` (Unix seconds or null), public address/ports and the control identity. The numeric `revision` here is the IPv4 revision, distinct from the rental’s installation revision. Copy it and `installation_id` into the PUT request.
PUT requires `rentals:ipv4`. The following example uses the earlier Bash helper and rental ID. Set `IPV4_ENABLED=false` to disable instead. Keep the saved body for uncertain retries; no `Idempotency-Key` is needed. After a conflict, review status before preparing a new request.

```
IPV4_ENABLED=true
if api "$BASE/rentals/$RENTAL_ID/ipv4" > ipv4-status.json; then
  if python3 - "$IPV4_ENABLED" <<'PY'
import json, sys
with open("ipv4-status.json") as source:
    status = json.load(source)
with open("ipv4-change.json", "w") as output:
    json.dump({"enabled": sys.argv[1] == "true",
               "expected_revision": status["revision"],
               "expected_installation_id": status["installation_id"]}, output)
PY
  then
    api --include --request PUT "$BASE/rentals/$RENTAL_ID/ipv4" \
      --header 'Content-Type: application/json' \
      --data-binary @ipv4-change.json
  fi
fi
# Wait at least 30 seconds between polls, and stop after a bounded number of attempts.
api "$BASE/rentals/$RENTAL_ID/ipv4"
```

HTTP 202 means accepted. Poll GET no faster than every 30 seconds; only `enabled` confirms forwarding. Other states are `off`, `applying`, `disabling`, `unavailable` and `unknown`. Missing or stale evidence never proves connectivity. A current installation can cancel its saved choice with `enabled: false`; enabling needs completed, eligible setup. Queued handoffs, ended/releasing rentals and obsolete assignments return `stale_rental`. Support blocks cannot be lifted by API tokens. Disabling stays available when new activations are suspended. For a timeout or lost PUT response, retry the exact saved body; do not automatically refresh the revision to force the change through.

## Endpoints and permissions
All paths in this table are relative to `/api/v1`. Every listed endpoint requires a bearer token.
 |  | Method and path | Required permission | Purpose
 | [`GET /me`](#quickstart) | `account:read` | Your account and available CHF credit.
 | [`GET /capacity`](#quickstart) | `rentals:read` | Advisory availability per GPU model.
 | [`GET /images`](#quickstart) | `rentals:read` | Images you can install through this API.
 | [`POST /rentals`](#create) | `rentals:create` | Rent one server by GPU model. Requires Idempotency-Key.
 | [`GET /rentals`](#rental-list) | `rentals:read` | Paginated active rentals and optional closed history.
 | [`GET /rentals/{id}/ipv4`](#ipv4) | `rentals:read` | Shared IPv4 state, controls, tariff and ports.
 | [`PUT /rentals/{id}/ipv4`](#ipv4) | `rentals:ipv4` | Enable or disable shared IPv4 using its current revision.
 | [`GET /rentals/{id}`](#rental-fields) | `rentals:read` | One rental, progress, rate, revision and connection details.
 | [`POST /rentals/{id}/reinstall`](#reinstall) | `rentals:reinstall` | Erase and reinstall the same rental. Requires Idempotency-Key.
 | [`DELETE /rentals/{id}`](#terminate) | `rentals:terminate` | Stop rental billing and release the server. Requires Idempotency-Key.
 | [`GET /operations/{id}`](#wait) | `rentals:read` | Poll an accepted create, reinstall or termination.
 | [`GET /transactions`](#billing) | `billing:read` | Your wallet transactions.
 | [`GET /transactions/{id}`](#billing) | `billing:read` | One of your transactions.
 | [`GET /reports/transactions`](#billing) | `billing:read` | Download your transaction report as PDF.

Successful reads return HTTP 200; accepted lifecycle actions return HTTP 202. Use JSON request bodies and `Content-Type: application/json` for creation/reinstall. Send the token only in the `Authorization: Bearer …` header. Cookies and browser login do not authorize these endpoints. Responses are private and should not be cached. Preserve IDs exactly as returned; treat all IDs as opaque values, including transaction IDs. Timestamps use UTC with an explicit offset.

### List rentals
`GET /rentals` defaults to active rentals, with `page=1` and `page_size=25` (maximum 100). Add `include_closed=true` to include ended rentals. It returns `items`, `page`, `page_size` and `total`. The total counts your own matching rentals only. Follow pages until you have read the total; changing live rental state may change results between requests.

```
api "$BASE/rentals?page=1&page_size=25"
api "$BASE/rentals?page=1&page_size=25&include_closed=true"
```

## Your credit and transactions
Fund your account on the website. Customer API amounts use integer CHF cents; transaction amounts are positive for credits and negative for charges. The maximum hourly rate on a rental request is not a total spending limit. See [pricing and billing terms](https://www.swissgpu.ch/docs/pricing) for charges. Hourly usage begins after successful installation.
Transaction pages use `page` and `page_size` (default 10, maximum 50). Their `total` counts your matching transactions only. Treat returned IDs as opaque. PDF reports accept optional Unix-second `start` and `end` parameters. No matching transactions returns HTTP 404. Check the response status before saving a report.

```
api "$BASE/transactions?page=1&page_size=10"
# The helper exits nonzero for HTTP errors. Rename only a successful PDF response.
if api --output transactions.pdf.part "$BASE/reports/transactions"; then
  mv transactions.pdf.part transactions.pdf
else
  cat transactions.pdf.part
  rm transactions.pdf.part
fi
```

Transaction responses contain `id`, `type`, `amount` (CHF cents), `timestamp` and optional type-specific fields. For example, a usage charge may include `duration` in seconds or `power_usage_kwh`. See the schema for each transaction type. Reports return `application/pdf` on success. To select a period, append `?start=UNIX_SECONDS&end=UNIX_SECONDS`; end must not precede start.

## Retries and errors
Create, reinstall and terminate require an `Idempotency-Key` of 1–128 printable ASCII characters without spaces. Save a unique key and the exact request for each intended action. Keys belong to the account across tokens. Once accepted, poll the operation; reusing its key does not restart failed work.
After a transport error or HTTP 5xx, the server may already have accepted the action. Retry with the original method, target, key and body; do not create a new key. For `Retry-After`, wait the stated number of seconds; if absent, start with a short delay and increase it between attempts. Stop after a bounded number of attempts and reconcile the operation or contact support.
Errors contain a `detail` string and a `request_id`. Use `detail` for known error codes and retain a fallback for unknown codes. The request ID is also in the `X-Request-ID` response header. Validation errors additionally contain an `errors`array with `loc`, `msg` and `type` for each issue. For example:

```
{
  "detail": "capacity_unavailable",
  "request_id": "44444444444444448444444444444444"
}
```

```
{
  "detail": "invalid_request",
  "request_id": "44444444444444448444444444444444",
  "errors": [
    {"loc": ["body", "gpu"], "msg": "Field required", "type": "missing"}
  ]
}
```

 |  | HTTP / detail | What to do
 | `401 / invalid_token` | Check whether the token expired or was revoked.
 | `403 / insufficient_scope` | Use a token with the endpoint’s permission.
 | `402 / insufficient_balance` | Add credit on the website.
 | `409 / capacity_unavailable` | No matching server could be claimed. Check capacity before a new attempt.
 | `409 / price_changed` | Review current pricing and your ceiling before authorizing a changed request.
 | `409 / stale_revision` | Review the rental again before authorizing an erase.
 | `409 / stale_rental` | This assignment is queued, ending or no longer current; review the rental.
 | `409 / ipv4_unavailable` | Refresh IPv4 status and review readiness, control revisions, admission and support blocks; contact support if it persists.
 | `409 / idempotency_conflict` | This account already used the key for a different request. Recover the original action; do not blindly retry with a new key.
 | `409 / account_operation_pending` | Wait for your existing setup operation before starting another.
 | `409 / active_rental_limit` | An account rental limit applies. Review active rentals or contact support.
 | `409 / installation_unavailable` | The installation cannot currently proceed. Contact support if it persists.
 | `422 / invalid_request` | Correct the fields identified by errors; never log a secret-bearing request body.
 | `422 / invalid_idempotency_key` | Use 1–128 printable ASCII characters without spaces.
 | `429 / rate_limited` | Wait for Retry-After seconds before retrying.
 | `503 / telemetry_unavailable or ipv4_cleanup_pending` | Wait for Retry-After, then retry the exact request and key.
 | `503 / customer_api_disabled` | Check published notices or use the website; avoid a tight retry loop.

A 404 means the record is missing or does not belong to your account; reports also return 404 when no transactions match. A 413 means the body exceeds 8 KiB. For other 409 conflicts, refresh the rental and review its state before deciding on a new action. Send only documented request fields.
Default limits are 120 reads and 10 changes per minute per account and token. Additional tokens do not increase the account allowance. If an action needs attention, give support its request, operation and rental IDs, never credentials. See [terms](https://www.swissgpu.ch/terms) and [published notices](https://www.swissgpu.ch/status) before integrating.

## Integrating with an agent

- Obtain explicit customer intent for paid creation, disk erasure and termination. A capacity read is not a reservation or permission to rent.

- Keep credentials and each action’s key, exact request and returned IDs in secure storage. Follow [Retries and errors](#retries) before repeating an uncertain request.

- Follow the returned guidance and polling delay. Stop on failure or attention; never raise a price ceiling or replace a revision without a new decision.

- Inspect HTTP status and Content-Type before parsing. PDF reports are binary; error responses are JSON.
When finished, remove private request files and run `unset CUSTOMER_TOKEN`.