Ir para o conteúdo principal
Apidly Cloud
Política de cookies

Os cookies de análise e de publicidade ficam desativados, a menos que você aceite. Política de cookies

Gostaríamos de usar o Google Analytics e o Microsoft Clarity para entender como as páginas públicas são usadas, incluindo visualizações de página e gravações de sessão, e o Reddit Pixel para medir se nossos anúncios no Reddit geram visitas e cadastros. Você escolhe aqui se eles ficam ativados. Recusar não muda nada no funcionamento do site.

Exemplos para cada tarefa comum

Programas completos em JavaScript, Python e shell para copiar: iniciar com limite de preço, rodar um script, vigiar o saldo, exportar o uso, webhooks e mais.

Última atualização em 23 de novembro de 20264 min de leitura
Ver como Markdown

Programas completos para copiar e executar, um para cada tarefa comum, em JavaScript, Python e shell. Nenhum arquivo contém preço: cada um lê os preços da API, e os que iniciam algo verificam o preço antes com uma simulação gratuita e recusam acima do limite que você define em MAX_HOURLY_USD. Cada arquivo é verificado automaticamente contra os SDKs, a CLI e a descrição da API, e executado contra uma versão de teste da API.

Antes de começar

  • Uma chave de API na variável de ambiente APIDLY_API_KEY. Cada arquivo a lê de lá; nunca escreva uma chave em um arquivo.
  • JavaScript: Node 18 ou mais recente e o SDK (veja SDKs). Salve o arquivo com a extensão .mjs e execute-o com node.
  • Python: Python 3.9 ou mais recente e o SDK (veja SDKs). Execute o arquivo com python.
  • Shell: bash, curl, jq e o comando apidly (veja CLI).
  • Cada arquivo começa com um comentário que diz o que ele faz, quanto custa, como parar de gastar e quais variáveis ele lê.

Iniciar o servidor mais barato para um template

Encontra o plano disponível mais barato com memória de GPU suficiente para o template, verifica o preço com uma simulação, cria o servidor com um limite de gasto e um tempo máximo de execução, espera até ele rodar e mostra o comando SSH. Pressione Enter e ele exclui o servidor.

JavaScript · examples/node/launch-cheapest-server.mjs

// Launch the cheapest server that fits a template, wait until it runs, print how to connect, then destroy it.
//
// What it does: finds the cheapest plan in stock with enough GPU memory for TEMPLATE, prices the request with a dry
//   run (nothing is created), refuses when it costs more per hour than MAX_HOURLY_USD, then creates the server with a
//   spending limit and a maximum running time, waits until it runs and prints the SSH command. Press Enter (or close
//   the input) to destroy it.
// What it costs: the dry run is free. The server is billed by the second from the moment it runs, at the hourly price
//   the script prints (compute plus disk). It stops on its own at MAX_SPEND_USD or after MAX_HOURS hours.
// How to stop spending: press Enter, or run `apidly destroy SERVER_ID --yes`. A stopped server still pays for its disk;
//   only destroy ends every charge.
//
// Needs Node 18+, `npm install ./apidly-sdk-VERSION.tgz` (see https://apidly.com/docs/sdks) and an API key with the
// Servers scope in APIDLY_API_KEY. Optional: SSH_KEY_ID (from `apidly ssh-keys`), TEMPLATE (default pytorch),
// MAX_SPEND_USD (default MAX_HOURLY_USD x MAX_HOURS), MAX_HOURS (default 2), POLL_SECONDS (default 10).
//   MAX_HOURLY_USD=<your limit> node launch-cheapest-server.mjs
import { createInterface } from "node:readline";
import { Apidly } from "@apidly/sdk";

const env = process.env;
const maxHourly = Number(env.MAX_HOURLY_USD);
if (!(maxHourly > 0)) {
  console.error("Set MAX_HOURLY_USD to the most you will pay per hour");
  process.exit(2);
}
const maxHours = Number(env.MAX_HOURS ?? 2);
const maxSpend = Number(env.MAX_SPEND_USD ?? maxHourly * maxHours);
const pollMs = Number(env.POLL_SECONDS ?? 10) * 1000;
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

const apidly = new Apidly({ apiKey: env.APIDLY_API_KEY });

const { template } = await apidly.templates.get(env.TEMPLATE ?? "pytorch");
const { plans } = await apidly.plans.list({
  minVramGb: template.minVramGb,
  availability: "available",
  sort: "price",
  limit: 1,
});
const plan = plans[0];
if (!plan) {
  console.error(
    `No plan with ${template.minVramGb} GB GPU memory is in stock right now. Try again later.`
  );
  process.exit(1);
}

const request = {
  planId: plan.id,
  templateId: template.id,
  label: `cheapest-${template.slug}`,
  diskGb: Math.max(plan.diskGb, template.defaultDiskGb),
  sshKeyIds: env.SSH_KEY_ID ? [env.SSH_KEY_ID] : [],
  automation: {
    maxRuntimeHours: maxHours,
    spendCapCents: Math.max(10, Math.round(maxSpend * 100)),
  },
};

// 1. Price check: a dry run runs every check of a real request and creates nothing.
const { quote } = await apidly.servers.estimate(request);
console.log(
  `${plan.name}: ${quote.totalHourlyUsd} USD per hour while running (${quote.storageHourlyUsd} of it for the disk)`
);
if (quote.blockers.length > 0) {
  console.error(
    quote.blockers.map((b) => `${b.code}: ${b.message}`).join("\n")
  );
  process.exit(1);
}
if (Number(quote.totalHourlyUsd) > maxHourly) {
  console.error(
    `That is more than MAX_HOURLY_USD=${maxHourly}. Nothing was created.`
  );
  process.exit(1);
}

// 2. The real request. The SDK sends an Idempotency-Key, so its own retries never create a second server.
let { server, deployment } = await apidly.servers.create(request);
while (!server) {
  // Some requests are reviewed by our team first; the server appears once the request is approved.
  if (["rejected", "failed", "cancelled"].includes(deployment.status)) {
    console.error(
      `Request ${deployment.id} was ${deployment.status}: ${deployment.reason ?? ""}`
    );
    process.exit(1);
  }
  console.log(`Request ${deployment.id} is ${deployment.status}, waiting...`);
  await sleep(pollMs);
  ({ deployment } = await apidly.deployments.get(deployment.id));
  if (deployment.serverId) {
    ({ server } = await apidly.servers.get(deployment.serverId));
  }
}

// 3. Wait until it runs.
while (server.status !== "running") {
  if (
    ["error", "destroyed", "suspended", "interrupted"].includes(server.status)
  ) {
    console.error(
      `Server ${server.id} is ${server.status}: ${server.statusMessage ?? ""}`
    );
    await apidly.servers.delete(server.id);
    process.exit(1);
  }
  console.log(`${server.id} is ${server.status}...`);
  await sleep(pollMs);
  ({ server } = await apidly.servers.get(server.id));
}
console.log(
  `${server.id} is running. Connect with:\n  ${server.connection?.ssh?.command ?? `apidly ssh ${server.id}`}`
);

// 4. Destroy it when you are done.
const rl = createInterface({ input: process.stdin });
console.log("Press Enter to destroy the server.");
await new Promise((done) => {
  rl.once("line", done);
  rl.once("close", done);
});
rl.close();
await apidly.servers.delete(server.id);
console.log(`Destroyed ${server.id}. Nothing more is charged for it.`);

Python · examples/python/launch_cheapest_server.py

"""Launch the cheapest server that fits a template, wait until it runs, print how to connect, then destroy it.

What it does: finds the cheapest plan in stock with enough GPU memory for TEMPLATE, prices the request with a dry run
  (nothing is created), refuses when it costs more per hour than MAX_HOURLY_USD, then creates the server with a
  spending limit and a maximum running time, waits until it runs and prints the SSH command. Press Enter (or close
  the input) to destroy it.
What it costs: the dry run is free. The server is billed by the second from the moment it runs, at the hourly price
  the script prints (compute plus disk). It stops on its own at MAX_SPEND_USD or after MAX_HOURS hours.
How to stop spending: press Enter, or run `apidly destroy SERVER_ID --yes`. A stopped server still pays for its disk;
  only destroy ends every charge.

Needs Python 3.9+, `pip install ./apidly-VERSION-py3-none-any.whl` (see https://apidly.com/docs/sdks) and an API key
with the Servers scope in APIDLY_API_KEY. Optional: SSH_KEY_ID (from `apidly ssh-keys`), TEMPLATE (default pytorch),
MAX_SPEND_USD (default MAX_HOURLY_USD x MAX_HOURS), MAX_HOURS (default 2), POLL_SECONDS (default 10).
  MAX_HOURLY_USD=<your limit> python launch_cheapest_server.py
"""
import os
import sys
import time

from apidly import Client

max_hourly = float(os.environ.get("MAX_HOURLY_USD") or 0)
if max_hourly <= 0:
    sys.exit("Set MAX_HOURLY_USD to the most you will pay per hour")
max_hours = float(os.environ.get("MAX_HOURS", "2"))
max_spend = float(os.environ.get("MAX_SPEND_USD") or max_hourly * max_hours)
poll = float(os.environ.get("POLL_SECONDS", "10"))

client = Client(api_key=os.environ["APIDLY_API_KEY"])

template = client.templates.get(os.environ.get("TEMPLATE", "pytorch"))["template"]
plans = client.plans.list(
    min_vram_gb=template["minVramGb"], availability="available", sort="price", limit=1
)["plans"]
if not plans:
    sys.exit(f"No plan with {template['minVramGb']} GB GPU memory is in stock right now. Try again later.")
plan = plans[0]

request = dict(
    plan_id=plan["id"],
    template_id=template["id"],
    label=f"cheapest-{template['slug']}",
    disk_gb=max(plan["diskGb"], template["defaultDiskGb"]),
    ssh_key_ids=[os.environ["SSH_KEY_ID"]] if os.environ.get("SSH_KEY_ID") else [],
    automation={"maxRuntimeHours": max_hours, "spendCapCents": max(10, round(max_spend * 100))},
)

# 1. Price check: a dry run runs every check of a real request and creates nothing.
quote = client.servers.estimate(**request)["quote"]
print(f"{plan['name']}: {quote['totalHourlyUsd']} USD per hour while running ({quote['storageHourlyUsd']} of it for the disk)")
if quote["blockers"]:
    sys.exit("\n".join(f"{b['code']}: {b['message']}" for b in quote["blockers"]))
if float(quote["totalHourlyUsd"]) > max_hourly:
    sys.exit(f"That is more than MAX_HOURLY_USD={max_hourly}. Nothing was created.")

# 2. The real request. The SDK sends an Idempotency-Key, so its own retries never create a second server.
created = client.servers.create(**request)
server, deployment = created["server"], created["deployment"]
while server is None:
    # Some requests are reviewed by our team first; the server appears once the request is approved.
    if deployment["status"] in ("rejected", "failed", "cancelled"):
        sys.exit(f"Request {deployment['id']} was {deployment['status']}: {deployment.get('reason') or ''}")
    print(f"Request {deployment['id']} is {deployment['status']}, waiting...")
    time.sleep(poll)
    deployment = client.deployments.get(deployment["id"])["deployment"]
    if deployment.get("serverId"):
        server = client.servers.get(deployment["serverId"])["server"]

# 3. Wait until it runs.
while server["status"] != "running":
    if server["status"] in ("error", "destroyed", "suspended", "interrupted"):
        client.servers.delete(server["id"])
        sys.exit(f"Server {server['id']} is {server['status']}: {server.get('statusMessage') or ''}")
    print(f"{server['id']} is {server['status']}...")
    time.sleep(poll)
    server = client.servers.get(server["id"])["server"]
ssh = (server.get("connection") or {}).get("ssh") or {}
print(f"{server['id']} is running. Connect with:\n  {ssh.get('command') or 'apidly ssh ' + server['id']}")

# 4. Destroy it when you are done.
try:
    input("Press Enter to destroy the server.\n")
except EOFError:
    pass
client.servers.delete(server["id"])
print(f"Destroyed {server['id']}. Nothing more is charged for it.")

Shell · examples/shell/launch-cheapest-server.sh

#!/usr/bin/env bash
# Launch the cheapest server that fits a template, wait until it runs, print how to connect, then destroy it.
#
# What it does: finds the cheapest plan in stock with enough GPU memory for TEMPLATE, prices the request with a dry
#   run (nothing is created), refuses when it costs more per hour than MAX_HOURLY_USD, then creates the server with a
#   spending limit and a maximum running time, waits until it runs and prints the SSH command. Press Enter (or close
#   the input) to destroy it.
# What it costs: the dry run is free. The server is billed by the second from the moment it runs, at the hourly price
#   the script prints (compute plus disk). It stops on its own at MAX_SPEND_USD or after MAX_HOURS hours.
# How to stop spending: press Enter, or run `apidly destroy SERVER_ID --yes`. A stopped server still pays for its disk;
#   only destroy ends every charge.
#
# Needs bash, curl, jq, the apidly CLI (https://apidly.com/docs/cli) and an API key with the Servers scope in
# APIDLY_API_KEY. Optional: SSH_KEY_ID (from `apidly ssh-keys`), TEMPLATE (default pytorch), MAX_SPEND_USD (default
# MAX_HOURLY_USD x MAX_HOURS), MAX_HOURS (default 2), POLL_SECONDS (default 10).
#   MAX_HOURLY_USD=<your limit> ./launch-cheapest-server.sh
set -euo pipefail

: "${MAX_HOURLY_USD:?Set MAX_HOURLY_USD to the most you will pay per hour}"
MAX_HOURS="${MAX_HOURS:-2}"
MAX_SPEND_USD="${MAX_SPEND_USD:-$(jq -n "$MAX_HOURLY_USD * $MAX_HOURS")}"
POLL_SECONDS="${POLL_SECONDS:-10}"
BASE="${APIDLY_API_URL:-https://apidly.com}"

template=$(apidly templates show "${TEMPLATE:-pytorch}" --json | jq '.template')
min_vram=$(jq -r '.minVramGb' <<<"$template")
plan=$(apidly plans --min-vram "$min_vram" --available --sort price --limit 1 --json | jq '.plans[0]')
if [ "$plan" = "null" ]; then
  echo "No plan with $min_vram GB GPU memory is in stock right now. Try again later." >&2
  exit 1
fi

body=$(jq -n --argjson plan "$plan" --argjson template "$template" \
  --arg ssh "${SSH_KEY_ID:-}" --argjson hours "$MAX_HOURS" --argjson spend "$MAX_SPEND_USD" '{
    planId: $plan.id,
    templateId: $template.id,
    label: ("cheapest-" + $template.slug),
    diskGb: ([$plan.diskGb, $template.defaultDiskGb] | max),
    sshKeyIds: (if $ssh == "" then [] else [$ssh] end),
    automation: { maxRuntimeHours: $hours, spendCapCents: ([10, ($spend * 100 | round)] | max) }
  }')

# 1. Price check: a dry run runs every check of a real request and creates nothing.
quote=$(curl -fsS -X POST "$BASE/api/v1/servers?dryRun=1" \
  -H "Authorization: Bearer $APIDLY_API_KEY" -H "Content-Type: application/json" -d "$body" | jq '.quote')
echo "$(jq -r '.name' <<<"$plan"): $(jq -r '.totalHourlyUsd' <<<"$quote") USD per hour while running"
if [ "$(jq '.blockers | length' <<<"$quote")" -gt 0 ]; then
  jq -r '.blockers[] | "\(.code): \(.message)"' <<<"$quote" >&2
  exit 1
fi
if jq -e --argjson max "$MAX_HOURLY_USD" '(.totalHourlyUsd | tonumber) > $max' <<<"$quote" >/dev/null; then
  echo "That is more than MAX_HOURLY_USD=$MAX_HOURLY_USD. Nothing was created." >&2
  exit 1
fi

# 2. The real request, with an Idempotency-Key: if curl retries, the same server is returned, never a second one.
created=$(curl -fsS --retry 3 -X POST "$BASE/api/v1/servers" \
  -H "Authorization: Bearer $APIDLY_API_KEY" -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen 2>/dev/null || cat /proc/sys/kernel/random/uuid)" -d "$body")
deployment=$(jq -r '.deployment.id' <<<"$created")
id=$(jq -r '.server.id // empty' <<<"$created")
while [ -z "$id" ]; do
  # Some requests are reviewed by our team first; the server appears once the request is approved.
  status=$(apidly deployments show "$deployment" --json | jq -r '.deployment.status')
  case "$status" in rejected | failed | cancelled) echo "Request $deployment was $status" >&2; exit 1 ;; esac
  echo "Request $deployment is $status, waiting..."
  sleep "$POLL_SECONDS"
  id=$(apidly deployments show "$deployment" --json | jq -r '.deployment.serverId // empty')
done

# 3. Wait until it runs.
while :; do
  server=$(apidly servers show "$id" --json | jq '.server')
  status=$(jq -r '.status' <<<"$server")
  [ "$status" = "running" ] && break
  case "$status" in
    error | destroyed | suspended | interrupted)
      echo "Server $id is $status" >&2
      apidly destroy "$id" --yes
      exit 1
      ;;
  esac
  echo "$id is $status..."
  sleep "$POLL_SECONDS"
done
echo "$id is running. Connect with:"
echo "  $(jq -r '.connection.ssh.command // empty' <<<"$server")"

# 4. Destroy it when you are done.
echo "Press Enter to destroy the server."
read -r _ || true
apidly destroy "$id" --yes
echo "Destroyed $id. Nothing more is charged for it."

Rodar um script em um servidor e buscar o resultado

Cria um servidor, envia seu job.sh local por SSH, salva o que o script imprime em result.txt e exclui o servidor, também quando o script falha. Precisa de uma chave SSH (SSH_KEY_ID) e de um plano.

JavaScript · examples/node/run-script-and-fetch-result.mjs

// Run a local script on a new GPU server, save what it prints to a file, then destroy the server.
//
// What it does: creates a server from PLAN_ID and TEMPLATE (default pytorch) with your SSH key, waits until it runs,
//   sends SCRIPT (default job.sh) to it over SSH, writes everything the script prints to RESULT (default result.txt)
//   and destroys the server, also when the script fails.
// What it costs: the server's hourly price (compute plus disk), by the second, from the moment it runs until it is
//   destroyed a few seconds after the script ends. A dry run prints the price first and refuses above MAX_HOURLY_USD.
// How to stop spending: the script destroys the server in a `finally` block. If you kill it with kill -9 or lose
//   power, run `apidly servers` and `apidly destroy SERVER_ID --yes`. The server also stops itself after MAX_HOURS.
//
// Needs Node 18+, `npm install ./apidly-sdk-VERSION.tgz`, the `ssh` command, APIDLY_API_KEY (Servers scope), SSH_KEY_ID
// (from `apidly ssh-keys`) and PLAN_ID (from `apidly plans --available --sort price`).
//   PLAN_ID=... SSH_KEY_ID=... MAX_HOURLY_USD=<your limit> node run-script-and-fetch-result.mjs
import { spawnSync } from "node:child_process";
import { closeSync, openSync } from "node:fs";
import { Apidly } from "@apidly/sdk";

const env = process.env;
for (const name of ["PLAN_ID", "SSH_KEY_ID", "MAX_HOURLY_USD"]) {
  if (!env[name]) {
    console.error(
      `Set ${name} first (see the comment at the top of this file).`
    );
    process.exit(2);
  }
}
const script = env.SCRIPT ?? "job.sh";
const resultFile = env.RESULT ?? "result.txt";
const pollMs = Number(env.POLL_SECONDS ?? 10) * 1000;
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

const apidly = new Apidly({ apiKey: env.APIDLY_API_KEY });
const { template } = await apidly.templates.get(env.TEMPLATE ?? "pytorch");
const request = {
  planId: env.PLAN_ID,
  templateId: template.id,
  label: "run-script",
  diskGb: template.defaultDiskGb,
  sshKeyIds: [env.SSH_KEY_ID],
  automation: { maxRuntimeHours: Number(env.MAX_HOURS ?? 2) },
};

const { quote } = await apidly.servers.estimate(request);
if (
  quote.blockers.length > 0 ||
  Number(quote.totalHourlyUsd) > Number(env.MAX_HOURLY_USD)
) {
  console.error(
    `Not started: ${quote.totalHourlyUsd} USD per hour`,
    quote.blockers
  );
  process.exit(1);
}

let { server, deployment } = await apidly.servers.create(request);
try {
  while (!server) {
    if (["rejected", "failed", "cancelled"].includes(deployment.status)) {
      throw new Error(`Request ${deployment.id} was ${deployment.status}`);
    }
    await sleep(pollMs);
    ({ deployment } = await apidly.deployments.get(deployment.id));
    if (deployment.serverId) {
      ({ server } = await apidly.servers.get(deployment.serverId));
    }
  }
  while (server.status !== "running") {
    if (
      ["error", "destroyed", "suspended", "interrupted"].includes(server.status)
    ) {
      throw new Error(
        `Server ${server.id} is ${server.status}: ${server.statusMessage ?? ""}`
      );
    }
    await sleep(pollMs);
    ({ server } = await apidly.servers.get(server.id));
  }

  // The SSH service can need a little longer than the server; try a few times.
  const { host, port, user } = server.connection.ssh;
  const args = [
    "-p",
    String(port),
    "-o",
    "StrictHostKeyChecking=accept-new",
    "-o",
    "ConnectTimeout=15",
    `${user}@${host}`,
    "bash -s",
  ];
  let code = 255;
  for (let attempt = 1; attempt <= 5 && code === 255; attempt++) {
    const input = openSync(script, "r");
    const output = openSync(resultFile, "w");
    code =
      spawnSync("ssh", args, { stdio: [input, output, "inherit"] }).status ??
      255;
    closeSync(input);
    closeSync(output);
    if (code === 255) {
      await sleep(pollMs);
    }
  }
  console.log(`${script} exited with ${code}; its output is in ${resultFile}`);
  process.exitCode = code;
} finally {
  if (server) {
    await apidly.servers.delete(server.id);
    console.log(`Destroyed ${server.id}.`);
  } else {
    await apidly.deployments.cancel(deployment.id).catch(() => {});
  }
}

Python · examples/python/run_script_and_fetch_result.py

"""Run a local script on a new GPU server, save what it prints to a file, then destroy the server.

What it does: creates a server from PLAN_ID and TEMPLATE (default pytorch) with your SSH key, waits until it runs,
  sends SCRIPT (default job.sh) to it over SSH, writes everything the script prints to RESULT (default result.txt)
  and destroys the server, also when the script fails.
What it costs: the server's hourly price (compute plus disk), by the second, from the moment it runs until it is
  destroyed a few seconds after the script ends. A dry run prints the price first and refuses above MAX_HOURLY_USD.
How to stop spending: the script destroys the server in a `finally` block. If you kill it with kill -9 or lose
  power, run `apidly servers` and `apidly destroy SERVER_ID --yes`. The server also stops itself after MAX_HOURS.

Needs Python 3.9+, `pip install ./apidly-VERSION-py3-none-any.whl`, the `ssh` command, APIDLY_API_KEY (Servers scope),
SSH_KEY_ID (from `apidly ssh-keys`) and PLAN_ID (from `apidly plans --available --sort price`).
  PLAN_ID=... SSH_KEY_ID=... MAX_HOURLY_USD=<your limit> python run_script_and_fetch_result.py
"""
import os
import subprocess
import sys
import time

from apidly import Client

for name in ("PLAN_ID", "SSH_KEY_ID", "MAX_HOURLY_USD"):
    if not os.environ.get(name):
        sys.exit(f"Set {name} first (see the comment at the top of this file).")
script = os.environ.get("SCRIPT", "job.sh")
result_file = os.environ.get("RESULT", "result.txt")
poll = float(os.environ.get("POLL_SECONDS", "10"))

client = Client(api_key=os.environ["APIDLY_API_KEY"])
template = client.templates.get(os.environ.get("TEMPLATE", "pytorch"))["template"]
request = dict(
    plan_id=os.environ["PLAN_ID"],
    template_id=template["id"],
    label="run-script",
    disk_gb=template["defaultDiskGb"],
    ssh_key_ids=[os.environ["SSH_KEY_ID"]],
    automation={"maxRuntimeHours": float(os.environ.get("MAX_HOURS", "2"))},
)

quote = client.servers.estimate(**request)["quote"]
if quote["blockers"] or float(quote["totalHourlyUsd"]) > float(os.environ["MAX_HOURLY_USD"]):
    sys.exit(f"Not started: {quote['totalHourlyUsd']} USD per hour {quote['blockers']}")

created = client.servers.create(**request)
server, deployment = created["server"], created["deployment"]
try:
    while server is None:
        if deployment["status"] in ("rejected", "failed", "cancelled"):
            raise RuntimeError(f"Request {deployment['id']} was {deployment['status']}")
        time.sleep(poll)
        deployment = client.deployments.get(deployment["id"])["deployment"]
        if deployment.get("serverId"):
            server = client.servers.get(deployment["serverId"])["server"]
    while server["status"] != "running":
        if server["status"] in ("error", "destroyed", "suspended", "interrupted"):
            raise RuntimeError(f"Server {server['id']} is {server['status']}: {server.get('statusMessage') or ''}")
        time.sleep(poll)
        server = client.servers.get(server["id"])["server"]

    # The SSH service can need a little longer than the server; try a few times.
    ssh = server["connection"]["ssh"]
    args = ["ssh", "-p", str(ssh["port"]), "-o", "StrictHostKeyChecking=accept-new", "-o", "ConnectTimeout=15",
            f"{ssh['user']}@{ssh['host']}", "bash -s"]
    code = 255
    for attempt in range(5):
        with open(script, "rb") as stdin, open(result_file, "wb") as stdout:
            code = subprocess.run(args, stdin=stdin, stdout=stdout).returncode
        if code != 255:
            break
        time.sleep(poll)
    print(f"{script} exited with {code}; its output is in {result_file}")
finally:
    if server is not None:
        client.servers.delete(server["id"])
        print(f"Destroyed {server['id']}.")
    else:
        try:
            client.deployments.cancel(deployment["id"])
        except Exception:
            pass
sys.exit(code)

Shell · examples/shell/run-script-and-fetch-result.sh

#!/usr/bin/env bash
# Run a local script on a new GPU server, save what it prints to a file, then destroy the server.
#
# What it does: prices a server of PLAN (a slug from `apidly plans`) and TEMPLATE (default pytorch) with a dry run,
#   creates it with your SSH key and waits until it runs, sends SCRIPT (default job.sh) to it over SSH, writes what the
#   script prints to RESULT (default result.txt) and destroys the server, also when the script fails.
# What it costs: the server's hourly price (compute plus disk), by the second, from the moment it runs until it is
#   destroyed a few seconds after the script ends. The dry run prints the price first and refuses above MAX_HOURLY_USD.
# How to stop spending: a trap destroys the server when the script exits, on errors and Ctrl-C too. If it is killed
#   with kill -9, run `apidly servers` and `apidly destroy SERVER_ID --yes`. It also stops itself after MAX_HOURS.
#
# Needs bash, jq, ssh, the apidly CLI, APIDLY_API_KEY (Servers scope), SSH_KEY_ID (from `apidly ssh-keys`) and PLAN.
#   PLAN=... SSH_KEY_ID=... MAX_HOURLY_USD=<your limit> ./run-script-and-fetch-result.sh
set -euo pipefail

: "${PLAN:?Set PLAN to a plan slug (see apidly plans --available --sort price)}"
: "${SSH_KEY_ID:?Set SSH_KEY_ID (see apidly ssh-keys)}"
: "${MAX_HOURLY_USD:?Set MAX_HOURLY_USD to the most you will pay per hour}"
SCRIPT="${SCRIPT:-job.sh}"
RESULT="${RESULT:-result.txt}"
POLL_SECONDS="${POLL_SECONDS:-10}"

quote=$(apidly deploy --plan "$PLAN" --template "${TEMPLATE:-pytorch}" --ssh-key "$SSH_KEY_ID" \
  --label run-script --dry-run --json | jq '.quote')
echo "$(jq -r '.totalHourlyUsd' <<<"$quote") USD per hour while running"
if jq -e --argjson max "$MAX_HOURLY_USD" '(.blockers | length) > 0 or (.totalHourlyUsd | tonumber) > $max' \
  <<<"$quote" >/dev/null; then
  echo "Not started." >&2
  exit 1
fi

# The runtime limit rides with the request (a launch file on stdin), and the clean-up trap is set right after the
# request exists, before anything else can fail: a request still waiting is cancelled, a server is destroyed, also one
# that never comes up.
launch=$(jq -n --arg plan "$PLAN" --arg template "${TEMPLATE:-pytorch}" --argjson hours "${MAX_HOURS:-2}" \
  '{planId: $plan, templateId: $template, automation: {maxRuntimeHours: $hours}}')
created=$(apidly deploy -f - --ssh-key "$SSH_KEY_ID" --label run-script --yes --json <<<"$launch")
request=$(jq -r '.deployment.id' <<<"$created")
id=$(jq -r '.server.id // empty' <<<"$created")
cleanup() {
  if [ -n "$id" ]; then
    apidly destroy "$id" --yes >/dev/null && echo "Destroyed $id."
  else
    apidly deployments cancel "$request" >/dev/null 2>&1 || true
  fi
}
trap cleanup EXIT

# Wait for the server (an approval wait included), then until it runs.
while [ -z "$id" ]; do
  sleep "$POLL_SECONDS"
  deployment=$(apidly deployments show "$request" --json | jq '.deployment')
  case "$(jq -r '.status' <<<"$deployment")" in
  rejected | failed | cancelled)
    echo "Request $request was $(jq -r '.status' <<<"$deployment")." >&2
    exit 1
    ;;
  esac
  id=$(jq -r '.serverId // empty' <<<"$deployment")
done
while :; do
  status=$(apidly servers show "$id" --json | jq -r '.server.status')
  [ "$status" = running ] && break
  case "$status" in
  error | destroyed | suspended | interrupted)
    echo "Server $id is $status." >&2
    exit 1
    ;;
  esac
  sleep "$POLL_SECONDS"
done

ssh_info=$(apidly servers show "$id" --json | jq '.server.connection.ssh')
target="$(jq -r '.user' <<<"$ssh_info")@$(jq -r '.host' <<<"$ssh_info")"
port=$(jq -r '.port' <<<"$ssh_info")

# The SSH service can need a little longer than the server; try a few times.
code=255
for _ in 1 2 3 4 5; do
  code=0
  ssh -p "$port" -o StrictHostKeyChecking=accept-new -o ConnectTimeout=15 "$target" 'bash -s' \
    <"$SCRIPT" >"$RESULT" || code=$?
  [ "$code" -ne 255 ] && break
  sleep "$POLL_SECONDS"
done
echo "$SCRIPT exited with $code; its output is in $RESULT"
exit "$code"

Parar todos os servidores quando o saldo ficar baixo

Lê o saldo a cada cinco minutos e para todos os servidores em execução assim que ele fica abaixo de MIN_BALANCE_USD. Com --once verifica uma única vez, para cron. Servidores parados continuam pagando pelos discos.

JavaScript · examples/node/stop-all-below-balance.mjs

// Watch the balance and stop every running server when it falls below a threshold.
//
// What it does: reads the balance every INTERVAL_SECONDS (default 300). When it is below MIN_BALANCE_USD, it stops
//   every server that is running or starting and exits. With --once it checks one time, for cron.
// What it costs: nothing; it only reads, and stopping is free. Stopped servers still pay for their disks.
// How to stop spending: this script is the stop. To end the disk charges too, destroy what you no longer need:
//   `apidly destroy SERVER_ID --yes`.
//
// Needs Node 18+, `npm install ./apidly-sdk-VERSION.tgz` and APIDLY_API_KEY with the Servers scope.
//   MIN_BALANCE_USD=<amount> node stop-all-below-balance.mjs [--once]
import { Apidly } from "@apidly/sdk";

const env = process.env;
const threshold = Number(env.MIN_BALANCE_USD);
if (!(threshold >= 0) || env.MIN_BALANCE_USD === undefined) {
  console.error(
    "Set MIN_BALANCE_USD, the balance in US dollars below which every server is stopped."
  );
  process.exit(2);
}
const once = process.argv.includes("--once");
const intervalMs = Number(env.INTERVAL_SECONDS ?? 300) * 1000;

const apidly = new Apidly({ apiKey: env.APIDLY_API_KEY });

while (true) {
  const { balance } = await apidly.billing.balance();
  console.log(
    `${new Date().toISOString()} balance ${balance.balanceUsd} USD, burning ${balance.burnPerHourUsd} USD/h`
  );
  if (Number(balance.balanceUsd) < threshold) {
    // Collect first, then stop: iter follows every page, so no server is missed however many you have.
    const servers = [];
    for await (const server of apidly.servers.iter({
      status: ["provisioning", "starting", "running"],
    })) {
      servers.push(server);
    }
    let stopped = 0;
    for (const server of servers) {
      try {
        await apidly.servers.stop(server.id);
        stopped++;
        console.log(`Stopped ${server.id} (${server.label})`);
      } catch (err) {
        console.error(`Could not stop ${server.id}: ${err.message}`);
        process.exitCode = 1;
      }
    }
    console.log(
      `Balance below ${threshold} USD: stopped ${stopped} server(s).`
    );
    break;
  }
  if (once) {
    break;
  }
  await new Promise((r) => setTimeout(r, intervalMs));
}

Python · examples/python/stop_all_below_balance.py

"""Watch the balance and stop every running server when it falls below a threshold.

What it does: reads the balance every INTERVAL_SECONDS (default 300). When it is below MIN_BALANCE_USD, it stops
  every server that is running or starting and exits. With --once it checks one time, for cron.
What it costs: nothing; it only reads, and stopping is free. Stopped servers still pay for their disks.
How to stop spending: this script is the stop. To end the disk charges too, destroy what you no longer need:
  `apidly destroy SERVER_ID --yes`.

Needs Python 3.9+, `pip install ./apidly-VERSION-py3-none-any.whl` and APIDLY_API_KEY with the Servers scope.
  MIN_BALANCE_USD=<amount> python stop_all_below_balance.py [--once]
"""
import datetime
import os
import sys
import time

from apidly import ApiError, Client

if os.environ.get("MIN_BALANCE_USD") is None:
    sys.exit("Set MIN_BALANCE_USD, the balance in US dollars below which every server is stopped.")
threshold = float(os.environ["MIN_BALANCE_USD"])
once = "--once" in sys.argv
interval = float(os.environ.get("INTERVAL_SECONDS", "300"))

client = Client(api_key=os.environ["APIDLY_API_KEY"])
failed = False

while True:
    balance = client.billing.balance()["balance"]
    now = datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds")
    print(f"{now} balance {balance['balanceUsd']} USD, burning {balance['burnPerHourUsd']} USD/h")
    if float(balance["balanceUsd"]) < threshold:
        # Collect first, then stop: iter follows every page, so no server is missed however many you have.
        servers = list(client.servers.iter(status=["provisioning", "starting", "running"]))
        stopped = 0
        for server in servers:
            try:
                client.servers.stop(server["id"])
                stopped += 1
                print(f"Stopped {server['id']} ({server['label']})")
            except ApiError as err:
                print(f"Could not stop {server['id']}: {err}", file=sys.stderr)
                failed = True
        print(f"Balance below {threshold} USD: stopped {stopped} server(s).")
        break
    if once:
        break
    time.sleep(interval)

sys.exit(1 if failed else 0)

Shell · examples/shell/stop-all-below-balance.sh

#!/usr/bin/env bash
# Watch the balance and stop every running server when it falls below a threshold.
#
# What it does: checks the balance every INTERVAL_SECONDS (default 300). When it is below MIN_BALANCE_USD, it stops
#   every server that is running or starting and exits. With --once it checks one time, for cron:
#   0 * * * * APIDLY_API_KEY=... MIN_BALANCE_USD=<amount> /path/to/stop-all-below-balance.sh --once
# What it costs: nothing; it only reads, and stopping is free. Stopped servers still pay for their disks.
# How to stop spending: this script is the stop. To end the disk charges too, destroy what you no longer need:
#   `apidly destroy SERVER_ID --yes`.
#
# Needs bash, jq, the apidly CLI and APIDLY_API_KEY with the Servers scope.
#   MIN_BALANCE_USD=<amount> ./stop-all-below-balance.sh [--once]
set -uo pipefail

: "${MIN_BALANCE_USD:?Set MIN_BALANCE_USD, the balance in US dollars below which every server is stopped}"
INTERVAL_SECONDS="${INTERVAL_SECONDS:-300}"

while :; do
  # Exit code 0: at or above the amount, 3: below it, anything else: the check itself failed.
  apidly balance --below "$MIN_BALANCE_USD" >/dev/null
  status=$?
  if [ "$status" -eq 3 ]; then
    # --all follows every page, so no server is missed however many you have.
    # A failed list must not read as "nothing is running": say so and exit non-zero instead.
    if ! ids=$(apidly servers --status provisioning,starting,running --all --json | jq -r '.servers[].id'); then
      echo "Balance below $MIN_BALANCE_USD USD, but the server list could not be read. Nothing was stopped." >&2
      exit 1
    fi
    failed=0
    for id in $ids; do
      apidly stop "$id" >/dev/null && echo "Stopped $id" || failed=1
    done
    echo "Balance below $MIN_BALANCE_USD USD: stopped every running server."
    exit "$failed"
  elif [ "$status" -ne 0 ]; then
    echo "Balance check failed with exit code $status" >&2
  fi
  [ "${1:-}" = "--once" ] && exit "$status"
  sleep "$INTERVAL_SECONDS"
done

Salvar um servidor como template e iniciar a partir dele

Salva um servidor que você configurou como template próprio, lista os segredos que você precisa preencher de novo (os valores nunca são copiados) e, após verificar o preço, inicia um novo servidor do mesmo plano a partir do template.

JavaScript · examples/node/save-server-as-template.mjs

// Save a server you set up as your own template, then launch a new server from that template.
//
// What it does: saves SERVER_ID (image, start command, ports, variables) as a template named TEMPLATE_NAME, lists the
//   secret values you must fill in again, prices a new server of the same plan with a dry run and creates it when it
//   costs at most MAX_HOURLY_USD per hour. The new server stops on its own after MAX_HOURS (default 2) hours.
// What it costs: saving a template is free. The new server is billed by the second at the printed hourly price.
// How to stop spending: `apidly destroy NEW_SERVER_ID --yes`. The original server keeps running and billing until
//   you stop or destroy it too. Delete the template with `apidly templates rm TEMPLATE_ID` (free to keep).
//
// Needs Node 18+, `npm install ./apidly-sdk-VERSION.tgz` and APIDLY_API_KEY with the Servers scope. SSH_KEY_ID (from
// `apidly ssh-keys`) puts your key on the new server; a template you connect to over SSH needs one.
//   SERVER_ID=ins_... SSH_KEY_ID=... TEMPLATE_NAME=my-setup MAX_HOURLY_USD=<your limit> node save-server-as-template.mjs
import { Apidly } from "@apidly/sdk";

const env = process.env;
for (const name of ["SERVER_ID", "TEMPLATE_NAME", "MAX_HOURLY_USD"]) {
  if (!env[name]) {
    console.error(
      `Set ${name} first (see the comment at the top of this file).`
    );
    process.exit(2);
  }
}

const apidly = new Apidly({ apiKey: env.APIDLY_API_KEY });

const { server: source } = await apidly.servers.get(env.SERVER_ID);
const saved = await apidly.servers.saveAsTemplate(source.id, {
  name: env.TEMPLATE_NAME,
  summary: `Saved from ${source.label}`,
});
console.log(`Saved template ${saved.template.id} (${saved.template.name}).`);
if (saved.secretsToFill.length > 0) {
  console.log(
    `Secret values are never copied. Fill these in on the template: ${saved.secretsToFill.join(", ")}`
  );
}

const request = {
  planId: source.planId,
  templateId: saved.template.id,
  label: `${env.TEMPLATE_NAME}-copy`,
  diskGb: source.diskGb,
  sshKeyIds: env.SSH_KEY_ID ? [env.SSH_KEY_ID] : [],
  automation: { maxRuntimeHours: Number(env.MAX_HOURS ?? 2) },
};
const { quote } = await apidly.servers.estimate(request);
console.log(
  `A new server would cost ${quote.totalHourlyUsd} USD per hour while running.`
);
if (
  quote.blockers.length > 0 ||
  Number(quote.totalHourlyUsd) > Number(env.MAX_HOURLY_USD)
) {
  console.error(
    "Not launched:",
    quote.blockers.map((b) => b.message).join("; ") || "over MAX_HOURLY_USD"
  );
  process.exit(1);
}
const { server, deployment } = await apidly.servers.create(request);
console.log(
  server
    ? `Launched ${server.id} from the template. Stop spending: apidly destroy ${server.id} --yes`
    : `Request ${deployment.id} is ${deployment.status}; it starts once approved.`
);

Python · examples/python/save_server_as_template.py

"""Save a server you set up as your own template, then launch a new server from that template.

What it does: saves SERVER_ID (image, start command, ports, variables) as a template named TEMPLATE_NAME, lists the
  secret values you must fill in again, prices a new server of the same plan with a dry run and creates it when it
  costs at most MAX_HOURLY_USD per hour. The new server stops on its own after MAX_HOURS (default 2) hours.
What it costs: saving a template is free. The new server is billed by the second at the printed hourly price.
How to stop spending: `apidly destroy NEW_SERVER_ID --yes`. The original server keeps running and billing until
  you stop or destroy it too. Delete the template with `apidly templates rm TEMPLATE_ID` (free to keep).

Needs Python 3.9+, `pip install ./apidly-VERSION-py3-none-any.whl` and APIDLY_API_KEY with the Servers scope. SSH_KEY_ID
(from `apidly ssh-keys`) puts your key on the new server; a template you connect to over SSH needs one.
  SERVER_ID=ins_... SSH_KEY_ID=... TEMPLATE_NAME=my-setup MAX_HOURLY_USD=<your limit> python save_server_as_template.py
"""
import os
import sys

from apidly import Client

for name in ("SERVER_ID", "TEMPLATE_NAME", "MAX_HOURLY_USD"):
    if not os.environ.get(name):
        sys.exit(f"Set {name} first (see the comment at the top of this file).")
name = os.environ["TEMPLATE_NAME"]

client = Client(api_key=os.environ["APIDLY_API_KEY"])

source = client.servers.get(os.environ["SERVER_ID"])["server"]
saved = client.servers.save_as_template(source["id"], name=name, summary=f"Saved from {source['label']}")
template = saved["template"]
print(f"Saved template {template['id']} ({template['name']}).")
if saved["secretsToFill"]:
    print("Secret values are never copied. Fill these in on the template: " + ", ".join(saved["secretsToFill"]))

request = dict(
    plan_id=source["planId"],
    template_id=template["id"],
    label=f"{name}-copy",
    disk_gb=source["diskGb"],
    ssh_key_ids=[os.environ["SSH_KEY_ID"]] if os.environ.get("SSH_KEY_ID") else [],
    automation={"maxRuntimeHours": float(os.environ.get("MAX_HOURS", "2"))},
)
quote = client.servers.estimate(**request)["quote"]
print(f"A new server would cost {quote['totalHourlyUsd']} USD per hour while running.")
if quote["blockers"] or float(quote["totalHourlyUsd"]) > float(os.environ["MAX_HOURLY_USD"]):
    sys.exit("Not launched: " + ("; ".join(b["message"] for b in quote["blockers"]) or "over MAX_HOURLY_USD"))
created = client.servers.create(**request)
if created["server"]:
    server_id = created["server"]["id"]
    print(f"Launched {server_id} from the template. Stop spending: apidly destroy {server_id} --yes")
else:
    print(f"Request {created['deployment']['id']} is {created['deployment']['status']}; it starts once approved.")

Shell · examples/shell/save-server-as-template.sh

#!/usr/bin/env bash
# Save a server you set up as your own template, then launch a new server from that template.
#
# What it does: saves SERVER_ID (image, start command, ports, variables) as a template named TEMPLATE_NAME, lists the
#   secret values you must fill in again, prices a new server of the same plan with a dry run and creates it when it
#   costs at most MAX_HOURLY_USD per hour. The new server stops on its own after MAX_HOURS (default 2) hours.
# What it costs: saving a template is free. The new server is billed by the second at the printed hourly price.
# How to stop spending: `apidly destroy NEW_SERVER_ID --yes`. The original server keeps running and billing until
#   you stop or destroy it too. Delete the template with `apidly templates rm TEMPLATE_ID` (free to keep).
#
# Needs bash, jq, the apidly CLI and APIDLY_API_KEY with the Servers scope. SSH_KEY_ID (from `apidly ssh-keys`) puts
# your key on the new server; a template you connect to over SSH needs one.
#   SERVER_ID=ins_... SSH_KEY_ID=... TEMPLATE_NAME=my-setup MAX_HOURLY_USD=<your limit> ./save-server-as-template.sh
set -euo pipefail

: "${SERVER_ID:?Set SERVER_ID (see apidly servers)}"
: "${TEMPLATE_NAME:?Set TEMPLATE_NAME, the name of the new template}"
: "${MAX_HOURLY_USD:?Set MAX_HOURLY_USD to the most you will pay per hour}"

source_server=$(apidly servers show "$SERVER_ID" --json | jq '.server')
saved=$(apidly templates save "$SERVER_ID" --name "$TEMPLATE_NAME" --json)
template_id=$(jq -r '.template.id' <<<"$saved")
echo "Saved template $template_id ($TEMPLATE_NAME)."
if [ "$(jq '.secretsToFill | length' <<<"$saved")" -gt 0 ]; then
  echo "Secret values are never copied. Fill these in on the template: $(jq -r '.secretsToFill | join(", ")' <<<"$saved")"
fi

plan=$(jq -r '.planId' <<<"$source_server")
disk=$(jq -r '.diskGb' <<<"$source_server")
quote=$(apidly deploy --plan "$plan" --template "$template_id" --disk "$disk" --label "$TEMPLATE_NAME-copy" \
  ${SSH_KEY_ID:+--ssh-key "$SSH_KEY_ID"} --dry-run --json | jq '.quote')
echo "A new server would cost $(jq -r '.totalHourlyUsd' <<<"$quote") USD per hour while running."
if jq -e --argjson max "$MAX_HOURLY_USD" '(.blockers | length) > 0 or (.totalHourlyUsd | tonumber) > $max' \
  <<<"$quote" >/dev/null; then
  echo "Not launched." >&2
  exit 1
fi
new_id=$(apidly deploy --plan "$plan" --template "$template_id" --disk "$disk" --label "$TEMPLATE_NAME-copy" \
  ${SSH_KEY_ID:+--ssh-key "$SSH_KEY_ID"} --yes --json | jq -r '.server.id // empty')
if [ -n "$new_id" ]; then
  apidly automation set "$new_id" --max-runtime-hours "${MAX_HOURS:-2}" >/dev/null
  echo "Launched $new_id from the template. Stop spending: apidly destroy $new_id --yes"
else
  echo "The request waits for approval; see apidly deployments."
fi

Uso por servidor e por chave de API em CSV

Grava usage-by-server.csv e usage-by-api-key.csv do mês atual, ou de FROM até TO. Ele só lê, então basta uma chave Read only.

JavaScript · examples/node/usage-report-csv.mjs

// Write what you were charged, per server and per API key, to two CSV files for a spreadsheet.
//
// What it does: reads the usage from FROM to TO (default: the current UTC month; TO is exclusive), grouped by server and
//   grouped by API key, following every page, and writes usage-by-server.csv and usage-by-api-key.csv.
// What it costs: nothing; it only reads. A key with the Read only scope is enough.
// How to stop spending: nothing is started. To see what is still running: `apidly servers --status running`.
//
// Needs Node 18+, `npm install ./apidly-sdk-VERSION.tgz` and APIDLY_API_KEY.
//   FROM=2026-11-01 TO=2026-12-01 node usage-report-csv.mjs
import { writeFileSync } from "node:fs";
import { Apidly } from "@apidly/sdk";

const env = process.env;
const range = { from: env.FROM, to: env.TO };

const apidly = new Apidly({ apiKey: env.APIDLY_API_KEY });

/** A CSV cell, quoted when it holds a comma, quote or line break. */
const cell = (v) => {
  const s = String(v ?? "");
  return /[",\n\r]/.test(s) ? `"${s.replaceAll('"', '""')}"` : s;
};
/** A name you typed: a leading = + - @ would run as a formula in a spreadsheet, so it gets a ' in front. */
const text = (v) => (/^[=+\-@]/.test(String(v ?? "")) ? `'${v}` : v);

async function report(groupBy, file) {
  const lines = [
    ["id", "name", "compute_usd", "disk_usd", "volume_usd", "total_usd"].join(
      ","
    ),
  ];
  let total = 0;
  for await (const row of apidly.billing.iterUsage({ groupBy, ...range })) {
    lines.push(
      [
        row.key,
        text(row.label),
        row.computeUsd,
        row.storageUsd,
        row.volumeUsd,
        row.totalUsd,
      ]
        .map(cell)
        .join(",")
    );
    total += Number(row.totalUsd);
  }
  writeFileSync(file, `${lines.join("\n")}\n`);
  console.log(`${file}: ${lines.length - 1} rows, ${total.toFixed(2)} USD`);
}

await report("instance", "usage-by-server.csv");
await report("apiKey", "usage-by-api-key.csv");

Python · examples/python/usage_report_csv.py

"""Write what you were charged, per server and per API key, to two CSV files for a spreadsheet.

What it does: reads the usage from FROM to TO (default: the current UTC month; TO is exclusive), grouped by server and
  grouped by API key, following every page, and writes usage-by-server.csv and usage-by-api-key.csv.
What it costs: nothing; it only reads. A key with the Read only scope is enough.
How to stop spending: nothing is started. To see what is still running: `apidly servers --status running`.

Needs Python 3.9+, `pip install ./apidly-VERSION-py3-none-any.whl` and APIDLY_API_KEY.
  FROM=2026-11-01 TO=2026-12-01 python usage_report_csv.py
"""
import csv
import os
from decimal import Decimal

from apidly import Client

client = Client(api_key=os.environ["APIDLY_API_KEY"])
date_from = os.environ.get("FROM")
date_to = os.environ.get("TO")


def text(value):
    """A name you typed: a leading = + - @ would run as a formula in a spreadsheet, so it gets a ' in front."""
    value = value or ""
    return "'" + value if value[:1] in ("=", "+", "-", "@") else value


def report(group_by, path):
    total = Decimal(0)
    rows = 0
    with open(path, "w", newline="", encoding="utf-8") as f:
        out = csv.writer(f)
        out.writerow(["id", "name", "compute_usd", "disk_usd", "volume_usd", "total_usd"])
        # iter_usage follows nextCursor across every page.
        for row in client.billing.iter_usage(group_by=group_by, from_=date_from, to=date_to):
            out.writerow([row["key"], text(row.get("label")), row["computeUsd"], row["storageUsd"],
                          row["volumeUsd"], row["totalUsd"]])
            total += Decimal(row["totalUsd"])
            rows += 1
    print(f"{path}: {rows} rows, {total:.2f} USD")


report("instance", "usage-by-server.csv")
report("apiKey", "usage-by-api-key.csv")

Shell · examples/shell/usage-report-csv.sh

#!/usr/bin/env bash
# Write what you were charged, per server and per API key, to two CSV files for a spreadsheet.
#
# What it does: downloads the usage from FROM to TO (default: the current UTC month; TO is exclusive) as CSV, once
#   grouped by server (usage-by-server.csv) and once grouped by API key (usage-by-api-key.csv).
# What it costs: nothing; it only reads. A key with the Read only scope is enough.
# How to stop spending: nothing is started. To see what is still running: `apidly servers --status running`.
#
# Needs bash, curl, the apidly CLI and APIDLY_API_KEY.
#   FROM=2026-11-01 TO=2026-12-01 ./usage-report-csv.sh
set -euo pipefail

BASE="${APIDLY_API_URL:-https://apidly.com}"
range=()
[ -n "${FROM:-}" ] && range+=(--from "$FROM")
[ -n "${TO:-}" ] && range+=(--to "$TO")

# Per server, with the CLI.
apidly export usage --group-by instance "${range[@]+"${range[@]}"}" --out usage-by-server.csv

# Per API key, the same file straight from the API with curl (`apidly export usage --group-by apiKey` works too).
curl -fsS -G "$BASE/api/v1/billing/export" -H "Authorization: Bearer $APIDLY_API_KEY" \
  --data-urlencode kind=usage --data-urlencode groupBy=apiKey \
  ${FROM:+--data-urlencode "from=$FROM"} ${TO:+--data-urlencode "to=$TO"} -o usage-by-api-key.csv
echo "Wrote usage-by-api-key.csv"

Receber webhooks e verificar a assinatura

Um receptor sem framework. Ele confere o cabeçalho Apidly-Signature com o corpo bruto, recusa tudo que não for assinado, tiver sido alterado ou tiver mais de cinco minutos, e ignora um evento que já viu. Os eventos e o conteúdo estão em Webhooks.

JavaScript · examples/node/webhook-receiver.mjs

// Receive webhook events and accept only the ones that carry a valid signature. Uses only Node's own http module.
//
// What it does: listens on PORT (default 8080) for POST requests, checks the Apidly-Signature header against the raw
//   body with your signing secret, answers 401 to anything unsigned, too old or altered, ignores repeats of an event
//   it has already seen and prints each event. Add your own handling where it says so.
// What it costs: nothing on our side; deliveries are free. You run the receiver on your own machine or server.
// How to stop spending: nothing is started. Stop the receiver with Ctrl-C; remove the webhook with
//   `apidly webhooks rm WEBHOOK_ID --yes`.
//
// Needs Node 18+, `npm install ./apidly-sdk-VERSION.tgz` and APIDLY_WEBHOOK_SECRET, the signing secret shown once when
// you add the webhook (`apidly webhooks add https://YOUR-HOST/ --events balance.low,server.stopped`). The address must
// be reachable from the internet over HTTPS, for example behind a reverse proxy.
//   APIDLY_WEBHOOK_SECRET=... node webhook-receiver.mjs
import { createServer } from "node:http";
import { verifyWebhook } from "@apidly/sdk";

const secret = process.env.APIDLY_WEBHOOK_SECRET;
if (!secret) {
  console.error("Set APIDLY_WEBHOOK_SECRET to the webhook's signing secret.");
  process.exit(2);
}
const port = Number(process.env.PORT ?? 8080);
const MAX_BODY = 1024 * 1024;
/** Event ids already handled: the same event can be delivered more than once. Use a database in production. */
const seen = new Set();

const server = createServer((req, res) => {
  if (req.method !== "POST") {
    res.writeHead(405).end();
    return;
  }
  const chunks = [];
  let size = 0;
  req.on("data", (chunk) => {
    size += chunk.length;
    if (size > MAX_BODY) {
      res.writeHead(413).end();
      req.destroy();
      return;
    }
    chunks.push(chunk);
  });
  req.on("end", () => {
    if (res.writableEnded) {
      return;
    }
    // Verify the RAW bytes, before any JSON parsing: re-encoded JSON would not match the signature.
    const raw = Buffer.concat(chunks);
    if (
      !verifyWebhook(
        new Uint8Array(raw),
        req.headers["apidly-signature"] ?? "",
        secret
      )
    ) {
      res.writeHead(401).end("bad signature");
      return;
    }
    const event = JSON.parse(raw.toString("utf8"));
    if (seen.has(event.id)) {
      res.writeHead(200).end("duplicate");
      return;
    }
    seen.add(event.id);
    // Answer quickly; do slow work after answering.
    res.writeHead(200).end("ok");
    console.log(`${event.createdAt} ${event.type} ${event.id}`);
    if (event.type === "balance.low") {
      // Your handling here, for example: notify someone, or stop servers (see stop-all-below-balance.mjs).
      console.log(`Balance is low: ${event.data?.balance?.usd} USD left`);
    }
  });
});

server.listen(port, () => console.log(`Listening on port ${port}`));

Python · examples/python/webhook_receiver.py

"""Receive webhook events and accept only the ones that carry a valid signature. Uses only Python's standard library.

What it does: listens on PORT (default 8080) for POST requests, checks the Apidly-Signature header against the raw
  body with your signing secret, answers 401 to anything unsigned, too old or altered, ignores repeats of an event
  it has already seen and prints each event. Add your own handling where it says so.
What it costs: nothing on our side; deliveries are free. You run the receiver on your own machine or server.
How to stop spending: nothing is started. Stop the receiver with Ctrl-C; remove the webhook with
  `apidly webhooks rm WEBHOOK_ID --yes`.

Needs Python 3.9+, `pip install ./apidly-VERSION-py3-none-any.whl` and APIDLY_WEBHOOK_SECRET, the signing secret shown
once when you add the webhook (`apidly webhooks add https://YOUR-HOST/ --events balance.low,server.stopped`). The
address must be reachable from the internet over HTTPS, for example behind a reverse proxy.
  APIDLY_WEBHOOK_SECRET=... python webhook_receiver.py
"""
import json
import os
import sys
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

from apidly import verify_webhook

SECRET = os.environ.get("APIDLY_WEBHOOK_SECRET")
if not SECRET:
    sys.exit("Set APIDLY_WEBHOOK_SECRET to the webhook's signing secret.")
PORT = int(os.environ.get("PORT", "8080"))
MAX_BODY = 1024 * 1024
# Event ids already handled: the same event can be delivered more than once. Use a database in production.
seen = set()


class Receiver(BaseHTTPRequestHandler):
    def answer(self, status, text=""):
        self.send_response(status)
        self.send_header("Content-Type", "text/plain")
        self.end_headers()
        self.wfile.write(text.encode())

    def do_POST(self):
        length = int(self.headers.get("Content-Length") or 0)
        if length > MAX_BODY:
            self.answer(413)
            return
        # Verify the RAW bytes, before any JSON parsing: re-encoded JSON would not match the signature.
        raw = self.rfile.read(length)
        if not verify_webhook(raw, self.headers.get("Apidly-Signature", ""), SECRET):
            self.answer(401, "bad signature")
            return
        event = json.loads(raw)
        if event["id"] in seen:
            self.answer(200, "duplicate")
            return
        seen.add(event["id"])
        # Answer quickly; do slow work after answering.
        self.answer(200, "ok")
        print(f"{event['createdAt']} {event['type']} {event['id']}", flush=True)
        if event["type"] == "balance.low":
            # Your handling here, for example: notify someone, or stop servers (see stop_all_below_balance.py).
            print(f"Balance is low: {event['data']['balance']['usd']} USD left", flush=True)

    def log_message(self, *args):
        pass  # keep the output to the events


print(f"Listening on port {PORT}", flush=True)
ThreadingHTTPServer(("", PORT), Receiver).serve_forever()

Serverless: criar um endpoint, rodar um job, escalar a zero

Requer endpoints serverless na sua conta e um template para uma imagem que rode o kit de worker (veja Seu primeiro endpoint com seu próprio código). Cria um endpoint com 0 a 1 worker e um teto de gasto por hora, envia um job, mostra o progresso e o resultado e depois pausa o endpoint para que nenhum worker continue rodando.

JavaScript · examples/node/serverless-job.mjs

// Serverless: create an endpoint from your worker image, send it one job, follow its progress, print the result and
// scale back to zero. Needs the serverless feature on your account (the Endpoints page says when it is not).
//
// What it does: creates an endpoint named NAME (default example-worker) from TEMPLATE_ID, a template for an image that
//   runs the worker kit (see https://apidly.com/docs/tutorial-serverless-worker), on the cheapest plan in stock with
//   enough GPU memory, with 0 to 1 workers and an hourly spending cap. It submits a job to JOB_PATH (default /hello)
//   with JOB_INPUT (JSON, default {"name":"Ada"}), prints the progress the handler reports, prints the result, then
//   pauses the endpoint so every worker is released.
// What it costs: no price per request. A worker is billed by the second at its plan's hourly price (printed below)
//   while it runs, including the cold start. MAX_HOURLY_USD caps what the endpoint may spend per hour.
// How to stop spending: the script pauses the endpoint at the end (a paused endpoint costs nothing). Delete it with
//   `apidly endpoints rm ENDPOINT_ID --yes`, or resume it with `apidly endpoints resume ENDPOINT_ID`.
//
// Needs Node 18+, `npm install ./apidly-sdk-VERSION.tgz` and APIDLY_API_KEY with the Servers scope.
//   TEMPLATE_ID=tpl_... MAX_HOURLY_USD=<your limit> node serverless-job.mjs
import { Apidly } from "@apidly/sdk";

const env = process.env;
for (const name of ["TEMPLATE_ID", "MAX_HOURLY_USD"]) {
  if (!env[name]) {
    console.error(
      `Set ${name} first (see the comment at the top of this file).`
    );
    process.exit(2);
  }
}
const pollSeconds = Number(env.POLL_SECONDS ?? 30);

const apidly = new Apidly({ apiKey: env.APIDLY_API_KEY });

const { template } = await apidly.templates.get(env.TEMPLATE_ID);
const { plans } = await apidly.plans.list({
  minVramGb: template.minVramGb,
  availability: "available",
  sort: "price",
  limit: 1,
});
if (!plans[0]) {
  console.error("No plan that fits the template is in stock right now.");
  process.exit(1);
}
console.log(
  `Workers run on ${plans[0].name} at ${plans[0].hourlyPriceUsd} USD per hour each, plus disk.`
);

const { endpoint } = await apidly.endpoints.create({
  name: env.NAME ?? "example-worker",
  planId: plans[0].id,
  templateId: template.id,
  jobMode: "kit",
  minWorkers: 0,
  maxWorkers: 1,
  idleSeconds: 300,
  maxHourlySpendUsd: Number(env.MAX_HOURLY_USD),
});
console.log(`Created endpoint ${endpoint.id}.`);

try {
  const { job } = await apidly.endpoints.createJob(endpoint.id, {
    path: env.JOB_PATH ?? "/hello",
    input: JSON.parse(env.JOB_INPUT ?? '{"name":"Ada"}'),
  });
  console.log(
    `Submitted job ${job.id}; the first worker can take several minutes to start.`
  );

  // Each call waits on our side up to waitSeconds for the job to end, so this loop makes few requests.
  let current = job;
  let lastProgress = "";
  while (["queued", "running"].includes(current.status)) {
    ({ job: current } = await apidly.endpoints.getJob(endpoint.id, job.id, {
      waitSeconds: pollSeconds,
    }));
    const progress = JSON.stringify(current.progress ?? null);
    if (progress !== lastProgress && current.progress != null) {
      console.log(`progress: ${progress}`);
      lastProgress = progress;
    }
  }
  console.log(
    `Job ${current.status}${current.errorCode ? ` (${current.errorCode})` : ""}.`
  );
  if (current.status === "succeeded") {
    console.log(
      typeof current.result === "string"
        ? current.result
        : JSON.stringify(current.result)
    );
  } else {
    process.exitCode = 1;
  }
} finally {
  // Scale to zero now instead of waiting for the idle timeout.
  await apidly.endpoints.pause(endpoint.id);
  console.log(
    `Paused ${endpoint.id}: no workers, nothing billed. Delete it: apidly endpoints rm ${endpoint.id} --yes`
  );
}

Python · examples/python/serverless_job.py

"""Serverless: create an endpoint from your worker image, send it one job, follow its progress, print the result and
scale back to zero. Needs the serverless feature on your account (the Endpoints page says when it is not).

What it does: creates an endpoint named NAME (default example-worker) from TEMPLATE_ID, a template for an image that
  runs the worker kit (see https://apidly.com/docs/tutorial-serverless-worker), on the cheapest plan in stock with
  enough GPU memory, with 0 to 1 workers and an hourly spending cap. It submits a job to JOB_PATH (default /hello)
  with JOB_INPUT (JSON, default {"name":"Ada"}), prints the progress the handler reports, prints the result, then
  pauses the endpoint so every worker is released.
What it costs: no price per request. A worker is billed by the second at its plan's hourly price (printed below)
  while it runs, including the cold start. MAX_HOURLY_USD caps what the endpoint may spend per hour.
How to stop spending: the script pauses the endpoint at the end (a paused endpoint costs nothing). Delete it with
  `apidly endpoints rm ENDPOINT_ID --yes`, or resume it with `apidly endpoints resume ENDPOINT_ID`.

Needs Python 3.9+, `pip install ./apidly-VERSION-py3-none-any.whl` and APIDLY_API_KEY with the Servers scope.
  TEMPLATE_ID=tpl_... MAX_HOURLY_USD=<your limit> python serverless_job.py
"""
import json
import os
import sys

from apidly import Client

for name in ("TEMPLATE_ID", "MAX_HOURLY_USD"):
    if not os.environ.get(name):
        sys.exit(f"Set {name} first (see the comment at the top of this file).")
poll = int(os.environ.get("POLL_SECONDS", "30"))

client = Client(api_key=os.environ["APIDLY_API_KEY"])

template = client.templates.get(os.environ["TEMPLATE_ID"])["template"]
plans = client.plans.list(
    min_vram_gb=template["minVramGb"], availability="available", sort="price", limit=1
)["plans"]
if not plans:
    sys.exit("No plan that fits the template is in stock right now.")
print(f"Workers run on {plans[0]['name']} at {plans[0]['hourlyPriceUsd']} USD per hour each, plus disk.")

endpoint = client.endpoints.create({
    "name": os.environ.get("NAME", "example-worker"),
    "planId": plans[0]["id"],
    "templateId": template["id"],
    "jobMode": "kit",
    "minWorkers": 0,
    "maxWorkers": 1,
    "idleSeconds": 300,
    "maxHourlySpendUsd": float(os.environ["MAX_HOURLY_USD"]),
})["endpoint"]
print(f"Created endpoint {endpoint['id']}.")

ok = False
try:
    job = client.endpoints.create_job(endpoint["id"], {
        "path": os.environ.get("JOB_PATH", "/hello"),
        "input": json.loads(os.environ.get("JOB_INPUT", '{"name":"Ada"}')),
    })["job"]
    print(f"Submitted job {job['id']}; the first worker can take several minutes to start.")

    # Each call waits on our side up to wait_seconds for the job to end, so this loop makes few requests.
    last_progress = None
    while job["status"] in ("queued", "running"):
        job = client.endpoints.get_job(endpoint["id"], job["id"], wait_seconds=poll)["job"]
        if job.get("progress") is not None and job["progress"] != last_progress:
            print(f"progress: {json.dumps(job['progress'])}")
            last_progress = job["progress"]
    print(f"Job {job['status']}" + (f" ({job['errorCode']})" if job.get("errorCode") else "") + ".")
    if job["status"] == "succeeded":
        result = job.get("result")
        print(result if isinstance(result, str) else json.dumps(result))
        ok = True
finally:
    # Scale to zero now instead of waiting for the idle timeout.
    client.endpoints.pause(endpoint["id"])
    print(f"Paused {endpoint['id']}: no workers, nothing billed. Delete it: apidly endpoints rm {endpoint['id']} --yes")

sys.exit(0 if ok else 1)

Shell · examples/shell/serverless-job.sh

#!/usr/bin/env bash
# Serverless: create an endpoint from your worker image, send it one job, follow its progress, print the result and
# scale back to zero. Needs the serverless feature on your account (the Endpoints page says when it is not).
#
# What it does: creates an endpoint named NAME (default example-worker) from TEMPLATE_ID, a template for an image that
#   runs the worker kit (see https://apidly.com/docs/tutorial-serverless-worker), on the cheapest plan in stock with
#   enough GPU memory, with 0 to 1 workers and an hourly spending cap. It submits a job to JOB_PATH (default /hello)
#   with JOB_INPUT (JSON, default {"name":"Ada"}), prints the progress the handler reports, prints the result, then
#   pauses the endpoint so every worker is released.
# What it costs: no price per request. A worker is billed by the second at its plan's hourly price (printed below)
#   while it runs, including the cold start. MAX_HOURLY_USD caps what the endpoint may spend per hour.
# How to stop spending: the script pauses the endpoint when it exits (a paused endpoint costs nothing). Delete it with
#   `apidly endpoints rm ENDPOINT_ID --yes`, or resume it with `apidly endpoints resume ENDPOINT_ID`.
#
# Needs bash, jq, the apidly CLI and APIDLY_API_KEY with the Servers scope.
#   TEMPLATE_ID=tpl_... MAX_HOURLY_USD=<your limit> ./serverless-job.sh
set -euo pipefail

: "${TEMPLATE_ID:?Set TEMPLATE_ID to your worker template (see apidly templates --own)}"
: "${MAX_HOURLY_USD:?Set MAX_HOURLY_USD, the most the endpoint may spend per hour}"
POLL_SECONDS="${POLL_SECONDS:-30}"

min_vram=$(apidly templates show "$TEMPLATE_ID" --json | jq -r '.template.minVramGb')
plan=$(apidly plans --min-vram "$min_vram" --available --sort price --limit 1 --json | jq '.plans[0]')
if [ "$plan" = "null" ]; then
  echo "No plan that fits the template is in stock right now." >&2
  exit 1
fi
echo "Workers run on $(jq -r '.name' <<<"$plan") at $(jq -r '.hourlyPriceUsd' <<<"$plan") USD per hour each, plus disk."

endpoint=$(apidly endpoints create --name "${NAME:-example-worker}" --plan "$(jq -r '.id' <<<"$plan")" \
  --template "$TEMPLATE_ID" --job-mode kit --min-workers 0 --max-workers 1 --idle-seconds 300 \
  --max-spend "$MAX_HOURLY_USD" --json | jq -r '.endpoint.id')
echo "Created endpoint $endpoint."
# Scale to zero when the script ends, whatever happens, instead of waiting for the idle timeout.
trap 'apidly endpoints pause "$endpoint" >/dev/null && echo "Paused $endpoint: no workers, nothing billed."' EXIT

job=$(apidly endpoints submit "$endpoint" "${JOB_PATH:-/hello}" -d "${JOB_INPUT:-{\"name\":\"Ada\"}}" --json |
  jq -r '.job.id')
echo "Submitted job $job; the first worker can take several minutes to start."

last=""
while :; do
  state=$(apidly endpoints job "$endpoint" "$job" --json | jq '.job')
  status=$(jq -r '.status' <<<"$state")
  progress=$(jq -c '.progress // empty' <<<"$state")
  if [ -n "$progress" ] && [ "$progress" != "$last" ]; then
    echo "progress: $progress"
    last=$progress
  fi
  case "$status" in queued | running) sleep "$POLL_SECONDS" ;; *) break ;; esac
done
echo "Job $status."
if [ "$status" = "succeeded" ]; then
  jq -r '.result | if type == "string" then . else tojson end' <<<"$state"
else
  exit 1
fi

Parar um servidor uma vez em um horário definido

Define uma parada única, daqui a três horas, a menos que você escolha outro horário. A regra roda do nosso lado, então funciona mesmo com seu computador desligado.

JavaScript · examples/node/scheduled-stop.mjs

// Stop a server once at a set time, for example at the end of the working day.
//
// What it does: sets a one-time stop on SERVER_ID, IN_HOURS hours from now (default 3), or at STOP_AT (an ISO time in
//   UTC such as 2026-12-01T18:00:00Z). The rule lives on our side, so it fires even when your computer is off. Other
//   automation rules of the server are left as they are. Prints when the server will stop.
// What it costs: nothing. Until the stop the server is billed as usual; after it, only its disk is billed.
// How to stop spending: destroy the server instead to end the disk charge too: `apidly destroy SERVER_ID --yes`, or
//   set a destroy time with `apidly automation set SERVER_ID --destroy-at TIME`. Remove the stop time again with
//   `apidly automation set SERVER_ID --clear stop-at`.
//
// Needs Node 18+, `npm install ./apidly-sdk-VERSION.tgz` and APIDLY_API_KEY with the Servers scope.
//   SERVER_ID=ins_... IN_HOURS=3 node scheduled-stop.mjs
import { Apidly } from "@apidly/sdk";

const env = process.env;
if (!env.SERVER_ID) {
  console.error("Set SERVER_ID, the server to stop (see `apidly servers`).");
  process.exit(2);
}
const stopAt =
  env.STOP_AT ??
  new Date(Date.now() + Number(env.IN_HOURS ?? 3) * 3600 * 1000)
    .toISOString()
    .replace(/\.\d+Z$/, "Z");

const apidly = new Apidly({ apiKey: env.APIDLY_API_KEY });

// Only the keys you send change; a key sent as null clears that rule.
const { nextStopAt } = await apidly.servers.setAutomation(env.SERVER_ID, {
  stopAt,
});
console.log(`${env.SERVER_ID} stops at ${nextStopAt ?? stopAt}.`);

Python · examples/python/scheduled_stop.py

"""Stop a server once at a set time, for example at the end of the working day.

What it does: sets a one-time stop on SERVER_ID, IN_HOURS hours from now (default 3), or at STOP_AT (an ISO time in
  UTC such as 2026-12-01T18:00:00Z). The rule lives on our side, so it fires even when your computer is off. Other
  automation rules of the server are left as they are. Prints when the server will stop.
What it costs: nothing. Until the stop the server is billed as usual; after it, only its disk is billed.
How to stop spending: destroy the server instead to end the disk charge too: `apidly destroy SERVER_ID --yes`, or
  set a destroy time with `apidly automation set SERVER_ID --destroy-at TIME`. Remove the stop time again with
  `apidly automation set SERVER_ID --clear stop-at`.

Needs Python 3.9+, `pip install ./apidly-VERSION-py3-none-any.whl` and APIDLY_API_KEY with the Servers scope.
  SERVER_ID=ins_... IN_HOURS=3 python scheduled_stop.py
"""
import datetime
import os
import sys

from apidly import Client

server_id = os.environ.get("SERVER_ID")
if not server_id:
    sys.exit("Set SERVER_ID, the server to stop (see `apidly servers`).")
stop_at = os.environ.get("STOP_AT")
if not stop_at:
    when = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=float(os.environ.get("IN_HOURS", "3")))
    stop_at = when.strftime("%Y-%m-%dT%H:%M:%SZ")

client = Client(api_key=os.environ["APIDLY_API_KEY"])

# Only the keys you send change; a key sent as None clears that rule.
answer = client.servers.set_automation(server_id, {"stopAt": stop_at})
print(f"{server_id} stops at {answer.get('nextStopAt') or stop_at}.")

Shell · examples/shell/scheduled-stop.sh

#!/usr/bin/env bash
# Stop a server once at a set time, for example at the end of the working day.
#
# What it does: sets a one-time stop on SERVER_ID, IN_HOURS hours from now (default 3), or at STOP_AT (an ISO time in
#   UTC such as 2026-12-01T18:00:00Z). The rule lives on our side, so it fires even when your computer is off. Other
#   automation rules of the server are left as they are. Then shows the server's rules.
# What it costs: nothing. Until the stop the server is billed as usual; after it, only its disk is billed.
# How to stop spending: destroy the server instead to end the disk charge too: `apidly destroy SERVER_ID --yes`, or
#   set a destroy time with `apidly automation set SERVER_ID --destroy-at TIME`. Remove the stop time again with
#   `apidly automation set SERVER_ID --clear stop-at`.
#
# Needs bash, the apidly CLI and APIDLY_API_KEY with the Servers scope.
#   SERVER_ID=ins_... IN_HOURS=3 ./scheduled-stop.sh
set -euo pipefail

: "${SERVER_ID:?Set SERVER_ID, the server to stop (see apidly servers)}"
if [ -z "${STOP_AT:-}" ]; then
  hours="${IN_HOURS:-3}"
  # GNU date (Linux) first, then BSD date (macOS).
  STOP_AT=$(date -u -d "+$hours hours" +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || date -u -v+"$hours"H +%Y-%m-%dT%H:%M:%SZ)
fi

apidly automation set "$SERVER_ID" --stop-at "$STOP_AT"
apidly automation get "$SERVER_ID"

Paginação e novas tentativas seguras

Lê duas vezes todas as páginas dos seus servidores, com o auxiliar do SDK e à mão com o cursor. Com LAUNCH=1 também cria um servidor com uma única chave de idempotência que cada nova tentativa reutiliza, então uma nova tentativa nunca cria um segundo servidor. Erros que uma nova tentativa não resolve não são repetidos.

JavaScript · examples/node/pagination-and-retry.mjs

// Read long lists page by page, and retry a request that creates something without ever creating it twice.
//
// What it does: (1) lists every server with the iter helper, which follows nextCursor for you; (2) does the same by
//   hand with list() and the cursor, for when you need one page at a time; (3) with LAUNCH=1, requests a server with
//   ONE idempotency key reused on every retry, so a retry after a timeout or a 429/5xx answer returns the first
//   server instead of creating a second one. Errors that a retry cannot fix (bad input, no balance) are not retried.
// What it costs: listing is free. With LAUNCH=1 one server is created (PLAN_ID, TEMPLATE, default pytorch) and billed by
//   the second at its hourly price; the script prints it from a dry run first and refuses above MAX_HOURLY_USD.
// How to stop spending: the launched server stops itself after 1 hour; destroy it sooner with
//   `apidly destroy SERVER_ID --yes`.
//
// Needs Node 18+, `npm install ./apidly-sdk-VERSION.tgz` and APIDLY_API_KEY (Read only is enough without LAUNCH=1).
//   node pagination-and-retry.mjs
//   LAUNCH=1 PLAN_ID=... MAX_HOURLY_USD=<your limit> node pagination-and-retry.mjs
import { randomUUID } from "node:crypto";
import {
  Apidly,
  ConnectionError,
  RateLimitError,
  ServerError,
} from "@apidly/sdk";

const env = process.env;
// The SDK already retries reads, and writes that carry an idempotency key, twice on its own; this sets that number.
const apidly = new Apidly({ apiKey: env.APIDLY_API_KEY, maxRetries: 2 });

// 1. Every item, every page.
let count = 0;
for await (const server of apidly.servers.iter({ includeDestroyed: false })) {
  count++;
  console.log(`${server.id}  ${server.status}  ${server.label}`);
}
console.log(`${count} server(s).`);

// 2. The same by hand: pass the nextCursor of one page to get the next; null means there are no more pages.
let cursor;
let pages = 0;
do {
  const page = await apidly.servers.list({ limit: 50, cursor });
  pages++;
  cursor = page.nextCursor ?? undefined;
} while (cursor);
console.log(`${pages} page(s) of up to 50.`);

// 3. A safe retry of a create.
if (env.LAUNCH === "1") {
  const { template } = await apidly.templates.get(env.TEMPLATE ?? "pytorch");
  const request = {
    planId: env.PLAN_ID,
    templateId: template.id,
    label: "retry-example",
    diskGb: template.defaultDiskGb,
    automation: { maxRuntimeHours: 1 },
  };
  const { quote } = await apidly.servers.estimate(request);
  if (
    quote.blockers.length > 0 ||
    !(Number(quote.totalHourlyUsd) <= Number(env.MAX_HOURLY_USD))
  ) {
    console.error(
      `Not launched: ${quote.totalHourlyUsd} USD per hour`,
      quote.blockers
    );
    process.exit(1);
  }

  // One key for this one server. Keep it (in a file or a database) if your program may restart in between.
  const idempotencyKey = randomUUID();
  const retryable = (err) =>
    err instanceof ConnectionError ||
    err instanceof RateLimitError ||
    err instanceof ServerError;
  for (let attempt = 1; ; attempt++) {
    try {
      const { server, deployment } = await apidly.servers.create(request, {
        idempotencyKey,
      });
      console.log(
        `Request ${deployment.id}: server ${server?.id ?? "waiting for approval"} (attempt ${attempt}).`
      );
      break;
    } catch (err) {
      if (!retryable(err) || attempt >= 5) {
        throw err;
      }
      // Wait as long as the API asks (Retry-After), or back off: 2, 4, 8, 16 seconds.
      const seconds = err.retryAfter ?? 2 ** attempt;
      console.error(
        `${err.message}; trying again in ${seconds} s with the same key`
      );
      await new Promise((r) => setTimeout(r, seconds * 1000));
    }
  }
}

Python · examples/python/pagination_and_retry.py

"""Read long lists page by page, and retry a request that creates something without ever creating it twice.

What it does: (1) lists every server with the iter helper, which follows nextCursor for you; (2) does the same by
  hand with list() and the cursor, for when you need one page at a time; (3) with LAUNCH=1, requests a server with
  ONE idempotency key reused on every retry, so a retry after a timeout or a 429/5xx answer returns the first
  server instead of creating a second one. Errors that a retry cannot fix (bad input, no balance) are not retried.
What it costs: listing is free. With LAUNCH=1 one server is created (PLAN_ID, TEMPLATE, default pytorch) and billed by
  the second at its hourly price; the script prints it from a dry run first and refuses above MAX_HOURLY_USD.
How to stop spending: the launched server stops itself after 1 hour; destroy it sooner with
  `apidly destroy SERVER_ID --yes`.

Needs Python 3.9+, `pip install ./apidly-VERSION-py3-none-any.whl` and APIDLY_API_KEY (Read only is enough without
LAUNCH=1).
  python pagination_and_retry.py
  LAUNCH=1 PLAN_ID=... MAX_HOURLY_USD=<your limit> python pagination_and_retry.py
"""
import os
import sys
import time
import uuid

from apidly import ApidlyConnectionError, Client, RateLimitError, ServerError

# The SDK already retries reads, and writes that carry an idempotency key, twice on its own; this sets that number.
client = Client(api_key=os.environ["APIDLY_API_KEY"], max_retries=2)

# 1. Every item, every page.
count = 0
for server in client.servers.iter(include_destroyed=False):
    count += 1
    print(f"{server['id']}  {server['status']}  {server['label']}")
print(f"{count} server(s).")

# 2. The same by hand: pass the nextCursor of one page to get the next; None means there are no more pages.
cursor = None
pages = 0
while True:
    page = client.servers.list(limit=50, cursor=cursor)
    pages += 1
    cursor = page.get("nextCursor")
    if not cursor:
        break
print(f"{pages} page(s) of up to 50.")

# 3. A safe retry of a create.
if os.environ.get("LAUNCH") == "1":
    template = client.templates.get(os.environ.get("TEMPLATE", "pytorch"))["template"]
    request = dict(
        plan_id=os.environ["PLAN_ID"],
        template_id=template["id"],
        label="retry-example",
        disk_gb=template["defaultDiskGb"],
        automation={"maxRuntimeHours": 1},
    )
    quote = client.servers.estimate(**request)["quote"]
    if quote["blockers"] or not float(quote["totalHourlyUsd"]) <= float(os.environ.get("MAX_HOURLY_USD") or 0):
        sys.exit(f"Not launched: {quote['totalHourlyUsd']} USD per hour {quote['blockers']}")

    # One key for this one server. Keep it (in a file or a database) if your program may restart in between.
    idempotency_key = str(uuid.uuid4())
    attempt = 0
    while True:
        attempt += 1
        try:
            created = client.servers.create(**request, idempotency_key=idempotency_key)
            server = created["server"]
            print(f"Request {created['deployment']['id']}: server "
                  f"{server['id'] if server else 'waiting for approval'} (attempt {attempt}).")
            break
        except (ApidlyConnectionError, RateLimitError, ServerError) as err:
            if attempt >= 5:
                raise
            # Wait as long as the API asks (Retry-After), or back off: 2, 4, 8, 16 seconds.
            seconds = getattr(err, "retry_after", None) or 2 ** attempt
            print(f"{err}; trying again in {seconds} s with the same key", file=sys.stderr)
            time.sleep(seconds)

Shell · examples/shell/pagination-and-retry.sh

#!/usr/bin/env bash
# Read long lists page by page, and retry a request that creates something without ever creating it twice.
#
# What it does: (1) lists every server with `--all`, which follows the pages for you; (2) walks the pages by hand with
#   curl and nextCursor; (3) with LAUNCH=1, requests a server with ONE Idempotency-Key that curl reuses on each of its
#   retries (timeouts, 429 and 5xx answers, honouring Retry-After), so a retry returns the first server instead of
#   creating a second one. Answers a retry cannot fix (400, 402, 403) are not retried.
# What it costs: listing is free. With LAUNCH=1 one server is created (PLAN_ID, TEMPLATE_ID) and billed by the second
#   at its hourly price; a dry run prints it first and the script refuses above MAX_HOURLY_USD.
# How to stop spending: the launched server stops itself after 1 hour; destroy it sooner with
#   `apidly destroy SERVER_ID --yes`.
#
# Needs bash, curl, jq, the apidly CLI and APIDLY_API_KEY (Read only is enough without LAUNCH=1).
#   ./pagination-and-retry.sh
#   LAUNCH=1 PLAN_ID=... TEMPLATE_ID=... MAX_HOURLY_USD=<your limit> ./pagination-and-retry.sh
set -euo pipefail

BASE="${APIDLY_API_URL:-https://apidly.com}"

# 1. Every item, every page.
apidly servers --all --json | jq -r '.servers[] | "\(.id)  \(.status)  \(.label)"'

# 2. The same by hand: send the nextCursor of one page to get the next; null means there are no more pages.
cursor=""
pages=0
while :; do
  page=$(curl -fsS -G "$BASE/api/v1/servers" -H "Authorization: Bearer $APIDLY_API_KEY" \
    --data-urlencode limit=50 ${cursor:+--data-urlencode "cursor=$cursor"})
  pages=$((pages + 1))
  cursor=$(jq -r '.nextCursor // empty' <<<"$page")
  [ -z "$cursor" ] && break
done
echo "$pages page(s) of up to 50."

# 3. A safe retry of a create.
if [ "${LAUNCH:-}" = "1" ]; then
  : "${PLAN_ID:?Set PLAN_ID}" "${TEMPLATE_ID:?Set TEMPLATE_ID}" "${MAX_HOURLY_USD:?Set MAX_HOURLY_USD}"
  disk=$(apidly templates show "$TEMPLATE_ID" --json | jq '.template.defaultDiskGb')
  body=$(jq -n --arg plan "$PLAN_ID" --arg template "$TEMPLATE_ID" --argjson disk "$disk" \
    '{planId: $plan, templateId: $template, label: "retry-example", diskGb: $disk, automation: {maxRuntimeHours: 1}}')
  quote=$(curl -fsS -X POST "$BASE/api/v1/servers?dryRun=1" -H "Authorization: Bearer $APIDLY_API_KEY" \
    -H "Content-Type: application/json" -d "$body" | jq '.quote')
  if jq -e --argjson max "$MAX_HOURLY_USD" '(.blockers | length) > 0 or (.totalHourlyUsd | tonumber) > $max' \
    <<<"$quote" >/dev/null; then
    echo "Not launched: $(jq -r '.totalHourlyUsd' <<<"$quote") USD per hour" >&2
    exit 1
  fi
  # One key for this one server. Keep it in a file if your script may be run again for the same server.
  key=$(uuidgen 2>/dev/null || cat /proc/sys/kernel/random/uuid)
  curl -fsS --retry 4 --retry-delay 2 --retry-max-time 120 -X POST "$BASE/api/v1/servers" \
    -H "Authorization: Bearer $APIDLY_API_KEY" -H "Content-Type: application/json" \
    -H "Idempotency-Key: $key" -d "$body" | jq -r '"Request \(.deployment.id): server \(.server.id // "waiting for approval")"'
fi

Próximos passos

Pronto para testar?

Crie uma conta gratuita e adicione crédito quando quiser iniciar um servidor. A menor recarga é $ 10.

Criar uma conta gratuita

Isto foi útil?

Ainda com dúvidas? Fale conosco