ClickAPIs
Docs · Jobs & async

Jobs & async

Long work runs in the background so your request never waits on it. Add "async": true to any operation, or let us decide: calls estimated above 1,000 units become jobs automatically.

1. Submit

The call returns 202 Accepted straight away with a job id.

Response 202
{
  "ok": true,
  "data": {
    "job_id": "6f1c2a9e-4b7d-4c1e-9a52-0d8e3f7b1c44",
    "status": "queued",
    "estimated_units": 500,
    "poll": "/v1/jobs/6f1c2a9e-4b7d-4c1e-9a52-0d8e3f7b1c44"
  }
}

2. Poll, or get a webhook

GET /v1/jobs/{id} is free. Status goes queued → running → done | failed | cancelled; progress shows symbols done out of total. When it is done, result holds exactly what the synchronous call would have returned in data.

GET /v1/jobs/{id}
{
  "ok": true,
  "data": {
    "id": "6f1c2a9e-4b7d-4c1e-9a52-0d8e3f7b1c44",
    "op": "screen",
    "status": "running",
    "progress": {
      "done": 300,
      "total": 500
    },
    "created_at": "2026-11-12T14:03:11Z"
  }
}

GET /v1/jobs lists your recent jobs; DELETE /v1/jobs/{id} cancels a queued one. Up to 10 jobs can be queued or running; results are kept for 30 days. You are charged when a job finishes, for the units it actually used; failed and cancelled jobs are free.

For live progress in a browser app, the dashboard also pushes job.update events; from a server, polling with backoff is simplest.

Polling examples

#!/usr/bin/env bash
# Submit a screen as a job, then poll until it finishes. Needs curl and jq.
set -euo pipefail
API=https://clickapis.com/v1
AUTH="Authorization: Bearer $CLICKAPIS_KEY"

JOB=$(curl -sf "$API/screen" -H "$AUTH" -H "Content-Type: application/json" -d '{
  "universe": "us.top500",
  "where": "rsi(14) < 30 and close > sma(200)",
  "select": ["rsi(14) as rsi", "ret(20) as ret_20d"],
  "sort": "rsi(14)", "order": "asc",
  "async": true
}' | jq -r '.data.job_id')
echo "job $JOB"

delay=1
while :; do
  R=$(curl -sf "$API/jobs/$JOB" -H "$AUTH")
  STATUS=$(echo "$R" | jq -r '.data.status')
  case "$STATUS" in
    done)      echo "$R" | jq '.data.result.rows'; break ;;
    failed)    echo "$R" | jq '.data.error' >&2; exit 1 ;;
    cancelled) echo "cancelled" >&2; exit 1 ;;
    *)         echo "$STATUS $(echo "$R" | jq -r '.data.progress // {} | "\(.done // 0)/\(.total // "?")"')"
               sleep $delay; delay=$(( delay < 8 ? delay * 2 : 8 )) ;;
  esac
done
import os, random, time
import requests

API = "https://clickapis.com/v1"
S = requests.Session()
S.headers["Authorization"] = f"Bearer {os.environ['CLICKAPIS_KEY']}"


def submit(op: str, body: dict) -> str:
    r = S.post(f"{API}/{op}", json={**body, "async": True}, timeout=30)
    r.raise_for_status()
    return r.json()["data"]["job_id"]


def wait(job_id: str, timeout: float = 600) -> dict:
    \"\"\"Poll with exponential backoff and jitter until the job is done.\"\"\"
    delay, deadline = 1.0, time.monotonic() + timeout
    while time.monotonic() < deadline:
        r = S.get(f"{API}/jobs/{job_id}", timeout=30)
        if r.status_code == 429:            # rate limited: back off harder
            time.sleep(delay * 2)
            continue
        r.raise_for_status()
        job = r.json()["data"]
        if job["status"] == "done":
            return job["result"]
        if job["status"] in ("failed", "cancelled"):
            raise RuntimeError(job.get("error") or job["status"])
        time.sleep(delay + random.uniform(0, delay / 2))
        delay = min(delay * 2, 10)
    raise TimeoutError(job_id)


job = submit("event-study", {
    "symbols": ["SPY", "QQQ", "IWM"],
    "condition": "rsi(14) < 30 and close > sma(200)",
    "horizons": [5, 20, 60],
})
result = wait(job)
for h in result["results"]:
    print(h["horizon"], h["mean"], h["win_rate"], h["edge_t_stat"])
// Node 18+
const API = "https://clickapis.com/v1";
const headers = {
  "Authorization": `Bearer ${process.env.CLICKAPIS_KEY}`,
  "Content-Type": "application/json",
};
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

async function runJob(op, body, { timeoutMs = 600_000 } = {}) {
  const sub = await fetch(`${API}/${op}`, {
    method: "POST", headers, body: JSON.stringify({ ...body, async: true }),
  }).then((r) => r.json());
  if (!sub.ok) throw new Error(sub.error.message);

  const id = sub.data.job_id;
  const until = Date.now() + timeoutMs;
  for (let delay = 1000; Date.now() < until; delay = Math.min(delay * 2, 10_000)) {
    const job = await fetch(`${API}/jobs/${id}`, { headers }).then((r) => r.json());
    const { status, result, error, progress } = job.data ?? {};
    if (status === "done") return result;
    if (status === "failed" || status === "cancelled") throw new Error(error?.message ?? status);
    if (progress) console.log(`${status} ${progress.done}/${progress.total}`);
    await sleep(delay + Math.random() * delay / 2);
  }
  throw new Error(`timed out waiting for job ${id}`);
}

const result = await runJob("screen", {
  universe: "us.top500",
  where: "close > sma(200) and rsi(14) < 35",
  select: ["rsi(14) as rsi"],
  sort: "rsi(14)", order: "asc", limit: 25,
});
console.table(result.rows);

3. Webhooks

Add "webhook_url": "https://…" to the request and we POST the finished job there, whether it succeeded (job.done) or failed (job.failed). The body is the job’s data and meta, exactly what the synchronous call would have returned:

Webhook body job.done
{
  "event": "job.done",
  "job_id": "6f1c2a9e-4b7d-4c1e-9a52-0d8e3f7b1c44",
  "status": "done",
  "op": "screen",
  "data": {
    "rows": [
      {
        "symbol": "DT",
        "date": "2026-11-12",
        "close": 44.79,
        "rsi": 26.411771,
        "ret_20d": -0.297191,
        "sort_value": 26.411771
      },
      {
        "symbol": "ZBRA",
        "date": "2026-11-12",
        "close": 317.91,
        "rsi": 29.946263,
        "ret_20d": -0.157877,
        "sort_value": 29.946263
      }
    ],
    "universe": "us.top500",
    "where": "rsi(14) < 30 and close > sma(200)",
    "sort": "rsi(14)",
    "order": "asc",
    "scanned": 500,
    "matched": 2,
    "not_found": 0
  },
  "meta": {
    "op": "screen",
    "units": 50,
    "cost_usd": 0.025,
    "billing": "credits",
    "free_call": false,
    "free_calls_left": 0,
    "balance_usd": 24.5,
    "ms": 2140
  }
}

Verify the signature

Every delivery carries these headers. The signature is an HMAC-SHA256 of the timestamp, a dot and the raw body, keyed with your account’s webhook secret (in Settings):

Content-Type: application/json
User-Agent: ClickAPIs-Webhooks/1
X-ClickAPIs-Event: job.done            (or job.failed)
X-ClickAPIs-Delivery: <uuid>           (the same on every retry)
X-ClickAPIs-Timestamp: 1767225600
X-ClickAPIs-Signature: sha256=<hex of HMAC_SHA256(secret, timestamp + "." + raw_body)>
  • Compute the HMAC over the raw bytes you received, before any JSON parsing. We send compact JSON; re-serialising it changes the bytes.
  • Compare in constant time, and reject timestamps more than 5 minutes old to stop replays.
# pip install flask
import hashlib, hmac, os, time
from flask import Flask, abort, request

SECRET = os.environ["CLICKAPIS_WEBHOOK_SECRET"].encode()   # Settings > Webhook secret
app = Flask(__name__)


@app.post("/hooks/clickapis")
def clickapis_hook():
    ts = request.headers.get("X-ClickAPIs-Timestamp", "")
    sig = request.headers.get("X-ClickAPIs-Signature", "")
    raw = request.get_data()                                    # the exact bytes we sent
    expected = "sha256=" + hmac.new(SECRET, ts.encode() + b"." + raw, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, sig):
        abort(401)
    if not ts.isdigit() or abs(time.time() - int(ts)) > 300:   # reject replays older than 5 minutes
        abort(401)

    event = request.get_json()
    if already_handled(request.headers["X-ClickAPIs-Delivery"]):  # retries reuse the delivery id
        return "", 204
    if event["event"] == "job.done":
        handle_result(event["job_id"], event["op"], event["data"])
    else:                                                      # "job.failed"
        log_failure(event["job_id"], event["error"])
    return "", 204                                             # any 2xx within 10 s stops the retries
// npm i express
import crypto from "node:crypto";
import express from "express";

const SECRET = process.env.CLICKAPIS_WEBHOOK_SECRET;
const app = express();

// Use the raw body: re-serialising parsed JSON would change the bytes and break the signature.
app.post("/hooks/clickapis", express.raw({ type: "application/json" }), (req, res) => {
  const ts = req.get("X-ClickAPIs-Timestamp") ?? "";
  const sig = req.get("X-ClickAPIs-Signature") ?? "";
  const expected = "sha256=" + crypto.createHmac("sha256", SECRET)
    .update(ts + ".").update(req.body).digest("hex");
  const ok = sig.length === expected.length &&
    crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected));
  if (!ok || Math.abs(Date.now() / 1000 - Number(ts)) > 300) return res.sendStatus(401);

  const event = JSON.parse(req.body);
  console.log(req.get("X-ClickAPIs-Delivery"), event.event, event.job_id, event.op);  // event.data or event.error
  res.sendStatus(204);
});

app.listen(3000);
<?php
$secret = getenv('CLICKAPIS_WEBHOOK_SECRET');
$raw = file_get_contents('php://input');
$ts  = $_SERVER['HTTP_X_CLICKAPIS_TIMESTAMP'] ?? '';
$sig = $_SERVER['HTTP_X_CLICKAPIS_SIGNATURE'] ?? '';

$expected = 'sha256=' . hash_hmac('sha256', $ts . '.' . $raw, $secret);
if (!hash_equals($expected, $sig) || abs(time() - (int)$ts) > 300) {
    http_response_code(401);
    exit;
}
$event = json_decode($raw, true);
// $event['event'] ('job.done' | 'job.failed'), $event['job_id'], $event['op'], $event['data'] + $event['meta'] or $event['error']
// $_SERVER['HTTP_X_CLICKAPIS_DELIVERY'] is the same on every retry: use it to skip duplicates
http_response_code(204);

Retries and idempotency

  • Answer with any 2xx within 10 seconds. Anything else (a 3xx, 4xx or 5xx, a timeout or a connection error) is retried: up to 3 attempts in all, about 1 s and 2 s apart.
  • Redirects are not followed: point webhook_url at the final URL.
  • Acknowledge first and do slow work afterwards (a queue, a background task).
  • The same delivery can arrive more than once. X-ClickAPIs-Delivery is the same on every retry of one delivery, and job_id identifies the job: store the ones you have handled and skip repeats.
  • We only deliver to public addresses: hosts that resolve to private, loopback, link-local or cloud-metadata addresses are refused, as are non-https URLs. Any port is fine.
  • GET /v1/webhooks/deliveries (free) and Settings → Webhooks list every attempt with its status code and time, for 30 days.

4. Testing your webhook receiver

You can test a receiver end to end without running a job or spending credits: POST /v1/webhooks/test sends a realistic, signed sample delivery to your URL, with the same body shape and headers as a real one, and "test": true in the body. It is free, limited to 10 an hour per account, and tells you exactly what was sent and what your endpoint answered. The same tool is in the dashboard under Settings → Webhooks.

FieldDescription
url requiredYour receiver. https only, public address, any port; redirects are not followed. Times out after 10 s.
event"job.done" (default) or "job.failed".
opWhich operation the sample result comes from. Default "screen"; any operation name works.
curl https://clickapis.com/v1/webhooks/test \
  -H "Authorization: Bearer $CLICKAPIS_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://your-tunnel.example.com/hooks/clickapis", "event": "job.done", "op": "screen"}'
import os, requests

r = requests.post(
    "https://clickapis.com/v1/webhooks/test",
    headers={"Authorization": f"Bearer {os.environ['CLICKAPIS_KEY']}"},
    json={"url": "https://your-tunnel.example.com/hooks/clickapis", "event": "job.failed"},
    timeout=30,
)
t = r.json()["data"]
print(t["delivered"], t["status_code"], t["ms"], "ms")
print(t["response_excerpt"])      # what your receiver answered
# t["body_sent"] is the exact raw body; t["timestamp"] and t["signature_header"] let you
# check your verification code offline against your webhook secret.
Response 200
{
  "ok": true,
  "data": {
    "delivered": true,
    "status_code": 204,
    "ms": 183,
    "error": null,
    "response_excerpt": "",
    "delivery_id": "0b6e1d52-6a51-4d3f-9f0e-2a7c1f4e8b90",
    "event": "job.done",
    "timestamp": "1767225600",
    "signature_header": "sha256=3f1c…",
    "headers_sent": {
      "Content-Type": "application/json",
      "User-Agent": "ClickAPIs-Webhooks/1",
      "X-ClickAPIs-Event": "job.done",
      "X-ClickAPIs-Delivery": "0b6e1d52-6a51-4d3f-9f0e-2a7c1f4e8b90",
      "X-ClickAPIs-Timestamp": "1767225600",
      "X-ClickAPIs-Signature": "sha256=3f1c…"
    },
    "body_sent": "{\"event\":\"job.done\",\"job_id\":\"…\",\"status\":\"done\",\"op\":\"screen\",\"data\":{…},\"meta\":{…},\"test\":true}"
  }
}

delivered is true when your endpoint answered 2xx. A URL we refuse (not https, or a private address) returns 400 WEBHOOK_URL_REFUSED; the 11th test in an hour returns 429 RATE_LIMITED with retry_after_s.

Receiving on your own machine

Your laptop is not reachable from the internet, and we only deliver to public https addresses, so put a tunnel in front of your local server:

# 1. run your receiver locally, e.g. on port 3000
# 2. expose it over https with a tunnel (pick one)
ngrok http 3000
cloudflared tunnel --url http://localhost:3000
# 3. use the https URL the tunnel prints, plus your path:
#    https://<random>.ngrok-free.app/hooks/clickapis
#    https://<random>.trycloudflare.com/hooks/clickapis

Just want to see what arrives before writing any code? Use a request inspector such as webhook.site: it gives you a public https URL and shows every request’s headers and body. Paste that URL into the test, then check the signature with your secret. Anything sent to a public inspector can be read by whoever has its URL, so use it with test deliveries only.

Sample deliveries

A successful job:

POST /hooks/clickapis HTTP/1.1
Content-Type: application/json
User-Agent: ClickAPIs-Webhooks/1
X-ClickAPIs-Event: job.done
X-ClickAPIs-Delivery: 0b6e1d52-6a51-4d3f-9f0e-2a7c1f4e8b90
X-ClickAPIs-Timestamp: 1767225600
X-ClickAPIs-Signature: sha256=<hex HMAC_SHA256(secret, "1767225600." + raw_body)>
Body job.done
{
  "event": "job.done",
  "job_id": "6f1c2a9e-4b7d-4c1e-9a52-0d8e3f7b1c44",
  "status": "done",
  "op": "screen",
  "data": {
    "rows": [
      {
        "symbol": "DT",
        "date": "2026-11-12",
        "close": 44.79,
        "rsi": 26.411771,
        "ret_20d": -0.297191,
        "sort_value": 26.411771
      },
      {
        "symbol": "ZBRA",
        "date": "2026-11-12",
        "close": 317.91,
        "rsi": 29.946263,
        "ret_20d": -0.157877,
        "sort_value": 29.946263
      }
    ],
    "universe": "us.top500",
    "where": "rsi(14) < 30 and close > sma(200)",
    "sort": "rsi(14)",
    "order": "asc",
    "scanned": 500,
    "matched": 2,
    "not_found": 0
  },
  "meta": {
    "op": "screen",
    "units": 50,
    "cost_usd": 0.025,
    "billing": "credits",
    "free_call": false,
    "free_calls_left": 0,
    "balance_usd": 24.5,
    "ms": 2140
  }
}

A failed job carries error instead of data and meta (failed jobs are not charged):

POST /hooks/clickapis HTTP/1.1
Content-Type: application/json
User-Agent: ClickAPIs-Webhooks/1
X-ClickAPIs-Event: job.failed
X-ClickAPIs-Delivery: 0b6e1d52-6a51-4d3f-9f0e-2a7c1f4e8b90
X-ClickAPIs-Timestamp: 1767225600
X-ClickAPIs-Signature: sha256=<hex HMAC_SHA256(secret, "1767225600." + raw_body)>
Body job.failed
{
  "event": "job.failed",
  "job_id": "6f1c2a9e-4b7d-4c1e-9a52-0d8e3f7b1c44",
  "status": "failed",
  "op": "screen",
  "error": {
    "code": "BAD_EXPRESSION",
    "message": "unknown function 'rsj' at position 0; did you mean rsi?"
  }
}

Real deliveries have no test field; test deliveries carry "test": true and a job_id that does not exist, so your handler can skip them before touching your data.

Checklist

  • Verify the signature over the raw body, and reject stale timestamps.
  • Answer 2xx within 10 seconds; queue the slow work.
  • Skip deliveries you have already handled (X-ClickAPIs-Delivery, or job_id for a job).
  • Treat "test": true as a no-op in production.
  • After a rotation in Settings, deliveries are signed with the new secret straight away.