Docs / SDKs & tools

Python SDK

apipods is the official Python package. It contains a typed client for the REST API and the runtime that turns a Python function into a serverless worker. Current version: 1.9.1.

Install

Python 3.9 or newer. The package has no compiled dependencies and works on Linux, macOS and Windows.

Terminal
$ pip install apipods
$ python -c "import apipods; print(apipods.__version__)"
1.9.1

Set your key once in the environment. The client reads APIPODS_API_KEY automatically; see Authentication.

Terminal
$ export APIPODS_API_KEY="ak_live_..."

Create a client

client.py
import apipods

client = apipods.Client()  # reads APIPODS_API_KEY

# or configure explicitly
client = apipods.Client(
    api_key="ak_live_...",
    timeout=30,          # seconds per HTTP request
    max_retries=3,       # retries 429, 500 and 503 with exponential backoff
)
NameTypeDescription
api_keystrDefaults to the APIPODS_API_KEY environment variable.
base_urlstrControl-plane URL. Defaults to https://api.apipods.com/v1.
run_base_urlstrRuntime URL. Defaults to https://run.apipods.com/v1. Point it at http://localhost:8000 to call a local worker (see Local testing).
timeoutfloatHTTP timeout in seconds. Default 30.
max_retriesintAutomatic retries for 429, 500 and 503. Default 3. Every retried POST reuses the same Idempotency-Key.

An async client with the same surface is available as apipods.AsyncClient; every method becomes awaitable.

Manage pods

Keyword arguments are the snake_case version of the JSON fields: gpu_type_id → gpuTypeId, container_disk_in_gb → containerDiskInGb. gpu_type_id also accepts the short alias (e.g. H100_SXM).

pods.py
pod = client.pods.create(
    name="llama-finetune",
    gpu_type_id="NVIDIA_H100_80GB_SXM",
    gpu_count=1,
    region_id="eu-nl-1",
    image="apipods/pytorch:2.9.0-py3.12-cuda12.8.1",
    container_disk_in_gb=50,
    volume_in_gb=100,
    ports=[{"port": 8888, "protocol": "http"}, {"port": 22, "protocol": "tcp"}],
    env={"HF_TOKEN": "{{ secrets.HF_TOKEN }}"},
)
pod.wait_until_running(timeout=600)
print(pod.id, pod.status, pod.cost_per_hr)
print(pod.ssh_command)  # ssh root@pod_8f2k1x9q.ssh.apipods.com

for line in client.pods.logs(pod.id, follow=True):
    print(line.timestamp, line.message)

client.pods.stop(pod.id)       # -> EXITED, volume disk kept
client.pods.start(pod.id)      # -> RUNNING again
client.pods.terminate(pod.id)  # -> TERMINATED, disks deleted

Call serverless endpoints

call.py
ep = client.endpoint("ep_4n8wq2zt")

# Synchronous: waits up to 90 seconds
job = ep.run_sync({"prompt": "a lighthouse on a cliff at dusk", "steps": 4})
print(job.status, job.delay_time, job.execution_time, job.output)

# Asynchronous: returns immediately with IN_QUEUE
job = ep.run({"prompt": "a lighthouse"}, webhook="https://example.com/hooks/apipods")
print(job.status())            # IN_QUEUE / IN_PROGRESS / COMPLETED ...
result = job.output(timeout=120)

# Streaming handlers
for chunk in ep.run({"prompt": "Tell me a story"}).stream():
    print(chunk, end="", flush=True)

# Existing job, cancel, retry
job = ep.job("job_3x9wq2mt")
job.cancel()
job.retry()

print(ep.health())             # queue and worker counts
ep.purge_queue()               # drop all IN_QUEUE jobs

Job states are described in Job states.

Worker runtime

The same package runs inside your worker image. apipods.serverless.start connects to the job queue, calls your handler for every job and reports results back.

handler.py
import apipods

model = load_model()  # runs once per worker, captured by Warmstart

def handler(job):
    prompt = job["input"]["prompt"]
    return {"text": model.generate(prompt)}

apipods.serverless.start({"handler": handler})
OptionDescription
handlerRequired. A function, async function or generator that receives the job dict (`id`, `input`).
concurrency_modifierCallable receiving the current concurrency and returning the desired one. See Concurrency.
return_aggregate_streamFor generator handlers: also return all yielded chunks as the final `output`.

Helpers: apipods.serverless.progress_update(job, {...}) publishes progress visible in /status. Full guide: Write a handler and Local testing.

Pagination & errors

list() returns an iterator that fetches pages lazily with the cursor; pass limit to change the page size. Errors raise subclasses of apipods.APIError.

errors.py
for pod in client.pods.list(status="RUNNING"):
    print(pod.id, pod.name)

try:
    client.pods.start("pod_8f2k1x9q")
except apipods.NoCapacityError:
    print("GPU on this host is taken; try again later or use a network volume")
except apipods.InvalidStateError as e:
    print(e.code, e.message)      # invalid_state
except apipods.RateLimitError as e:
    print("retry after", e.retry_after)
except apipods.APIError as e:
    print(e.status, e.code, e.request_id)
ExceptionHTTP statusError code
AuthenticationError401invalid_api_key, revoked_api_key, missing_api_key
PermissionDeniedError403insufficient_scope, insufficient_role, gpu_quota_exceeded, active_workers_not_enabled
NotFoundError404resource_not_found
InvalidStateError409invalid_state, resource_in_use
BillingError402insufficient_balance, spend_limit_reached
RateLimitError429rate_limited
NoCapacityError503no_capacity

The full list of codes is in Errors.

Resource reference

ResourcePythonMethodsAPI reference
Podsclient.podslist, get, create, update, start, stop, restart, terminate, logsPods
Endpointsclient.endpointslist, get, create, update, delete, workers, metrics, logsEndpoints
Runtimeclient.endpoint(id)run, run_sync, job, health, purge_queueJobs
Templatesclient.templateslist, get, create, update, deleteTemplates
Registry credentialsclient.registry_credentialslist, create, deleteTemplates
Network volumesclient.volumeslist, get, create, update, deleteNetwork volumes
S3 keysclient.s3_keyslist, create, deleteNetwork volumes
GPU types & poolsclient.gpu_types, client.gpu_pools, client.regionslist, getGPU types
Secretsclient.secretslist, get, create, update, deleteSecrets
SSH keysclient.ssh_keyslist, create, deleteSSH keys
Webhooksclient.webhookslist, get, create, update, delete, test, deliveriesWebhooks
Billingclient.billingbalance, usage, invoices.list, spend_limit.get, spend_limit.updateBilling
API keysclient.api_keyslist, create, rotate, deleteAPI keys