Function jobs
For work longer than one call: batch scrapes a list of URLs, crawl follows a site's links, map lists a whole site's URLs, watch reports live changes on a page, warmup keeps a browser browsing like a person. A job starts with one request, runs on your threads in the background for as long as it needs, and you follow it, read its results as they arrive — as JSON lines or one zip archive — stop it and resume it. Jobs come with every paid plan.
Start a job
POST https://cdpfleet.com/v1/functions/batch, /crawl, /watch, /warmup, or /map with "job": true, with your API key, returns 202 {"job_id", "status_url", "concurrency"} at once. Jobs have no size or time limit of their own: a run that reaches your plan's session limit (24 hours) continues in a new run by itself, so a job goes on until it's done or you stop it — it uses your threads and minutes all along.
curl -s https://cdpfleet.com/v1/functions/crawl -H "x-api-key: $CDPFLEET_API_KEY" -H "content-type: application/json" \
-d '{"url":"https://books.toscrape.com/","max_depth":2,"max_pages":200,"formats":["markdown"],"concurrency":4}'
# {"job_id":"7c1e…","status_url":"https://cdpfleet.com/v1/jobs/7c1e…","concurrency":4}
batch
| Field | Type | Default | What it does |
|---|---|---|---|
urls | string[] | this or urls_url | Public http/https URLs, scraped in any order — as many as fit in the request (1 MB, about 10,000). |
urls_url | string | this or urls | A public link to a text file with one URL per line, any length. |
A batch from start to finish — start it, poll its status until it ends, then download every result as JSON lines:
# curl: the job id and status are read with grep
H="x-api-key: $CDPFLEET_API_KEY"
JOB=$(curl -s https://cdpfleet.com/v1/functions/batch -H "$H" -H "content-type: application/json" \
-d '{"urls":["https://books.toscrape.com/catalogue/page-1.html","https://books.toscrape.com/catalogue/page-2.html"],"formats":["markdown"],"concurrency":2}' | grep -o '"job_id":"[^"]*"' | cut -d'"' -f4)
echo "job $JOB"
while sleep 5; do
STATUS=$(curl -s https://cdpfleet.com/v1/jobs/$JOB -H "$H" | grep -o '"status":"[a-z]*"' | head -1 | cut -d'"' -f4)
echo "$STATUS"
case $STATUS in done|failed|stopped|interrupted) break ;; esac
done
curl -s https://cdpfleet.com/v1/jobs/$JOB/results.jsonl -H "$H" -o results.jsonl
wc -l results.jsonl
// Node.js 18+: save as batch.mjs, run node batch.mjs
import { writeFile } from 'node:fs/promises';
async function api(url, body) {
const res = await fetch(url, {
method: body ? 'POST' : 'GET',
headers: { 'x-api-key': process.env.CDPFLEET_API_KEY, ...(body && { 'content-type': 'application/json' }) },
body: body && JSON.stringify(body),
signal: AbortSignal.timeout(30000),
});
if (!res.ok) throw new Error(`${res.status} ${await res.text()}`); // 429: wait Retry-After seconds
return res;
}
// 1. Start the job: 202 {job_id, status_url, concurrency}
const { job_id } = await (await api('https://cdpfleet.com/v1/functions/batch', {
urls: [
'https://books.toscrape.com/catalogue/page-1.html',
'https://books.toscrape.com/catalogue/page-2.html',
],
formats: ['markdown'],
concurrency: 2,
})).json();
console.log('job', job_id);
// 2. Poll its status until it ends
let job;
do {
await new Promise((r) => setTimeout(r, 5000));
job = await (await api(`https://cdpfleet.com/v1/jobs/${job_id}`)).json();
console.log(job.status, JSON.stringify(job.progress));
} while (!['done', 'failed', 'stopped', 'interrupted'].includes(job.status));
// 3. Every result as JSON lines, one page per line
const jsonl = await (await api(`https://cdpfleet.com/v1/jobs/${job_id}/results.jsonl`)).text();
await writeFile('results.jsonl', jsonl);
console.log(`results.jsonl: ${jsonl.split('\n').filter(Boolean).length} pages`);
# Python 3 with requests (pip install requests): save as batch.py, run python batch.py
import os
import time
import requests
def api(method, url, **kw):
r = requests.request(method, url, headers={"x-api-key": os.environ["CDPFLEET_API_KEY"]}, timeout=30, **kw)
if not r.ok:
raise SystemExit(f"{r.status_code} {r.text}") # 429: wait r.headers["Retry-After"] seconds
return r
# 1. Start the job: 202 {job_id, status_url, concurrency}
job_id = api("POST", "https://cdpfleet.com/v1/functions/batch", json={
"urls": [
"https://books.toscrape.com/catalogue/page-1.html",
"https://books.toscrape.com/catalogue/page-2.html",
],
"formats": ["markdown"],
"concurrency": 2,
}).json()["job_id"]
print("job", job_id)
# 2. Poll its status until it ends
while True:
time.sleep(5)
job = api("GET", f"https://cdpfleet.com/v1/jobs/{job_id}").json()
print(job["status"], job["progress"])
if job["status"] in ("done", "failed", "stopped", "interrupted"):
break
# 3. Every result as JSON lines, one page per line
jsonl = api("GET", f"https://cdpfleet.com/v1/jobs/{job_id}/results.jsonl").content
open("results.jsonl", "wb").write(jsonl)
print(f"results.jsonl: {len(jsonl.splitlines())} pages")
// Java 17+ and Gson (com.google.code.gson:gson): save as Main.java, run java -cp gson-2.11.0.jar Main.java
import com.google.gson.*;
import java.net.URI;
import java.net.http.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.time.Duration;
import java.util.List;
public class Main {
static final HttpClient HTTP = HttpClient.newHttpClient();
static byte[] api(String url, String body) throws Exception {
HttpRequest.Builder req = HttpRequest.newBuilder(URI.create(url))
.header("x-api-key", System.getenv("CDPFLEET_API_KEY"))
.timeout(Duration.ofSeconds(30));
if (body != null) req.header("content-type", "application/json").POST(HttpRequest.BodyPublishers.ofString(body));
HttpResponse<byte[]> res = HTTP.send(req.build(), HttpResponse.BodyHandlers.ofByteArray());
if (res.statusCode() >= 300) { // 429: wait Retry-After seconds
throw new RuntimeException(res.statusCode() + " " + new String(res.body(), StandardCharsets.UTF_8));
}
return res.body();
}
static JsonObject json(byte[] bytes) {
return JsonParser.parseString(new String(bytes, StandardCharsets.UTF_8)).getAsJsonObject();
}
public static void main(String[] args) throws Exception {
// 1. Start the job: 202 {job_id, status_url, concurrency}
String body = """
{
"urls": [
"https://books.toscrape.com/catalogue/page-1.html",
"https://books.toscrape.com/catalogue/page-2.html"
],
"formats": ["markdown"],
"concurrency": 2
}
""";
String jobId = json(api("https://cdpfleet.com/v1/functions/batch", body)).get("job_id").getAsString();
System.out.println("job " + jobId);
// 2. Poll its status until it ends
String status;
do {
Thread.sleep(5000);
JsonObject job = json(api("https://cdpfleet.com/v1/jobs/" + jobId, null));
status = job.get("status").getAsString();
System.out.println(status + " " + job.get("progress"));
} while (!List.of("done", "failed", "stopped", "interrupted").contains(status));
// 3. Every result as JSON lines, one page per line
byte[] jsonl = api("https://cdpfleet.com/v1/jobs/" + jobId + "/results.jsonl", null);
Files.write(Path.of("results.jsonl"), jsonl);
System.out.println("results.jsonl: " + new String(jsonl, StandardCharsets.UTF_8).lines().count() + " pages");
}
}
// .NET 8+: dotnet new console, replace Program.cs with this, run dotnet run
using System.Text;
using System.Text.Json;
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
http.DefaultRequestHeaders.Add("x-api-key", Environment.GetEnvironmentVariable("CDPFLEET_API_KEY"));
async Task<HttpContent> Api(string url, string? body = null)
{
var res = body == null ? await http.GetAsync(url)
: await http.PostAsync(url, new StringContent(body, Encoding.UTF8, "application/json"));
if (!res.IsSuccessStatusCode) // 429: wait Retry-After seconds
throw new Exception($"{(int)res.StatusCode} {await res.Content.ReadAsStringAsync()}");
return res.Content;
}
// 1. Start the job: 202 {job_id, status_url, concurrency}
var body = """
{
"urls": [
"https://books.toscrape.com/catalogue/page-1.html",
"https://books.toscrape.com/catalogue/page-2.html"
],
"formats": ["markdown"],
"concurrency": 2
}
""";
var start = JsonDocument.Parse(await (await Api("https://cdpfleet.com/v1/functions/batch", body)).ReadAsStringAsync()).RootElement;
var jobId = start.GetProperty("job_id").GetString();
Console.WriteLine($"job {jobId}");
// 2. Poll its status until it ends
string? status;
do
{
await Task.Delay(5000);
var job = JsonDocument.Parse(await (await Api($"https://cdpfleet.com/v1/jobs/{jobId}")).ReadAsStringAsync()).RootElement;
status = job.GetProperty("status").GetString();
Console.WriteLine($"{status} {job.GetProperty("progress")}");
} while (status is not ("done" or "failed" or "stopped" or "interrupted"));
// 3. Every result as JSON lines, one page per line
var jsonl = await (await Api($"https://cdpfleet.com/v1/jobs/{jobId}/results.jsonl")).ReadAsByteArrayAsync();
await File.WriteAllBytesAsync("results.jsonl", jsonl);
Console.WriteLine($"results.jsonl: {Encoding.UTF8.GetString(jsonl).Split('\n', StringSplitOptions.RemoveEmptyEntries).Length} pages");
// Go 1.21+: save as main.go, run go run main.go
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"slices"
"strings"
"time"
)
func api(method, url, body string) []byte {
req, _ := http.NewRequest(method, url, strings.NewReader(body))
req.Header.Set("x-api-key", os.Getenv("CDPFLEET_API_KEY"))
if body != "" {
req.Header.Set("content-type", "application/json")
}
res, err := (&http.Client{Timeout: 30 * time.Second}).Do(req)
if err != nil {
log.Fatal(err)
}
defer res.Body.Close()
data, err := io.ReadAll(res.Body)
if err != nil {
log.Fatal(err)
}
if res.StatusCode >= 300 { // 429: wait Retry-After seconds
log.Fatalf("%s %s", res.Status, data)
}
return data
}
func main() {
// 1. Start the job: 202 {job_id, status_url, concurrency}
body := `{
"urls": [
"https://books.toscrape.com/catalogue/page-1.html",
"https://books.toscrape.com/catalogue/page-2.html"
],
"formats": ["markdown"],
"concurrency": 2
}`
var start struct {
JobID string `json:"job_id"`
}
if err := json.Unmarshal(api("POST", "https://cdpfleet.com/v1/functions/batch", body), &start); err != nil {
log.Fatal(err)
}
fmt.Println("job", start.JobID)
// 2. Poll its status until it ends
for {
time.Sleep(5 * time.Second)
var job struct {
Status string `json:"status"`
Progress map[string]any `json:"progress"`
}
if err := json.Unmarshal(api("GET", "https://cdpfleet.com/v1/jobs/"+start.JobID, ""), &job); err != nil {
log.Fatal(err)
}
fmt.Println(job.Status, job.Progress)
if slices.Contains([]string{"done", "failed", "stopped", "interrupted"}, job.Status) {
break
}
}
// 3. Every result as JSON lines, one page per line
jsonl := api("GET", "https://cdpfleet.com/v1/jobs/"+start.JobID+"/results.jsonl", "")
if err := os.WriteFile("results.jsonl", jsonl, 0o644); err != nil {
log.Fatal(err)
}
fmt.Printf("results.jsonl: %d pages\n", bytes.Count(jsonl, []byte("\n")))
}
A URL list in a file, only a few fields per page, a webhook and a zip, stop and resume: the batch-from-a-file recipe.
crawl
| Field | Type | Default | What it does |
|---|---|---|---|
url | string | required | Where the crawl starts. |
max_depth | number | 1 | How many links deep to follow from the start page; no upper limit. |
max_pages | number | 100 | Stop after this many pages; no upper limit. |
include / exclude | string[] | all / none | URL patterns as in map: * within a path segment, across segments, a leading / matches the path, e.g. ["/blog/"]. |
same_site | boolean | true | Only follow links on the start URL's site. |
delay_ms | number | 0 | Pause between pages, per thread. |
robots | boolean | true | Follow the site's robots.txt. |
map
| Field | Type | Default | What it does |
|---|---|---|---|
url | string | required | The site to map. |
job | boolean | required: true | Without it, map answers at once, up to 5,000 URLs. |
max_urls | number | no limit | Stop after this many URLs. |
max_depth | number | 1 | 1 = the sitemaps and the start page's links; more also opens the pages found, level by level, for their links (no content is kept). |
include / exclude, same_site | — | as in crawl | Which URLs to keep and follow. |
Each result is {"url", "source": "sitemap" | "links", "lastmod", "depth"}.
Both
| Field | Type | Default | What it does |
|---|---|---|---|
formats, wait_for, actions, extract, max_wait | — | as in scrape | Applied to every page — see scrape. |
country, proxy | — | random, the Community proxy | As for any function. |
concurrency | number | 2 | Pages at once: the threads the job holds while it runs, up to your plan's threads (asking for more uses all of them; the 202 says how many). |
deliver | object | none | {"webhook": {"url": "https://…", "events": ["page", "done"]}, "email": true, "format": "archive"} — events takes page, done (default), event (watch) and archive; see webhooks; "format": "archive" also builds the zip archive at the end. Results are always stored. |
Follow it
GET /v1/jobs/{id}—status(running,stopping,done,failed,stopped,interrupted),progress {done, failed, queued},runs,billed_seconds,results {parts, bytes}andexpires_at.GET /v1/jobs/{id}/events— a live stream (server-sent events):progress,partwhen new results are stored, anddoneat the end.GET /v1/jobs— your jobs, newest first (?status=,?type=).
curl -N https://cdpfleet.com/v1/jobs/$JOB/events -H "x-api-key: $CDPFLEET_API_KEY"
# event: progress
# data: {"status":"running","progress":{"done":40,"failed":1,"queued":112}}
Results
One JSON object per page — url, status, depth (crawl), partial, error, and the formats you asked for — stored in parts of up to 500 pages as the job runs.
GET /v1/jobs/{id}/results?cursor=0— one part:{"results": [...], "next_cursor"}. Keep passingnext_cursor; while the job runs it can return the same cursor with no results yet, and after the end it isnull.GET /v1/jobs/{id}/results.jsonl— everything as one JSON-lines download.GET /v1/jobs/{id}/results/files— every stored part as a direct download link (valid an hour), for fetching a big job in parallel.- Kept 14 days after the job ends; then
410 results_expired.
// Node.js 18+: every result of a finished job
let cursor = 0;
while (cursor !== null) {
const r = await fetch(`https://cdpfleet.com/v1/jobs/${job}/results?cursor=${cursor}`, { headers: { 'x-api-key': process.env.CDPFLEET_API_KEY } });
const { results, next_cursor } = await r.json();
for (const page of results) console.log(page.url, page.status);
cursor = next_cursor;
}
Archive (zip)
Instead of JSON lines, get everything as one zip: POST /v1/jobs/{id}/archive once the job has ended (or start the job with "deliver": {"format": "archive"}), then GET /v1/jobs/{id}/archive → {"status": "building" | "ready" | "failed", "bytes", "url"}. The url downloads straight from storage for an hour (ask again for a fresh one), and a job.archive webhook says when it's ready. Archives of any size work (zip64); they're kept as long as the job's results.
index.jsonl one line per page: url, status, depth, error, and the files below
pages/<host>/<path>/index.html html
pages/<host>/<path>/index.md markdown
pages/<host>/<path>/text.txt text
pages/<host>/<path>/screenshot.png screenshot, as an image
pages/<host>/<path>/links.json · requests.json · cookies.json · console.json · extract.json
errors.jsonl pages that failed
job.json the job, as GET /v1/jobs/{id} shows it
Paths keep the URL's segments with unsafe characters replaced; a query string or a very long path adds a short hash, so two URLs never share a folder. A map job's archive has urls.txt (one per line) and index.jsonl.
Watch: live changes on a page
POST https://cdpfleet.com/v1/functions/watch opens the page in a browser of yours and stays on it, reporting what changes while it's open: the XHR and fetch calls it makes (with their responses), WebSocket messages, and changes to a part of the page. Use it for prices, scores, order books, chat — anything that updates without a reload.
| Field | Type | Default | What it does |
|---|---|---|---|
url | string | required | The page to watch. |
duration | number | until stopped | Seconds to watch. |
filter | object | everything | {"url": ["*api*"], "selector": "#prices", "types": ["xhr", "fetch", "ws", "dom"]} — URL patterns for network events, the element whose changes count (debounced 0.5 s). |
reload_every | number | never | Reload the page every so many seconds. |
browser, launch, device | — | Chrome | As in your own browser; "launch": {"live_view": true} lets you watch the tab (GET /v1/jobs/{id}/live). WebSocket messages need a Chromium-based browser. |
deliver | object | none | Webhooks get job.event with a batch of events, at most every 2 s. |
Events arrive at once on GET /v1/jobs/{id}/events as event: event with {"events": [...]}, and are stored with the job's results: {"type": "xhr" | "fetch", "url", "method", "status", "response_body"}, {"type": "ws", "url", "direction", "data"}, {"type": "dom", "selector", "text", "html"}, each with at; bodies are cut at 64 KB.
curl -s https://cdpfleet.com/v1/functions/watch -H "x-api-key: $CDPFLEET_API_KEY" -H "content-type: application/json" -d '{"url":"https://quotes.toscrape.com/scroll","duration":300,"filter":{"url":["*api/quotes*"],"types":["xhr"]}}'
curl -N https://cdpfleet.com/v1/jobs/$JOB/events -H "x-api-key: $CDPFLEET_API_KEY"
Warmup: a browser that browses like a person
POST https://cdpfleet.com/v1/functions/warmup keeps a browser of yours browsing a site the way a visitor would — reading, scrolling, moving the mouse, following links, now and then searching — on one sticky IP, for as long as you like. Its cookies and storage build up in a persistent profile, and you can scrape pages in the same tab whenever you need, with that history behind you.
| Field | Type | Default | What it does |
|---|---|---|---|
url | string | required | Where to start. |
sites | string[] | none | More start pages to wander between. |
duration | number | until stopped | Seconds to run. |
profile | string | none | Your persistent profile to keep it in (created if missing, saved about every 10 minutes while the warmup runs and again when it ends — stopped or at its duration); reuse it later in any session or function. |
proxy | string | Community proxy | Best a sticky residential token (cdpfleet-resi-…-session-name) or your own; the same exit is used throughout. |
behavior | object | all on | {"scroll": true, "mouse": true, "typing": true, "dwell_s": [5, 40], "pages_per_site": [3, 12]}. |
cookie_every | number | 30 | Minutes between cookie deliveries (webhook job.cookies, results, and GET /v1/jobs/{id}/cookies). |
browser, launch, device, deliver | — | Camoufox | As for watch, except that the default browser is Camoufox. |
POST /v1/jobs/{id}/scrapewith a scrape body — the warmup pauses, loads the page in its own tab (same cookies, same IP), answers like scrape, and carries on.GET /v1/jobs/{id}/cookies— the cookies now, or after the end the last ones it delivered.- It never follows logout, delete, checkout or order links and never submits forms other than searches. It never solves a CAPTCHA or waits on one: on a challenge page it goes back or elsewhere on the site, counts it (
progress.challenges) and leaves that site alone for a while. - Progress:
{visits, sites, challenges, scrapes, last_url, cookies_at}; results also log each visit.
Watch and warmup run in your own browser session: they hold its threads (2 for a headful browser) and are billed as a session, and continue past the 24-hour session limit by themselves.
Stop and resume
DELETE /v1/jobs/{id} stops a job after the pages in flight (stopping, then stopped); its results stay. POST /v1/jobs/{id}/resume continues a stopped or interrupted job where it left off — a crawl keeps its queue and the pages it has seen, so nothing is fetched twice. A job is interrupted when its run can't continue: your minutes or threads running out, or a restart on our side.
Billing
A running job holds concurrency threads and uses browser-minutes per second for each, like that many sessions; billed_seconds is the total in thread-seconds. Starting a job needs that many free threads (429 threads_exceeded otherwise). The Community proxy and your own proxies cost nothing extra; residential traffic is billed per GB.
Webhooks and email
With "deliver": {"webhook": {"url": "https://…"}} we POST JSON to your URL. events picks what you get (default ["done"]):
"done"—job.donewhen the job ends, with itsstatus:done,stopped(you stopped it),failedorinterrupted."page"—job.pagefor each page of a batch or crawl (a page over 1 MB comes asresult_url)."event"—job.eventbatches of a watch's live events, at most one request per 2 s (the last batch, sent when the watch stops, can follow sooner)."archive"—job.archivewith the zip'surlandbytesonce it's ready (jobs with"format": "archive").
Each request carries x-cdpfleet-event, x-cdpfleet-delivery (a unique id; retries reuse it) and x-cdpfleet-signature: t=<unix time>,v1=<hex>. Answer with any 2xx; otherwise we retry after 10 s, 1 min, 5 min, 30 min and 2 h. The URL must be public https.
Your signing secret (whsec_…) is the same for all your jobs: GET /v1/me/webhook-secret, and POST /v1/me/webhook-secret/rotate to replace it. Check every request:
// Node.js: verify x-cdpfleet-signature on the raw request body
import crypto from 'node:crypto';
function verify(rawBody, header, secret, toleranceS = 300) {
const { t, v1 } = Object.fromEntries(header.split(',').map((kv) => kv.split('=')));
if (Math.abs(Date.now() / 1000 - Number(t)) > toleranceS) return false;
const want = crypto.createHmac('sha256', secret).update(`${t}.${rawBody}`).digest('hex');
return crypto.timingSafeEqual(Buffer.from(want), Buffer.from(v1));
}
The same check in Python, Java, C# and Go, de-duplicating retries and rotating the secret: Webhooks.
"email": true sends a short note to your account's address when the job ends.
Recipe: a batch from a file
A file of URLs, a few fields from each page, a signed webhook when it's done and a zip of the lot — and a stop and resume halfway. Measured on 2026-11-12 with a file of 101 URLs: 100 book pages of books.toscrape.com, listed from its catalogue pages 1–5, and one page that doesn't exist.
1. Send the file
urls.txt has one URL per line. Up to about 10,000 fit in the request (1 MB), so read the file and send it as urls: our 101 made a 10 KB body. For a longer list, put the file behind a link the service can download — a presigned S3, R2 or GCS link works — and send "urls_url" instead of urls. It is fetched once, before the job starts: a link that doesn't answer 200, or a line that isn't a public URL, is a 400 invalid_option at once ("urls_url: urls_url returned 404") and nothing is billed. Either way the list is stored with the job, and a resume reads it from there.
2. Ask for the fields, not the page
"formats": [] with an extract keeps only what the selectors match (without formats you'd get each page's whole HTML). Each line of the results:
{"url":"https://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html","status":200,
"extract":{"title":"A Light in the Attic","price":"£51.77","stock":"In stock (22 available)"}}
- Check
status, not onlyextract. The missing page came back"status": 404with"title": "404 Not Found"— the site's error page has anh1too — and"price": null. All 99 other book pages that loaded had a title and a price. - A page that didn't load has
errorand noextract: 1 of the 101 ("status": null, "error": "page_timeout"). A job doesn't try a page twice, so send those URLs again as a batch of their own — this one loaded the second time:
grep '"error":' results.jsonl | grep -o '"url":"[^"]*"' | cut -d'"' -f4 > urls.txt # then run the same batch again
3. A webhook and a zip
"deliver": {"webhook": {"url": "https://…", "events": ["done", "archive"]}, "format": "archive"} sends job.done when the job ends and job.archive with the zip's bytes and download url once it is built. Both arrived signed in the same second as the job's ended_at (check them as in webhooks); job.done carried the final progress, {"done": 100, "failed": 1, "queued": 0, "total": 101} — a 404 is a page done, only pages with an error count as failed.
The zip was ready 0.1 s after the end: an extract.json per page under pages/<host>/<path>/, index.jsonl, errors.jsonl (the page that timed out) and job.json — 103 files, 44,934 bytes, almost twice results.jsonl's 24,186. With a few fields per page the JSON lines are the compact form; the zip pays off with Markdown, HTML or screenshots (a third of the JSON lines in the crawl case).
4. The whole run in code
Read urls.txt, start the job, poll it until it ends, then download results.jsonl and the zip (its link is a plain storage link: no API key). Every tab was run on 2026-11-12 against a 12-line file: 12 results and a 6.6 KB zip each time.
# curl: the job id and status are read with grep; awk turns urls.txt into the "urls" array
H="x-api-key: $CDPFLEET_API_KEY"
OPTS='{"formats":[],"extract":{"title":"h1","price":".product_main .price_color","stock":".product_main .availability"},"concurrency":3,"deliver":{"webhook":{"url":"https://example.com/hooks/cdpfleet","events":["done","archive"]},"format":"archive"}}'
JOB=$(awk -v opts="$OPTS" 'NF { u = u (u ? "," : "") "\"" $1 "\"" } END { print "{\"urls\":[" u "]," substr(opts, 2) }' urls.txt |
curl -s https://cdpfleet.com/v1/functions/batch -H "$H" -H "content-type: application/json" -d @- | grep -o '"job_id":"[^"]*"' | cut -d'"' -f4)
echo "job $JOB"
while sleep 5; do
STATUS=$(curl -s https://cdpfleet.com/v1/jobs/$JOB -H "$H" | grep -o '"status":"[a-z]*"' | head -1 | cut -d'"' -f4)
echo "$STATUS"
case $STATUS in done|failed|stopped|interrupted) break ;; esac
done
curl -s https://cdpfleet.com/v1/jobs/$JOB/results.jsonl -H "$H" -o results.jsonl
wc -l results.jsonl
[ "$STATUS" = done ] || exit 1 # the zip is built once the job is done
while sleep 2; do
ARCHIVE=$(curl -s https://cdpfleet.com/v1/jobs/$JOB/archive -H "$H")
case $ARCHIVE in *'"status":"ready"'*) break ;; *'"status":"failed"'*) echo "$ARCHIVE"; exit 1 ;; esac
done
curl -s "$(echo "$ARCHIVE" | grep -o '"url":"[^"]*"' | cut -d'"' -f4)" -o job.zip # a storage link: no key
ls -l job.zip
// Node.js 18+: save as batch.mjs, run node batch.mjs
import { readFile, writeFile } from 'node:fs/promises';
async function api(url, body) {
const res = await fetch(url, {
method: body ? 'POST' : 'GET',
headers: { 'x-api-key': process.env.CDPFLEET_API_KEY, ...(body && { 'content-type': 'application/json' }) },
body: body && JSON.stringify(body),
signal: AbortSignal.timeout(30000),
});
if (!res.ok) throw new Error(`${res.status} ${await res.text()}`); // 429: wait Retry-After seconds
return res;
}
// 1. Start the job with the URLs in urls.txt, one per line: 202 {job_id, status_url, concurrency}
const urls = (await readFile('urls.txt', 'utf8')).split(/\s+/).filter(Boolean);
const { job_id } = await (await api('https://cdpfleet.com/v1/functions/batch', {
urls,
formats: [],
extract: {
title: 'h1',
price: '.product_main .price_color',
stock: '.product_main .availability',
},
concurrency: 3,
deliver: {
webhook: {
url: 'https://example.com/hooks/cdpfleet',
events: ['done', 'archive'],
},
format: 'archive',
},
})).json();
console.log('job', job_id);
// 2. Poll its status until it ends
let job;
do {
await new Promise((r) => setTimeout(r, 5000));
job = await (await api(`https://cdpfleet.com/v1/jobs/${job_id}`)).json();
console.log(job.status, JSON.stringify(job.progress));
} while (!['done', 'failed', 'stopped', 'interrupted'].includes(job.status));
// 3. Every result as JSON lines, one page per line
const jsonl = await (await api(`https://cdpfleet.com/v1/jobs/${job_id}/results.jsonl`)).text();
await writeFile('results.jsonl', jsonl);
console.log(`results.jsonl: ${jsonl.split('\n').filter(Boolean).length} pages`);
// 4. The zip: "format": "archive" builds it once the job is done
if (job.status !== 'done') throw new Error(`job ${job.status}: no archive`);
let archive;
do {
await new Promise((r) => setTimeout(r, 2000));
archive = await (await api(`https://cdpfleet.com/v1/jobs/${job_id}/archive`)).json();
} while (['none', 'building'].includes(archive.status));
if (archive.status !== 'ready') throw new Error(`archive ${JSON.stringify(archive)}`);
const zip = Buffer.from(await (await fetch(archive.url)).arrayBuffer()); // a storage link: no key
await writeFile('job.zip', zip);
console.log(`job.zip: ${zip.length} bytes`);
# Python 3 with requests (pip install requests): save as batch.py, run python batch.py
import os
import time
import requests
def api(method, url, **kw):
r = requests.request(method, url, headers={"x-api-key": os.environ["CDPFLEET_API_KEY"]}, timeout=30, **kw)
if not r.ok:
raise SystemExit(f"{r.status_code} {r.text}") # 429: wait r.headers["Retry-After"] seconds
return r
# 1. Start the job with the URLs in urls.txt, one per line: 202 {job_id, status_url, concurrency}
urls = open("urls.txt").read().split()
job_id = api("POST", "https://cdpfleet.com/v1/functions/batch", json={
"urls": urls,
"formats": [],
"extract": {
"title": "h1",
"price": ".product_main .price_color",
"stock": ".product_main .availability",
},
"concurrency": 3,
"deliver": {
"webhook": {
"url": "https://example.com/hooks/cdpfleet",
"events": ["done", "archive"],
},
"format": "archive",
},
}).json()["job_id"]
print("job", job_id)
# 2. Poll its status until it ends
while True:
time.sleep(5)
job = api("GET", f"https://cdpfleet.com/v1/jobs/{job_id}").json()
print(job["status"], job["progress"])
if job["status"] in ("done", "failed", "stopped", "interrupted"):
break
# 3. Every result as JSON lines, one page per line
jsonl = api("GET", f"https://cdpfleet.com/v1/jobs/{job_id}/results.jsonl").content
open("results.jsonl", "wb").write(jsonl)
print(f"results.jsonl: {len(jsonl.splitlines())} pages")
# 4. The zip: "format": "archive" builds it once the job is done
if job["status"] != "done":
raise SystemExit(f"job {job['status']}: no archive")
while True:
time.sleep(2)
archive = api("GET", f"https://cdpfleet.com/v1/jobs/{job_id}/archive").json()
if archive["status"] not in ("none", "building"):
break
if archive["status"] != "ready":
raise SystemExit(f"archive {archive}")
zip_bytes = requests.get(archive["url"], timeout=60).content # a storage link: no key
open("job.zip", "wb").write(zip_bytes)
print(f"job.zip: {len(zip_bytes)} bytes")
// Java 17+ and Gson (com.google.code.gson:gson): save as Main.java, run java -cp gson-2.11.0.jar Main.java
import com.google.gson.*;
import java.net.URI;
import java.net.http.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.time.Duration;
import java.util.List;
public class Main {
static final HttpClient HTTP = HttpClient.newHttpClient();
static byte[] api(String url, String body) throws Exception {
HttpRequest.Builder req = HttpRequest.newBuilder(URI.create(url))
.header("x-api-key", System.getenv("CDPFLEET_API_KEY"))
.timeout(Duration.ofSeconds(30));
if (body != null) req.header("content-type", "application/json").POST(HttpRequest.BodyPublishers.ofString(body));
HttpResponse<byte[]> res = HTTP.send(req.build(), HttpResponse.BodyHandlers.ofByteArray());
if (res.statusCode() >= 300) { // 429: wait Retry-After seconds
throw new RuntimeException(res.statusCode() + " " + new String(res.body(), StandardCharsets.UTF_8));
}
return res.body();
}
static JsonObject json(byte[] bytes) {
return JsonParser.parseString(new String(bytes, StandardCharsets.UTF_8)).getAsJsonObject();
}
public static void main(String[] args) throws Exception {
// 1. Start the job with the URLs in urls.txt, one per line: 202 {job_id, status_url, concurrency}
JsonObject body = JsonParser.parseString("""
{
"formats": [],
"extract": {
"title": "h1",
"price": ".product_main .price_color",
"stock": ".product_main .availability"
},
"concurrency": 3,
"deliver": {
"webhook": {
"url": "https://example.com/hooks/cdpfleet",
"events": ["done", "archive"]
},
"format": "archive"
}
}
""").getAsJsonObject();
body.add("urls", new Gson().toJsonTree(Files.readString(Path.of("urls.txt")).strip().split("\\s+")));
String jobId = json(api("https://cdpfleet.com/v1/functions/batch", body.toString())).get("job_id").getAsString();
System.out.println("job " + jobId);
// 2. Poll its status until it ends
String status;
do {
Thread.sleep(5000);
JsonObject job = json(api("https://cdpfleet.com/v1/jobs/" + jobId, null));
status = job.get("status").getAsString();
System.out.println(status + " " + job.get("progress"));
} while (!List.of("done", "failed", "stopped", "interrupted").contains(status));
// 3. Every result as JSON lines, one page per line
byte[] jsonl = api("https://cdpfleet.com/v1/jobs/" + jobId + "/results.jsonl", null);
Files.write(Path.of("results.jsonl"), jsonl);
System.out.println("results.jsonl: " + new String(jsonl, StandardCharsets.UTF_8).lines().count() + " pages");
// 4. The zip: "format": "archive" builds it once the job is done
if (!status.equals("done")) throw new RuntimeException("job " + status + ": no archive");
JsonObject archive;
do {
Thread.sleep(2000);
archive = json(api("https://cdpfleet.com/v1/jobs/" + jobId + "/archive", null));
} while (List.of("none", "building").contains(archive.get("status").getAsString()));
if (!archive.get("status").getAsString().equals("ready")) throw new RuntimeException("archive " + archive);
byte[] zip = HTTP.send(HttpRequest.newBuilder(URI.create(archive.get("url").getAsString())).build(), // a storage link: no key
HttpResponse.BodyHandlers.ofByteArray()).body();
Files.write(Path.of("job.zip"), zip);
System.out.println("job.zip: " + zip.length + " bytes");
}
}
// .NET 8+: dotnet new console, replace Program.cs with this, run dotnet run
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
http.DefaultRequestHeaders.Add("x-api-key", Environment.GetEnvironmentVariable("CDPFLEET_API_KEY"));
async Task<HttpContent> Api(string url, string? body = null)
{
var res = body == null ? await http.GetAsync(url)
: await http.PostAsync(url, new StringContent(body, Encoding.UTF8, "application/json"));
if (!res.IsSuccessStatusCode) // 429: wait Retry-After seconds
throw new Exception($"{(int)res.StatusCode} {await res.Content.ReadAsStringAsync()}");
return res.Content;
}
// 1. Start the job with the URLs in urls.txt, one per line: 202 {job_id, status_url, concurrency}
var body = JsonNode.Parse("""
{
"formats": [],
"extract": {
"title": "h1",
"price": ".product_main .price_color",
"stock": ".product_main .availability"
},
"concurrency": 3,
"deliver": {
"webhook": {
"url": "https://example.com/hooks/cdpfleet",
"events": ["done", "archive"]
},
"format": "archive"
}
}
""")!.AsObject();
body["urls"] = JsonSerializer.SerializeToNode(File.ReadAllText("urls.txt").Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries));
var start = JsonDocument.Parse(await (await Api("https://cdpfleet.com/v1/functions/batch", body.ToJsonString())).ReadAsStringAsync()).RootElement;
var jobId = start.GetProperty("job_id").GetString();
Console.WriteLine($"job {jobId}");
// 2. Poll its status until it ends
string? status;
do
{
await Task.Delay(5000);
var job = JsonDocument.Parse(await (await Api($"https://cdpfleet.com/v1/jobs/{jobId}")).ReadAsStringAsync()).RootElement;
status = job.GetProperty("status").GetString();
Console.WriteLine($"{status} {job.GetProperty("progress")}");
} while (status is not ("done" or "failed" or "stopped" or "interrupted"));
// 3. Every result as JSON lines, one page per line
var jsonl = await (await Api($"https://cdpfleet.com/v1/jobs/{jobId}/results.jsonl")).ReadAsByteArrayAsync();
await File.WriteAllBytesAsync("results.jsonl", jsonl);
Console.WriteLine($"results.jsonl: {Encoding.UTF8.GetString(jsonl).Split('\n', StringSplitOptions.RemoveEmptyEntries).Length} pages");
// 4. The zip: "format": "archive" builds it once the job is done
if (status != "done") throw new Exception($"job {status}: no archive");
JsonElement archive;
do
{
await Task.Delay(2000);
archive = JsonDocument.Parse(await (await Api($"https://cdpfleet.com/v1/jobs/{jobId}/archive")).ReadAsStringAsync()).RootElement;
} while (archive.GetProperty("status").GetString() is "none" or "building");
if (archive.GetProperty("status").GetString() != "ready") throw new Exception($"archive {archive}");
var zip = await new HttpClient().GetByteArrayAsync(archive.GetProperty("url").GetString()); // a storage link: no key
await File.WriteAllBytesAsync("job.zip", zip);
Console.WriteLine($"job.zip: {zip.Length} bytes");
// Go 1.21+: save as main.go, run go run main.go
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"slices"
"strings"
"time"
)
func api(method, url, body string) []byte {
req, _ := http.NewRequest(method, url, strings.NewReader(body))
req.Header.Set("x-api-key", os.Getenv("CDPFLEET_API_KEY"))
if body != "" {
req.Header.Set("content-type", "application/json")
}
res, err := (&http.Client{Timeout: 30 * time.Second}).Do(req)
if err != nil {
log.Fatal(err)
}
defer res.Body.Close()
data, err := io.ReadAll(res.Body)
if err != nil {
log.Fatal(err)
}
if res.StatusCode >= 300 { // 429: wait Retry-After seconds
log.Fatalf("%s %s", res.Status, data)
}
return data
}
func main() {
// 1. Start the job with the URLs in urls.txt, one per line: 202 {job_id, status_url, concurrency}
file, err := os.ReadFile("urls.txt")
if err != nil {
log.Fatal(err)
}
var fields map[string]any
if err := json.Unmarshal([]byte(`{
"formats": [],
"extract": {
"title": "h1",
"price": ".product_main .price_color",
"stock": ".product_main .availability"
},
"concurrency": 3,
"deliver": {
"webhook": {
"url": "https://example.com/hooks/cdpfleet",
"events": ["done", "archive"]
},
"format": "archive"
}
}`), &fields); err != nil {
log.Fatal(err)
}
fields["urls"] = strings.Fields(string(file))
body, _ := json.Marshal(fields)
var start struct {
JobID string `json:"job_id"`
}
if err := json.Unmarshal(api("POST", "https://cdpfleet.com/v1/functions/batch", string(body)), &start); err != nil {
log.Fatal(err)
}
fmt.Println("job", start.JobID)
// 2. Poll its status until it ends
var status string
for {
time.Sleep(5 * time.Second)
var job struct {
Status string `json:"status"`
Progress map[string]any `json:"progress"`
}
if err := json.Unmarshal(api("GET", "https://cdpfleet.com/v1/jobs/"+start.JobID, ""), &job); err != nil {
log.Fatal(err)
}
fmt.Println(job.Status, job.Progress)
status = job.Status
if slices.Contains([]string{"done", "failed", "stopped", "interrupted"}, job.Status) {
break
}
}
// 3. Every result as JSON lines, one page per line
jsonl := api("GET", "https://cdpfleet.com/v1/jobs/"+start.JobID+"/results.jsonl", "")
if err := os.WriteFile("results.jsonl", jsonl, 0o644); err != nil {
log.Fatal(err)
}
fmt.Printf("results.jsonl: %d pages\n", bytes.Count(jsonl, []byte("\n")))
// 4. The zip: "format": "archive" builds it once the job is done
if status != "done" {
log.Fatalf("job %s: no archive", status)
}
var archive struct {
Status string `json:"status"`
URL string `json:"url"`
}
for archive.Status == "" || archive.Status == "none" || archive.Status == "building" {
time.Sleep(2 * time.Second)
if err := json.Unmarshal(api("GET", "https://cdpfleet.com/v1/jobs/"+start.JobID+"/archive", ""), &archive); err != nil {
log.Fatal(err)
}
}
if archive.Status != "ready" {
log.Fatalf("archive %s", archive.Status)
}
res, err := http.Get(archive.URL) // a storage link: no key
if err != nil {
log.Fatal(err)
}
defer res.Body.Close()
zip, err := io.ReadAll(res.Body)
if err != nil {
log.Fatal(err)
}
if err := os.WriteFile("job.zip", zip, 0o644); err != nil {
log.Fatal(err)
}
fmt.Printf("job.zip: %d bytes\n", len(zip))
}
5. Stop it and resume it
curl -s -X DELETE https://cdpfleet.com/v1/jobs/$JOB -H "x-api-key: $CDPFLEET_API_KEY" # "status":"stopping"
curl -s -X POST https://cdpfleet.com/v1/jobs/$JOB/resume -H "x-api-key: $CDPFLEET_API_KEY" # {"job_id":"…","status":"running"}
In another run of the same file, on 2026-11-14, we stopped the job after 47 pages. DELETE answered stopping; the job was stopped 11.4 s later with 50 pages stored — the ones in flight finish — and job.done arrived with "status": "stopped" and {"done": 49, "failed": 1, "queued": 51}. No zip is built at a stop. A resume while it is still stopping is a 409 not_resumable (measured 2026-11-12); once stopped, POST …/resume answered 202, the second run fetched only the 51 URLs the first hadn't reached, and the job ended done with "runs": 2 and every result kept: results.jsonl held 101 lines for 101 different URLs. Then came job.done and job.archive, both signed.
6. Time and cost
At concurrency 3 the 101 URLs took 162 s — 37 pages a minute — and billed_seconds was 486: concurrency × running time, 4.8 thread-seconds a URL. The stopped job was billed 258 + 264 thread-seconds for its two runs, again about concurrency × the time each ran; the pause between them cost nothing. The Community proxy (the default) adds nothing.
Errors
| Status | error | When |
|---|---|---|
| 400 | invalid_option / invalid_url | A field out of range, or a URL that isn't public http(s); the message names it. |
| 403 | jobs_not_available | Jobs come with paid plans. |
| 404 | no such job | Not one of your jobs. |
| 409 | not_resumable | Only stopped and interrupted jobs resume. |
| 410 | results_expired / job_expired | More than 14 days after the end. |
| 429 | threads_exceeded, daily_quota_exhausted | Not enough free threads or minutes to start; wait Retry-After. |