Write a handler
A minimal handler
import apipods
def handler(job):
prompt = job["input"]["prompt"]
return {"text": prompt.upper()}
apipods.serverless.start({"handler": handler})Install the SDK with pip install apipods (version 1.9.1 or later). apipods.serverless.start() blocks forever: it connects to the endpoint's queue, calls handler for each job and posts the return value back. When you run the file outside Apipods it switches to local test mode.
The job object
Your handler receives a dict with two keys:
{
"id": "job_3x9wq2mt",
"input": {
"prompt": "a lighthouse on a cliff at dusk, 35mm photo",
"steps": 4
}
}idis the job ID the caller got back from/run. Use it to name output files or correlate logs.inputis exactly theinputobject from the request body. Validate it yourself; Apipods only checks that it is valid JSON within the payload limit.
Outputs and errors
Return any JSON-serializable value. It becomes the job's output and the job moves to COMPLETED. To fail a job, either raise an exception or return a dict with an error key:
import os
import torch
import apipods
from diffusers import AutoPipelineForText2Image
# Module-level code runs once per worker, before the first job.
# Warmstart snapshots the worker after this point.
pipe = AutoPipelineForText2Image.from_pretrained(
os.environ.get("MODEL_ID", "stabilityai/sdxl-turbo"),
torch_dtype=torch.float16,
variant="fp16",
).to("cuda")
def handler(job):
params = job["input"]
prompt = params.get("prompt")
if not prompt:
return {"error": "input.prompt is required"}
steps = int(params.get("steps", 4))
if not 1 <= steps <= 50:
raise ValueError("steps must be between 1 and 50")
seed = int(params.get("seed", torch.seed() % 2**31))
generator = torch.Generator("cuda").manual_seed(seed)
image = pipe(prompt, num_inference_steps=steps, guidance_scale=0.0, generator=generator).images[0]
path = f"/volume/outputs/{job['id']}.png"
os.makedirs(os.path.dirname(path), exist_ok=True)
image.save(path)
return {"path": path, "seed": seed}
apipods.serverless.start({"handler": handler})A failed job looks like this on /status:
{
"id": "job_7k2m4p8d",
"status": "FAILED",
"delayTime": 640,
"executionTime": 211,
"workerId": "wrk_8q3m2x9k",
"error": {
"type": "ValueError",
"message": "steps must be between 1 and 50",
"traceback": "Traceback (most recent call last): ..."
},
"createdAt": "2026-11-18T10:05:40Z",
"completedAt": "2026-11-18T10:05:41Z"
}/volume or upload them to your own bucket, and return a path or URL.Load models once
Code at module level runs once per worker, before the first job. Put model loading, tokenizer setup and warm-up passes there. It is also what Warmstart snapshots, so the cost is paid once per deploy rather than once per worker. Keep per-job work, such as decoding inputs and running inference, inside the handler.
Progress updates
Long jobs can report progress. The latest update appears as progress on /status while the job is IN_PROGRESS.
import apipods
def handler(job):
frames = job["input"]["frames"]
for i in range(frames):
render_frame(i)
if i % 10 == 0:
apipods.serverless.progress_update(job, {"percent": round(100 * i / frames)})
return {"frames": frames}
apipods.serverless.start({"handler": handler})Streaming and async handlers
Make the handler a generator to stream partial outputs. Make it async def to process several jobs at once on one worker with concurrency.
import apipods
async def handler(job):
async for token in model.generate(job["input"]["prompt"]):
yield {"token": token}
apipods.serverless.start({
"handler": handler,
"concurrency_modifier": lambda current: 8,
"return_aggregate_stream": True,
})Environment variables
Your endpoint's env is set in every worker, including secret references like {{ secrets.HF_TOKEN }}. Apipods also sets:
| Variable | Example | Description |
|---|---|---|
APIPODS_ENDPOINT_ID | ep_4n8wq2zt | The endpoint the worker belongs to. |
APIPODS_WORKER_ID | wrk_8q3m2x9k | Unique per worker. Appears in logs and on jobs as workerId. |
APIPODS_GPU_POOL_ID | L40S | The pool the worker was scheduled on. |
APIPODS_REGION_ID | eu-nl-1 | The region the worker runs in. |