> ## Documentation Index
> Fetch the complete documentation index at: https://docs.zenrows.com/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> The Zenrows HTTP API serves Fetch and Extract (extract=auto) at https://api.zenrows.com/v1/, Crawl at https://api.zenrows.com/v1/crawls, and Batch at https://async.api.zenrows.com/v1. Fetch, Extract, Crawl and Batch are described in OpenAPI 3.1 at https://www.zenrows.com/openapi.json and listed in the RFC 9727 API catalog at https://www.zenrows.com/.well-known/api-catalog. Every endpoint also has its own page under /api-reference with its schema. Use the spec for exact parameter names and types. Crawl's endpoints, parameters and errors are also at https://docs.zenrows.com/crawl/endpoints.md. To call Zenrows from an agent, connect the MCP server at https://mcp.zenrows.com/mcp. To search these docs from an agent, connect the docs MCP server at https://docs.zenrows.com/mcp. Agent skills for Zenrows are published at https://github.com/ZenRows/cli and install with `npx skills add ZenRows/cli`.

# Batch API Reference

> Every Batch request over HTTP: create jobs, track runs, collect results, webhooks, reruns, cost, idempotency and error codes, with examples in Python, Node.js, Java, PHP, Go, Ruby and cURL.

> [!NOTE]
>
> Batch is available to every Zenrows account. You need an active Zenrows API key. Replace `YOUR_ZENROWS_API_KEY` in every example with your key.

> [!TIP]
>
> Each endpoint on this page also has its own page in the [API Reference](https://docs.zenrows.com/api-reference.md#endpoint-reference), with typed parameters, a response example for every status code, and a playground that sends the request with your key.

## Basics

* **Base URL:** `https://async.api.zenrows.com/v1`
* **Authentication:** send `X-API-Key: YOUR_ZENROWS_API_KEY` on every request. The key travels in a header, never in the URL.
* **OpenAPI spec:** the Batch API is described in OpenAPI 3.1 at [www.zenrows.com/openapi.json](https://www.zenrows.com/openapi.json).
* **Bodies:** send JSON with `Content-Type: application/json` and receive JSON. Errors come back as `application/problem+json` (RFC 9457) with a stable `code` you can branch on, and a `type` that links to the code's entry in [API error codes](https://docs.zenrows.com/api-error-codes.md#batch).
* **Request ID:** every response carries an `X-Request-ID` header. Include it, with the job ID, when you contact support.
* **Ownership:** jobs belong to your account, so any of the account's API keys can read and manage them. A job's runs always spend the key it was created with, including that key's [credit caps](#api-key-credit-caps-and-batch). Another account gets `404`.
* **Limits:** the per-request and per-account limits are in the [introduction](https://docs.zenrows.com/batch/introduction.md#limits).

The Node.js examples below reuse this small wrapper, which adds authentication, sets the `Content-Type` header when there is a body, and turns error responses into thrown objects:

```javascript Node.js theme={"theme":"css-variables"}
const BASE = process.env.BATCH_API_URL ?? "https://async.api.zenrows.com/v1";
const API_KEY = process.env.ZENROWS_API_KEY;

async function api(method, path, { body, query, headers } = {}) {
  const url = new URL(BASE + path);
  for (const [k, v] of Object.entries(query ?? {})) {
    if (v !== undefined && v !== null) url.searchParams.set(k, v);
  }
  const res = await fetch(url, {
    method,
    headers: {
      "X-API-Key": API_KEY,
      ...(body ? { "Content-Type": "application/json" } : {}),
      ...headers,
    },
    body: body ? JSON.stringify(body) : undefined,
  });

  if (res.status === 204) return null;
  const isJson = (res.headers.get("content-type") ?? "").includes("json");
  const payload = isJson ? await res.json() : await res.arrayBuffer();
  if (!res.ok) {
    // RFC 7807 problem: { type, title, status, detail, code, invalid_tasks? }
    const err = new Error(payload?.detail || payload?.title || `HTTP ${res.status}`);
    err.status = res.status;
    err.code = payload?.code;
    err.problem = payload;
    throw err;
  }
  return payload;
}
```

## 1. Create your jobs

There are several ways to create a job. Pick the one that matches how your URLs arrive.

### Submit a job with all URLs up front

Create a **closed job** (one where you know all URLs up front) with `POST /jobs`. The response includes a `job_id` and the initial run status.

> [!NOTE]
>
> `POST /jobs` returns **`201 Created`** for fewer than 10,000 tasks and **`202 Accepted`** at 10,000 or more, whether the tasks are inline or read from a CSV upload. Scheduled-job submits return `201`. Handle both statuses the same way. The request shape and response body are identical, so treat both the same: store `job_id`, then poll until `stats.completed >= stats.total` (or use a webhook). On a `202`, `stats.total` is correct immediately, but `GET /jobs/{id}/results` may return partial pages for a few seconds while the task rows finish writing.

```python Python theme={"theme":"css-variables"}
## pip install requests
import requests, json

headers = {'X-API-Key': 'YOUR_ZENROWS_API_KEY', 'Content-Type': 'application/json'}
payload = {
    'type': 'regular',
    'status': 'closed',
    'zenrows_params': {'js_render': 'true', 'premium_proxy': 'true'},
    'tasks': [
        {'url': 'https://www.scrapingcourse.com/ecommerce/product/abominable-hoodie', 'external_id': 'order-1'},
        {'url': 'https://www.scrapingcourse.com/ecommerce/product/adrienne-trek-jacket', 'external_id': 'order-2'},
    ],
}
response = requests.post('https://async.api.zenrows.com/v1/jobs', headers=headers, data=json.dumps(payload))
print(response.json())
```

```javascript Node.js theme={"theme":"css-variables"}
// Reuses the api() helper from the Basics section.
const submitted = await api("POST", "/jobs", {
  body: {
    type: "regular",
    status: "closed",
    zenrows_params: { js_render: "true", premium_proxy: "true" },
    tasks: [
      { url: "https://www.scrapingcourse.com/ecommerce/product/abominable-hoodie", external_id: "order-1" },
      { url: "https://www.scrapingcourse.com/ecommerce/product/adrienne-trek-jacket", external_id: "order-2" },
    ],
  },
});
console.log("submitted", submitted.job_id, submitted.latest_run.status);
```

```java Java theme={"theme":"css-variables"}
import org.apache.hc.client5.http.fluent.Request;
import org.apache.hc.core5.http.ContentType;

public class SubmitJob {
    public static void main(final String... args) throws Exception {
        String body = "{"
            + "\"type\":\"regular\",\"status\":\"closed\","
            + "\"zenrows_params\":{\"js_render\":\"true\",\"premium_proxy\":\"true\"},"
            + "\"tasks\":["
            + "{\"url\":\"https://www.scrapingcourse.com/ecommerce/product/abominable-hoodie\",\"external_id\":\"order-1\"},"
            + "{\"url\":\"https://www.scrapingcourse.com/ecommerce/product/adrienne-trek-jacket\",\"external_id\":\"order-2\"}"
            + "]}";
        String response = Request.post("https://async.api.zenrows.com/v1/jobs")
                .addHeader("X-API-Key", "YOUR_ZENROWS_API_KEY")
                .bodyString(body, ContentType.APPLICATION_JSON)
                .execute().returnContent().asString();
        System.out.println(response);
    }
}
```

```php PHP theme={"theme":"css-variables"}
<?php
$payload = json_encode([
    'type' => 'regular',
    'status' => 'closed',
    'zenrows_params' => ['js_render' => 'true', 'premium_proxy' => 'true'],
    'tasks' => [
        ['url' => 'https://www.scrapingcourse.com/ecommerce/product/abominable-hoodie', 'external_id' => 'order-1'],
        ['url' => 'https://www.scrapingcourse.com/ecommerce/product/adrienne-trek-jacket', 'external_id' => 'order-2'],
    ],
]);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://async.api.zenrows.com/v1/jobs');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['X-API-Key: YOUR_ZENROWS_API_KEY', 'Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
echo $response . PHP_EOL;
curl_close($ch);
?>
```

```go Go theme={"theme":"css-variables"}
package main

import (
    "bytes"
    "io"
    "log"
    "net/http"
)

func main() {
    payload := []byte(`{
        "type": "regular",
        "status": "closed",
        "zenrows_params": { "js_render": "true", "premium_proxy": "true" },
        "tasks": [
            { "url": "https://www.scrapingcourse.com/ecommerce/product/abominable-hoodie", "external_id": "order-1" },
            { "url": "https://www.scrapingcourse.com/ecommerce/product/adrienne-trek-jacket", "external_id": "order-2" }
        ]
    }`)
    req, err := http.NewRequest("POST", "https://async.api.zenrows.com/v1/jobs", bytes.NewBuffer(payload))
    if err != nil {
        log.Fatalln(err)
    }
    req.Header.Set("X-API-Key", "YOUR_ZENROWS_API_KEY")
    req.Header.Set("Content-Type", "application/json")
    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        log.Fatalln(err)
    }
    defer resp.Body.Close()
    body, _ := io.ReadAll(resp.Body)
    log.Println(string(body))
}
```

```ruby Ruby theme={"theme":"css-variables"}
# gem install faraday
require 'faraday'
require 'json'

payload = {
    type: 'regular',
    status: 'closed',
    zenrows_params: { js_render: 'true', premium_proxy: 'true' },
    tasks: [
        { url: 'https://www.scrapingcourse.com/ecommerce/product/abominable-hoodie', external_id: 'order-1' },
        { url: 'https://www.scrapingcourse.com/ecommerce/product/adrienne-trek-jacket', external_id: 'order-2' }
    ]
}
conn = Faraday.new
res = conn.post('https://async.api.zenrows.com/v1/jobs') do |req|
    req.headers['X-API-Key'] = 'YOUR_ZENROWS_API_KEY'
    req.headers['Content-Type'] = 'application/json'
    req.body = payload.to_json
end
print(res.body)
```

```bash cURL theme={"theme":"css-variables"}
curl -X POST "https://async.api.zenrows.com/v1/jobs" \
  -H "X-API-Key: YOUR_ZENROWS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "regular",
    "status": "closed",
    "zenrows_params": { "js_render": "true", "premium_proxy": "true" },
    "tasks": [
      { "url": "https://www.scrapingcourse.com/ecommerce/product/abominable-hoodie", "external_id": "order-1" },
      { "url": "https://www.scrapingcourse.com/ecommerce/product/adrienne-trek-jacket", "external_id": "order-2" }
    ]
  }'
```

### Configure the scrape and per-URL options

`zenrows_params` applies to every URL in the job. A per-task `zenrows_params` overrides the job-level keys for that URL, so you can set the common case once and tune exceptions such as a different `proxy_country`.

Common keys:

* [`js_render`](https://docs.zenrows.com/fetch/features/js-rendering)
* [`premium_proxy`](https://docs.zenrows.com/fetch/features/premium-proxy)
* [`proxy_country`](https://docs.zenrows.com/fetch/features/proxy-country)
* [`js_instructions`](https://docs.zenrows.com/fetch/features/js-instructions)
* [`wait_for`](https://docs.zenrows.com/fetch/features/wait-for)
* [`wait`](https://docs.zenrows.com/fetch/features/wait)
* [`block_resources`](https://docs.zenrows.com/fetch/features/block-resources)
* [`custom_headers`](https://docs.zenrows.com/fetch/features/headers)
* [`json_response`](https://docs.zenrows.com/fetch/features/json-response)
* [`css_extractor`](https://docs.zenrows.com/fetch/features/css-extractor)
* [`extract`](https://docs.zenrows.com/extract/setup) and `extract_fields`
* [`mode`](https://docs.zenrows.com/fetch/features/adaptive-stealth-mode) (`auto` only)
* [`autoparse`](https://docs.zenrows.com/fetch/features/autoparse) (deprecated, use `extract`)
* `response_type` ([`markdown`](https://docs.zenrows.com/fetch/features/markdown), [`plaintext`](https://docs.zenrows.com/fetch/features/plaintext), or [`pdf`](https://docs.zenrows.com/fetch/features/pdf))
* [`outputs`](https://docs.zenrows.com/fetch/features/output-filters)
* [`original_status`](https://docs.zenrows.com/fetch/features/other#original-http-code)
* [`allowed_status_codes`](https://docs.zenrows.com/fetch/features/other#return-content-on-error)
* [`session_id`](https://docs.zenrows.com/fetch/features/other#session-id)

Batch doesn't take the screenshot parameters. An unknown key, or a value the parameter doesn't accept, rejects the whole submit with `400 invalid_argument`, and `invalid_tasks[]` names the task and the key (`unknown_param` or `invalid_param_value`).

```python Python theme={"theme":"css-variables"}
## pip install requests
import requests, json

headers = {'X-API-Key': 'YOUR_ZENROWS_API_KEY', 'Content-Type': 'application/json'}
payload = {
    'type': 'regular',
    'status': 'closed',
    'zenrows_params': {'js_render': 'true', 'proxy_country': 'us', 'response_type': 'markdown'},
    'tasks': [
        {'url': 'https://www.scrapingcourse.com/ecommerce/product/artemis-running-short',
        'external_id': 'order-42', 'zenrows_params': {'proxy_country': 'de'}},
        {'url': 'https://www.scrapingcourse.com/ecommerce/product/atomic-endurance-tee',
        'metadata': {'sku': 'ABC-1'}},
    ],
}
response = requests.post('https://async.api.zenrows.com/v1/jobs', headers=headers, data=json.dumps(payload))
print(response.json())
```

```javascript Node.js theme={"theme":"css-variables"}
const job = await api("POST", "/jobs", {
  body: {
    type: "regular",
    status: "closed",
    zenrows_params: { js_render: "true", proxy_country: "us", response_type: "markdown" },
    tasks: [
      { url: "https://www.scrapingcourse.com/ecommerce/product/artemis-running-short",
        external_id: "order-42", zenrows_params: { proxy_country: "de" } },
      { url: "https://www.scrapingcourse.com/ecommerce/product/atomic-endurance-tee",
        metadata: { sku: "ABC-1" } },
    ],
  },
});
console.log(job.job_id);
```

```java Java theme={"theme":"css-variables"}
import org.apache.hc.client5.http.fluent.Request;
import org.apache.hc.core5.http.ContentType;

public class ConfigureJob {
    public static void main(final String... args) throws Exception {
        String body = "{"
            + "\"type\":\"regular\",\"status\":\"closed\","
            + "\"zenrows_params\":{\"js_render\":\"true\",\"proxy_country\":\"us\",\"response_type\":\"markdown\"},"
            + "\"tasks\":["
            + "{\"url\":\"https://www.scrapingcourse.com/ecommerce/product/artemis-running-short\",\"external_id\":\"order-42\",\"zenrows_params\":{\"proxy_country\":\"de\"}},"
            + "{\"url\":\"https://www.scrapingcourse.com/ecommerce/product/atomic-endurance-tee\",\"metadata\":{\"sku\":\"ABC-1\"}}"
            + "]}";
        String response = Request.post("https://async.api.zenrows.com/v1/jobs")
                .addHeader("X-API-Key", "YOUR_ZENROWS_API_KEY")
                .bodyString(body, ContentType.APPLICATION_JSON)
                .execute().returnContent().asString();
        System.out.println(response);
    }
}
```

```php PHP theme={"theme":"css-variables"}
<?php
$payload = json_encode([
    'type' => 'regular',
    'status' => 'closed',
    'zenrows_params' => ['js_render' => 'true', 'proxy_country' => 'us', 'response_type' => 'markdown'],
    'tasks' => [
        ['url' => 'https://www.scrapingcourse.com/ecommerce/product/artemis-running-short',
        'external_id' => 'order-42', 'zenrows_params' => ['proxy_country' => 'de']],
        ['url' => 'https://www.scrapingcourse.com/ecommerce/product/atomic-endurance-tee',
        'metadata' => ['sku' => 'ABC-1']],
    ],
]);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://async.api.zenrows.com/v1/jobs');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['X-API-Key: YOUR_ZENROWS_API_KEY', 'Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
echo curl_exec($ch) . PHP_EOL;
curl_close($ch);
?>
```

```go Go theme={"theme":"css-variables"}
package main

import (
    "bytes"
    "io"
    "log"
    "net/http"
)

func main() {
    payload := []byte(`{
        "type": "regular",
        "status": "closed",
        "zenrows_params": { "js_render": "true", "proxy_country": "us", "response_type": "markdown" },
        "tasks": [
            { "url": "https://www.scrapingcourse.com/ecommerce/product/artemis-running-short", "external_id": "order-42", "zenrows_params": { "proxy_country": "de" } },
            { "url": "https://www.scrapingcourse.com/ecommerce/product/atomic-endurance-tee", "metadata": { "sku": "ABC-1" } }
        ]
    }`)
    req, err := http.NewRequest("POST", "https://async.api.zenrows.com/v1/jobs", bytes.NewBuffer(payload))
    if err != nil {
        log.Fatalln(err)
    }
    req.Header.Set("X-API-Key", "YOUR_ZENROWS_API_KEY")
    req.Header.Set("Content-Type", "application/json")
    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        log.Fatalln(err)
    }
    defer resp.Body.Close()
    body, _ := io.ReadAll(resp.Body)
    log.Println(string(body))
}
```

```ruby Ruby theme={"theme":"css-variables"}
# gem install faraday
require 'faraday'
require 'json'

payload = {
    type: 'regular',
    status: 'closed',
    zenrows_params: { js_render: 'true', proxy_country: 'us', response_type: 'markdown' },
    tasks: [
        { url: 'https://www.scrapingcourse.com/ecommerce/product/artemis-running-short',
          external_id: 'order-42', zenrows_params: { proxy_country: 'de' } },
        { url: 'https://www.scrapingcourse.com/ecommerce/product/atomic-endurance-tee',
          metadata: { sku: 'ABC-1' } }
    ]
}
conn = Faraday.new
res = conn.post('https://async.api.zenrows.com/v1/jobs') do |req|
    req.headers['X-API-Key'] = 'YOUR_ZENROWS_API_KEY'
    req.headers['Content-Type'] = 'application/json'
    req.body = payload.to_json
end
print(res.body)
```

```bash cURL theme={"theme":"css-variables"}
curl -X POST "https://async.api.zenrows.com/v1/jobs" \
  -H "X-API-Key: YOUR_ZENROWS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "regular",
    "status": "closed",
    "zenrows_params": { "js_render": "true", "proxy_country": "us", "response_type": "markdown" },
    "tasks": [
      { "url": "https://www.scrapingcourse.com/ecommerce/product/artemis-running-short", "external_id": "order-42", "zenrows_params": { "proxy_country": "de" } },
      { "url": "https://www.scrapingcourse.com/ecommerce/product/atomic-endurance-tee", "metadata": { "sku": "ABC-1" } }
    ]
  }'
```

> [!TIP]
>
> The API returns your `external_id` unchanged on every result, so you can match results back to your own records without tracking the API's task IDs. It doesn't need to be unique, but it must match `^[A-Za-z0-9._-]+$` and be 128 characters or fewer. Put free text, such as a search keyword, in `metadata` instead: up to 20 string values, keys up to 64 characters from the same set, values up to 1,024 bytes (UTF-8), 4 KiB in total.

### POST target fetches

By default, Batch fetches every target URL with an HTTP GET. To fetch a target with POST instead, set `"method": "POST"` and a `body` on the task object, up to **16 KiB** per task. Use it for read-only requests, such as search or GraphQL queries: a task can be retried, so the target may receive the same POST more than once.

* A JSON object, array, number or boolean `body` is sent as JSON, with `Content-Type: application/json`.
* A string `body` is sent verbatim, with `Content-Type: application/x-www-form-urlencoded`.
* A `Content-Type` in `custom_headers` overrides either.
* A POST task can't use `js_render`, `js_instructions` or `json_response`; the submit is rejected with `400 invalid_argument` and the reason `method_param_conflict`.

```json theme={"theme":"css-variables"}
{
  "type": "regular",
  "status": "closed",
  "tasks": [
    {
      "url": "https://api.example.com/search",
      "method": "POST",
      "body": "{\"query\": \"web scraping\", \"page\": 1}",
      "zenrows_params": { "custom_headers": { "Content-Type": "application/json" } }
    },
    {
      "url": "https://www.example.com/page",
      "external_id": "get-target"
    }
  ]
}
```

> [!NOTE]
>
> You can mix GET and POST targets in the same job. Tasks without a `method` field default to GET. Set `custom_headers` in `zenrows_params` to control the `Content-Type` sent with the POST body.

### Open jobs: adding tasks in batches

> [!NOTE]
>
> Open (queue-mode) jobs let you add tasks in batches after creating the job, instead of supplying all URLs upfront.

Create an open job, add tasks with `POST /jobs/{job_id}/tasks` over time, then close it by sending `last_batch: true` on the final batch. Each add-tasks call accepts up to 10,000 URLs, and an open job holds up to 100,000 in total; past that, add-tasks returns `429 quota_exceeded`, so open a new job. Send an `Idempotency-Key` on each add-tasks call so a retry adds its tasks once (see [Idempotency](#idempotency)).

```python Python theme={"theme":"css-variables"}
## pip install requests
import requests, json

headers = {'X-API-Key': 'YOUR_ZENROWS_API_KEY', 'Content-Type': 'application/json'}

job = requests.post('https://async.api.zenrows.com/v1/jobs', headers=headers,
                    data=json.dumps({'type': 'regular', 'status': 'open',
                                    'zenrows_params': {'js_render': 'true'}})).json()
job_id = job['job_id']

requests.post(f'https://async.api.zenrows.com/v1/jobs/{job_id}/tasks', headers=headers,
              data=json.dumps({'tasks': [{'url': 'https://www.scrapingcourse.com/ecommerce/page/1'}]}))
requests.post(f'https://async.api.zenrows.com/v1/jobs/{job_id}/tasks', headers=headers,
              data=json.dumps({'tasks': [{'url': 'https://www.scrapingcourse.com/ecommerce/page/2'}], 'last_batch': True}))
```

```javascript Node.js theme={"theme":"css-variables"}
const { job_id } = await api("POST", "/jobs", {
  body: { type: "regular", status: "open", zenrows_params: { js_render: "true" } },
});

await api("POST", `/jobs/${job_id}/tasks`, {
  body: { tasks: [{ url: "https://www.scrapingcourse.com/ecommerce/page/1" }] },
});
await api("POST", `/jobs/${job_id}/tasks`, {
  body: { tasks: [{ url: "https://www.scrapingcourse.com/ecommerce/page/2" }], last_batch: true }, // closes the job
});
```

```java Java theme={"theme":"css-variables"}
import org.apache.hc.client5.http.fluent.Request;
import org.apache.hc.core5.http.ContentType;

public class OpenJob {
    public static void main(final String... args) throws Exception {
        String key = "YOUR_ZENROWS_API_KEY";
        String created = Request.post("https://async.api.zenrows.com/v1/jobs")
                .addHeader("X-API-Key", key)
                .bodyString("{\"type\":\"regular\",\"status\":\"open\",\"zenrows_params\":{\"js_render\":\"true\"}}", ContentType.APPLICATION_JSON)
                .execute().returnContent().asString();
        System.out.println(created); // read job_id from this response

        String jobId = "JOB_ID";
        Request.post("https://async.api.zenrows.com/v1/jobs/" + jobId + "/tasks")
                .addHeader("X-API-Key", key)
                .bodyString("{\"tasks\":[{\"url\":\"https://www.scrapingcourse.com/ecommerce/page/1\"}]}", ContentType.APPLICATION_JSON)
                .execute().discardContent();
        Request.post("https://async.api.zenrows.com/v1/jobs/" + jobId + "/tasks")
                .addHeader("X-API-Key", key)
                .bodyString("{\"tasks\":[{\"url\":\"https://www.scrapingcourse.com/ecommerce/page/2\"}],\"last_batch\":true}", ContentType.APPLICATION_JSON)
                .execute().discardContent();
    }
}
```

```php PHP theme={"theme":"css-variables"}
<?php
function post($path, $body) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://async.api.zenrows.com/v1' . $path);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['X-API-Key: YOUR_ZENROWS_API_KEY', 'Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $res = curl_exec($ch);
    curl_close($ch);
    return json_decode($res, true);
}

$job = post('/jobs', ['type' => 'regular', 'status' => 'open', 'zenrows_params' => ['js_render' => 'true']]);
$jobId = $job['job_id'];
post("/jobs/$jobId/tasks", ['tasks' => [['url' => 'https://www.scrapingcourse.com/ecommerce/page/1']]]);
post("/jobs/$jobId/tasks", ['tasks' => [['url' => 'https://www.scrapingcourse.com/ecommerce/page/2']], 'last_batch' => true]);
?>
```

```go Go theme={"theme":"css-variables"}
package main

import (
    "bytes"
    "log"
    "net/http"
)

func post(path string, body string) {
    req, err := http.NewRequest("POST", "https://async.api.zenrows.com/v1"+path, bytes.NewBufferString(body))
    if err != nil {
        log.Fatalln(err)
    }
    req.Header.Set("X-API-Key", "YOUR_ZENROWS_API_KEY")
    req.Header.Set("Content-Type", "application/json")
    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        log.Fatalln(err)
    }
    defer resp.Body.Close()
}

func main() {
    // Create the open job, then read job_id from the response body.
    post("/jobs", `{"type":"regular","status":"open","zenrows_params":{"js_render":"true"}}`)
    jobId := "JOB_ID"
    post("/jobs/"+jobId+"/tasks", `{"tasks":[{"url":"https://www.scrapingcourse.com/ecommerce/page/1"}]}`)
    post("/jobs/"+jobId+"/tasks", `{"tasks":[{"url":"https://www.scrapingcourse.com/ecommerce/page/2"}],"last_batch":true}`)
}
```

```ruby Ruby theme={"theme":"css-variables"}
# gem install faraday
require 'faraday'
require 'json'

conn = Faraday.new
conn.headers['X-API-Key'] = 'YOUR_ZENROWS_API_KEY'
conn.headers['Content-Type'] = 'application/json'

job = JSON.parse(conn.post('https://async.api.zenrows.com/v1/jobs',
    { type: 'regular', status: 'open', zenrows_params: { js_render: 'true' } }.to_json).body)
job_id = job['job_id']

conn.post("https://async.api.zenrows.com/v1/jobs/#{job_id}/tasks",
    { tasks: [{ url: 'https://www.scrapingcourse.com/ecommerce/page/1' }] }.to_json)
conn.post("https://async.api.zenrows.com/v1/jobs/#{job_id}/tasks",
    { tasks: [{ url: 'https://www.scrapingcourse.com/ecommerce/page/2' }], last_batch: true }.to_json)
```

```bash cURL theme={"theme":"css-variables"}
# 1) Create the open job and note its job_id.
curl -X POST "https://async.api.zenrows.com/v1/jobs" \
  -H "X-API-Key: YOUR_ZENROWS_API_KEY" -H "Content-Type: application/json" \
  -d '{ "type": "regular", "status": "open", "zenrows_params": { "js_render": "true" } }'

# 2) Add a batch of tasks.
curl -X POST "https://async.api.zenrows.com/v1/jobs/JOB_ID/tasks" \
  -H "X-API-Key: YOUR_ZENROWS_API_KEY" -H "Content-Type: application/json" \
  -d '{ "tasks": [{ "url": "https://www.scrapingcourse.com/ecommerce/page/1" }] }'

# 3) Add the final batch and close the job.
curl -X POST "https://async.api.zenrows.com/v1/jobs/JOB_ID/tasks" \
  -H "X-API-Key: YOUR_ZENROWS_API_KEY" -H "Content-Type: application/json" \
  -d '{ "tasks": [{ "url": "https://www.scrapingcourse.com/ecommerce/page/2" }], "last_batch": true }'
```

`last_batch: true` (or `POST /jobs/{id}/close`) locks the job, and later adds return `409 last_batch_received` or `409 job_not_open`. An add-tasks call that races a close also answers `409 job_not_open`, and none of its tasks are added. An open job counts as one of your account's active jobs, even after you stop its run. A job holds a slot until you delete it, or until it's closed and its latest run has ended (`completed`, `stopped` or `failed`); deleting frees it at once. One that receives no tasks for 48 hours closes automatically. To abandon a run that is still in flight, call `POST /jobs/{id}/stop` (see [Control the current run](#control-the-current-run)). A very large submission also keeps ingesting task rows for a few seconds after it responds; `POST /jobs/{id}/tasks` can return `409 run_not_terminal` during that window, so retry shortly.

### Large inputs: CSV upload

For lists too large to inline, upload a CSV in three steps:

1. Create an input slot with `POST /job_inputs`.
2. PUT the file to the returned presigned URL using the exact headers it specifies
3. Submit a job referencing `file_input_id`.

The `fields` map points the canonical `url` (required) and `external_id` (optional) fields at your CSV columns by header name (with `header: true`) or 0-based index.

> [!NOTE]
>
> Limits: 50 MB and 100,000 rows. The presigned upload link works for 30 minutes, and the uploaded file for 24 hours; after that, a submit returns `404 file_input_not_found`. A CSV can feed a closed regular job or a scheduled job, not an open job (`409 file_input_unsupported_for_job_type`). Values mapped to `external_id` must match `[A-Za-z0-9._-]`, up to 128 characters.

```python Python theme={"theme":"css-variables"}
## pip install requests
import requests, json

headers = {'X-API-Key': 'YOUR_ZENROWS_API_KEY'}

# 1) Create the slot.
slot = requests.post('https://async.api.zenrows.com/v1/job_inputs',
                    headers={**headers, 'Content-Type': 'application/json'},
                    data=json.dumps({'type': 'csv',
                                      'csv': {'header': True, 'fields': {'url': 'URL', 'external_id': 'Customer Ref'}}})).json()

# 2) Upload the file with the exact content-type the slot requires.
with open('urls.csv', 'rb') as f:
    requests.put(slot['upload']['url'], headers=slot['upload']['headers'], data=f)

# 3) Submit referencing the slot.
job = requests.post('https://async.api.zenrows.com/v1/jobs',
                    headers={**headers, 'Content-Type': 'application/json'},
                    data=json.dumps({'type': 'regular', 'status': 'closed',
                                    'file_input_id': slot['file_input_id'], 'zenrows_params': {'js_render': 'true'}})).json()
print(job['job_id'])
```

```javascript Node.js theme={"theme":"css-variables"}
import { readFile } from "node:fs/promises";

// 1) Create the slot.
const slot = await api("POST", "/job_inputs", {
  body: { type: "csv", csv: { header: true, fields: { url: "URL", external_id: "Customer Ref" } } },
});

// 2) Upload the body with the EXACT content-type the slot requires.
const csvBytes = await readFile("urls.csv");
const put = await fetch(slot.upload.url, {
  method: slot.upload.method, // "PUT"
  headers: slot.upload.headers, // e.g. { "Content-Type": "text/csv" }
  body: csvBytes,
});
if (!put.ok) throw new Error(`upload failed: ${put.status}`);

// 3) Submit referencing the slot instead of inline tasks.
const job = await api("POST", "/jobs", {
  body: { type: "regular", status: "closed", file_input_id: slot.file_input_id, zenrows_params: { js_render: "true" } },
});
console.log(job.job_id);
```

```java Java theme={"theme":"css-variables"}
import org.apache.hc.client5.http.fluent.Request;
import org.apache.hc.core5.http.ContentType;
import java.io.File;

public class CsvUpload {
    public static void main(final String... args) throws Exception {
        String key = "YOUR_ZENROWS_API_KEY";

        // 1) Create the slot, then read upload.url, upload.headers, and file_input_id from the response.
        String slot = Request.post("https://async.api.zenrows.com/v1/job_inputs")
                .addHeader("X-API-Key", key)
                .bodyString("{\"type\":\"csv\",\"csv\":{\"header\":true,\"fields\":{\"url\":\"URL\",\"external_id\":\"Customer Ref\"}}}", ContentType.APPLICATION_JSON)
                .execute().returnContent().asString();
        System.out.println(slot);

        // 2) PUT the file to the presigned URL with the content-type the slot requires.
        Request.put("PRESIGNED_UPLOAD_URL")
                .bodyFile(new File("urls.csv"), ContentType.create("text/csv"))
                .execute().discardContent();

        // 3) Submit referencing the slot.
        String job = Request.post("https://async.api.zenrows.com/v1/jobs")
                .addHeader("X-API-Key", key)
                .bodyString("{\"type\":\"regular\",\"status\":\"closed\",\"file_input_id\":\"FILE_INPUT_ID\",\"zenrows_params\":{\"js_render\":\"true\"}}", ContentType.APPLICATION_JSON)
                .execute().returnContent().asString();
        System.out.println(job);
    }
}
```

```php PHP theme={"theme":"css-variables"}
<?php
$key = 'YOUR_ZENROWS_API_KEY';

// 1) Create the slot.
$ch = curl_init('https://async.api.zenrows.com/v1/job_inputs');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
    'type' => 'csv',
    'csv' => ['header' => true, 'fields' => ['url' => 'URL', 'external_id' => 'Customer Ref']],
]));
curl_setopt($ch, CURLOPT_HTTPHEADER, ["X-API-Key: $key", 'Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$slot = json_decode(curl_exec($ch), true);
curl_close($ch);

// 2) Upload the file with the exact content-type the slot requires.
$ch = curl_init($slot['upload']['url']);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents('urls.csv'));
curl_setopt($ch, CURLOPT_HTTPHEADER, $slot['upload']['headers']);
curl_exec($ch);
curl_close($ch);

// 3) Submit referencing the slot.
$ch = curl_init('https://async.api.zenrows.com/v1/jobs');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
    'type' => 'regular', 'status' => 'closed',
    'file_input_id' => $slot['file_input_id'], 'zenrows_params' => ['js_render' => 'true'],
]));
curl_setopt($ch, CURLOPT_HTTPHEADER, ["X-API-Key: $key", 'Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
echo curl_exec($ch) . PHP_EOL;
curl_close($ch);
?>
```

```go Go theme={"theme":"css-variables"}
package main

import (
    "bytes"
    "io"
    "log"
    "net/http"
    "os"
)

func main() {
    key := "YOUR_ZENROWS_API_KEY"

    // 1) Create the slot, then read upload.url, upload.headers, and file_input_id from the response.
    slotReq, _ := http.NewRequest("POST", "https://async.api.zenrows.com/v1/job_inputs",
        bytes.NewBufferString(`{"type":"csv","csv":{"header":true,"fields":{"url":"URL","external_id":"Customer Ref"}}}`))
    slotReq.Header.Set("X-API-Key", key)
    slotReq.Header.Set("Content-Type", "application/json")
    slotResp, err := http.DefaultClient.Do(slotReq)
    if err != nil {
        log.Fatalln(err)
    }
    defer slotResp.Body.Close()
    slotBody, _ := io.ReadAll(slotResp.Body)
    log.Println(string(slotBody))

    // 2) PUT the file to the presigned URL with the content-type the slot requires.
    file, _ := os.Open("urls.csv")
    defer file.Close()
    putReq, _ := http.NewRequest("PUT", "PRESIGNED_UPLOAD_URL", file)
    putReq.Header.Set("Content-Type", "text/csv")
    if _, err := http.DefaultClient.Do(putReq); err != nil {
        log.Fatalln(err)
    }

    // 3) Submit referencing the slot.
    jobReq, _ := http.NewRequest("POST", "https://async.api.zenrows.com/v1/jobs",
        bytes.NewBufferString(`{"type":"regular","status":"closed","file_input_id":"FILE_INPUT_ID","zenrows_params":{"js_render":"true"}}`))
    jobReq.Header.Set("X-API-Key", key)
    jobReq.Header.Set("Content-Type", "application/json")
    jobResp, err := http.DefaultClient.Do(jobReq)
    if err != nil {
        log.Fatalln(err)
    }
    defer jobResp.Body.Close()
    jobBody, _ := io.ReadAll(jobResp.Body)
    log.Println(string(jobBody))
}
```

```ruby Ruby theme={"theme":"css-variables"}
# gem install faraday
require 'faraday'
require 'json'

key = 'YOUR_ZENROWS_API_KEY'
conn = Faraday.new

# 1) Create the slot.
slot = JSON.parse(conn.post('https://async.api.zenrows.com/v1/job_inputs',
    { type: 'csv', csv: { header: true, fields: { url: 'URL', external_id: 'Customer Ref' } } }.to_json,
    { 'X-API-Key' => key, 'Content-Type' => 'application/json' }).body)

# 2) Upload the file with the exact headers the slot requires.
conn.put(slot['upload']['url'], File.read('urls.csv'), slot['upload']['headers'])

# 3) Submit referencing the slot.
job = JSON.parse(conn.post('https://async.api.zenrows.com/v1/jobs',
    { type: 'regular', status: 'closed', file_input_id: slot['file_input_id'], zenrows_params: { js_render: 'true' } }.to_json,
    { 'X-API-Key' => key, 'Content-Type' => 'application/json' }).body)
puts job['job_id']
```

```bash cURL theme={"theme":"css-variables"}
# 1) Create the slot. Read upload.url, upload.headers, and file_input_id from the response.
curl -X POST "https://async.api.zenrows.com/v1/job_inputs" \
  -H "X-API-Key: YOUR_ZENROWS_API_KEY" -H "Content-Type: application/json" \
  -d '{ "type": "csv", "csv": { "header": true, "fields": { "url": "URL", "external_id": "Customer Ref" } } }'

# 2) Upload the file to the presigned URL with the content-type it requires.
curl -X PUT "PRESIGNED_UPLOAD_URL" -H "Content-Type: text/csv" --data-binary @urls.csv

# 3) Submit referencing the slot.
curl -X POST "https://async.api.zenrows.com/v1/jobs" \
  -H "X-API-Key: YOUR_ZENROWS_API_KEY" -H "Content-Type: application/json" \
  -d '{ "type": "regular", "status": "closed", "file_input_id": "FILE_INPUT_ID", "zenrows_params": { "js_render": "true" } }'
```

### Scheduled jobs

A scheduled job stores its URLs as a template, and each fire creates a new run. Provide exactly one of `at`, `rate`, or `calendar` (plus a `timezone` for `at` and `calendar`). Times of day must be full hours, and the minimum interval between runs is 60 minutes. An account holds up to 5 scheduled jobs (`429 quota_exceeded` past that). A fire is skipped while the job's previous run is still `pending` or `running`. The request below schedules a job to run every 6 hours.

```python Python theme={"theme":"css-variables"}
## pip install requests
import requests, json

headers = {'X-API-Key': 'YOUR_ZENROWS_API_KEY', 'Content-Type': 'application/json'}
payload = {
    'type': 'scheduled', 'status': 'closed',
    'schedule': {'rate': {'every': 6, 'unit': 'hour'}},
    'tasks': [{'url': 'https://www.scrapingcourse.com/ecommerce/'}],
}
response = requests.post('https://async.api.zenrows.com/v1/jobs', headers=headers, data=json.dumps(payload))
print(response.json())
```

```javascript Node.js theme={"theme":"css-variables"}
const job = await api("POST", "/jobs", {
  body: {
    type: "scheduled", status: "closed",
    schedule: { rate: { every: 6, unit: "hour" } },
    tasks: [{ url: "https://www.scrapingcourse.com/ecommerce/" }],
  },
});
console.log(job.job_id);
```

```java Java theme={"theme":"css-variables"}
import org.apache.hc.client5.http.fluent.Request;
import org.apache.hc.core5.http.ContentType;

public class ScheduledJob {
    public static void main(final String... args) throws Exception {
        String body = "{\"type\":\"scheduled\",\"status\":\"closed\","
            + "\"schedule\":{\"rate\":{\"every\":6,\"unit\":\"hour\"}},"
            + "\"tasks\":[{\"url\":\"https://www.scrapingcourse.com/ecommerce/\"}]}";
        String response = Request.post("https://async.api.zenrows.com/v1/jobs")
                .addHeader("X-API-Key", "YOUR_ZENROWS_API_KEY")
                .bodyString(body, ContentType.APPLICATION_JSON)
                .execute().returnContent().asString();
        System.out.println(response);
    }
}
```

```php PHP theme={"theme":"css-variables"}
<?php
$payload = json_encode([
    'type' => 'scheduled', 'status' => 'closed',
    'schedule' => ['rate' => ['every' => 6, 'unit' => 'hour']],
    'tasks' => [['url' => 'https://www.scrapingcourse.com/ecommerce/']],
]);
$ch = curl_init('https://async.api.zenrows.com/v1/jobs');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['X-API-Key: YOUR_ZENROWS_API_KEY', 'Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
echo curl_exec($ch) . PHP_EOL;
curl_close($ch);
?>
```

```go Go theme={"theme":"css-variables"}
package main

import (
    "bytes"
    "io"
    "log"
    "net/http"
)

func main() {
    payload := []byte(`{
        "type": "scheduled", "status": "closed",
        "schedule": { "rate": { "every": 6, "unit": "hour" } },
        "tasks": [{ "url": "https://www.scrapingcourse.com/ecommerce/" }]
    }`)
    req, err := http.NewRequest("POST", "https://async.api.zenrows.com/v1/jobs", bytes.NewBuffer(payload))
    if err != nil {
        log.Fatalln(err)
    }
    req.Header.Set("X-API-Key", "YOUR_ZENROWS_API_KEY")
    req.Header.Set("Content-Type", "application/json")
    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        log.Fatalln(err)
    }
    defer resp.Body.Close()
    body, _ := io.ReadAll(resp.Body)
    log.Println(string(body))
}
```

```ruby Ruby theme={"theme":"css-variables"}
# gem install faraday
require 'faraday'
require 'json'

payload = {
    type: 'scheduled', status: 'closed',
    schedule: { rate: { every: 6, unit: 'hour' } },
    tasks: [{ url: 'https://www.scrapingcourse.com/ecommerce/' }]
}
conn = Faraday.new
res = conn.post('https://async.api.zenrows.com/v1/jobs') do |req|
    req.headers['X-API-Key'] = 'YOUR_ZENROWS_API_KEY'
    req.headers['Content-Type'] = 'application/json'
    req.body = payload.to_json
end
print(res.body)
```

```bash cURL theme={"theme":"css-variables"}
curl -X POST "https://async.api.zenrows.com/v1/jobs" \
  -H "X-API-Key: YOUR_ZENROWS_API_KEY" -H "Content-Type: application/json" \
  -d '{
    "type": "scheduled", "status": "closed",
    "schedule": { "rate": { "every": 6, "unit": "hour" } },
    "tasks": [{ "url": "https://www.scrapingcourse.com/ecommerce/" }]
  }'
```

For a calendar schedule, replace the `schedule` object. The example below runs at 09:00 and 18:00 on Mon/Wed/Fri in Berlin time. Use an `at` object instead for a one-shot run at a single wall-clock time.

```json theme={"theme":"css-variables"}
{
  "schedule": {
    "calendar": {
      "times_of_day": ["09:00", "18:00"],
      "cadence": { "weekly": { "days": ["mon", "wed", "fri"] } }
    },
    "timezone": "Europe/Berlin"
  }
}
```

Manage a schedule with `PUT /jobs/{id}/schedule` to replace it, and `POST /jobs/{id}/schedule/state` with `{"schedule_state": "paused"}` or `{"schedule_state": "active"}` to pause or resume.

## 2. Track your jobs

Check progress and find your jobs once they are running.

### Check job status

Read a job with `GET /jobs/{job_id}`. Progress lives in `latest_run.stats`, where `completed` equals `successful` plus `failed`.

```python Python theme={"theme":"css-variables"}
## pip install requests
import requests

response = requests.get('https://async.api.zenrows.com/v1/jobs/JOB_ID',
                        headers={'X-API-Key': 'YOUR_ZENROWS_API_KEY'})
job = response.json()
print(job['latest_run']['status'], job['latest_run']['stats'])
```

```javascript Node.js theme={"theme":"css-variables"}
const job = await api("GET", "/jobs/JOB_ID");
console.log(job.latest_run.status, job.latest_run.stats);
```

```java Java theme={"theme":"css-variables"}
import org.apache.hc.client5.http.fluent.Request;

public class GetJob {
    public static void main(final String... args) throws Exception {
        String response = Request.get("https://async.api.zenrows.com/v1/jobs/JOB_ID")
                .addHeader("X-API-Key", "YOUR_ZENROWS_API_KEY")
                .execute().returnContent().asString();
        System.out.println(response);
    }
}
```

```php PHP theme={"theme":"css-variables"}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://async.api.zenrows.com/v1/jobs/JOB_ID');
curl_setopt($ch, CURLOPT_HTTPHEADER, ['X-API-Key: YOUR_ZENROWS_API_KEY']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
echo curl_exec($ch) . PHP_EOL;
curl_close($ch);
?>
```

```go Go theme={"theme":"css-variables"}
package main

import (
    "io"
    "log"
    "net/http"
)

func main() {
    req, err := http.NewRequest("GET", "https://async.api.zenrows.com/v1/jobs/JOB_ID", nil)
    if err != nil {
        log.Fatalln(err)
    }
    req.Header.Set("X-API-Key", "YOUR_ZENROWS_API_KEY")
    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        log.Fatalln(err)
    }
    defer resp.Body.Close()
    body, _ := io.ReadAll(resp.Body)
    log.Println(string(body))
}
```

```ruby Ruby theme={"theme":"css-variables"}
# gem install faraday
require 'faraday'

conn = Faraday.new
res = conn.get('https://async.api.zenrows.com/v1/jobs/JOB_ID') do |req|
    req.headers['X-API-Key'] = 'YOUR_ZENROWS_API_KEY'
end
print(res.body)
```

```bash cURL theme={"theme":"css-variables"}
curl "https://async.api.zenrows.com/v1/jobs/JOB_ID" \
  -H "X-API-Key: YOUR_ZENROWS_API_KEY"
```

To wait for a run to finish, poll this endpoint until `latest_run.status` reaches a **terminal** state (`completed`, `failed`, or `stopped`), backing off between calls rather than running a tight loop. A run with `latest_run.pause_state: "paused"` makes no progress until you resume it, so stop polling and report it instead of waiting.

```python Python theme={"theme":"css-variables"}
## pip install requests
import time, requests

def wait_for_job(job_id, timeout=600):
    terminal = {'completed', 'failed', 'stopped', 'deleted'}
    headers = {'X-API-Key': 'YOUR_ZENROWS_API_KEY'}
    deadline = time.time() + timeout
    delay = 2.0
    while True:
        job = requests.get(f'https://async.api.zenrows.com/v1/jobs/{job_id}', headers=headers).json()
        run = job.get('latest_run')
        if run and run['status'] in terminal:
            return job
        if time.time() > deadline:
            raise TimeoutError('timeout waiting for job')
        time.sleep(delay)
        delay = min(delay * 1.5, 15.0)  # back off gradually, capped at 15s

job = wait_for_job('JOB_ID')
s = job['latest_run']['stats']  # { total, completed, successful, failed }
print(job['latest_run']['status'], f"{s['successful']}/{s['total']} successful")
```

```javascript Node.js theme={"theme":"css-variables"}
async function waitForJob(jobId, { timeoutMs = 600_000 } = {}) {
  const TERMINAL = new Set(["completed", "failed", "stopped", "deleted"]);
  const deadline = Date.now() + timeoutMs;
  let delay = 2000;
  for (;;) {
    const job = await api("GET", `/jobs/${jobId}`);
    const run = job.latest_run;
    if (run && TERMINAL.has(run.status)) return job;
    if (Date.now() > deadline) throw new Error("timeout waiting for job");
    await new Promise((r) => setTimeout(r, delay));
    delay = Math.min(delay * 1.5, 15_000); // back off gradually, capped at 15s
  }
}

const job = await waitForJob("JOB_ID");
const s = job.latest_run.stats; // { total, completed, successful, failed }
console.log(`${job.latest_run.status}: ${s.successful}/${s.total} successful`);
```

```java Java theme={"theme":"css-variables"}
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.hc.client5.http.fluent.Request;
import java.util.Set;

public class WaitForJob {
    static final ObjectMapper M = new ObjectMapper();

    public static void main(final String... args) throws Exception {
        Set<String> terminal = Set.of("completed", "failed", "stopped", "deleted");
        long deadline = System.currentTimeMillis() + 600_000;
        long delay = 2000;
        while (true) {
            String body = Request.get("https://async.api.zenrows.com/v1/jobs/JOB_ID")
                    .addHeader("X-API-Key", "YOUR_ZENROWS_API_KEY")
                    .execute().returnContent().asString();
            JsonNode run = M.readTree(body).path("latest_run");
            if (terminal.contains(run.path("status").asText())) {
                System.out.println(run.path("stats"));
                break;
            }
            if (System.currentTimeMillis() > deadline) throw new RuntimeException("timeout waiting for job");
            Thread.sleep(delay);
            delay = Math.min((long) (delay * 1.5), 15_000); // back off gradually, capped at 15s
        }
    }
}
```

```php PHP theme={"theme":"css-variables"}
<?php
function get_job($id) {
    $ch = curl_init("https://async.api.zenrows.com/v1/jobs/$id");
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['X-API-Key: YOUR_ZENROWS_API_KEY']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $res = curl_exec($ch);
    curl_close($ch);
    return json_decode($res, true);
}

$terminal = ['completed', 'failed', 'stopped', 'deleted'];
$deadline = time() + 600;
$delay = 2.0;
while (true) {
    $job = get_job('JOB_ID');
    $run = $job['latest_run'] ?? null;
    if ($run && in_array($run['status'], $terminal, true)) { print_r($run['stats']); break; }
    if (time() > $deadline) throw new RuntimeException('timeout waiting for job');
    usleep((int)($delay * 1000000));
    $delay = min($delay * 1.5, 15.0); // back off gradually, capped at 15s
}
?>
```

```go Go theme={"theme":"css-variables"}
package main

import (
    "encoding/json"
    "io"
    "log"
    "net/http"
    "time"
)

func getJob(id string) map[string]any {
    req, _ := http.NewRequest("GET", "https://async.api.zenrows.com/v1/jobs/"+id, nil)
    req.Header.Set("X-API-Key", "YOUR_ZENROWS_API_KEY")
    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        log.Fatalln(err)
    }
    defer resp.Body.Close()
    body, _ := io.ReadAll(resp.Body)
    var job map[string]any
    json.Unmarshal(body, &job)
    return job
}

func main() {
    terminal := map[string]bool{"completed": true, "failed": true, "stopped": true, "deleted": true}
    deadline := time.Now().Add(10 * time.Minute)
    delay := 2 * time.Second
    for {
        job := getJob("JOB_ID")
        run, _ := job["latest_run"].(map[string]any)
        status, _ := run["status"].(string)
        if run != nil && terminal[status] {
            log.Println(run["stats"])
            break
        }
        if time.Now().After(deadline) {
            log.Fatalln("timeout waiting for job")
        }
        time.Sleep(delay)
        if delay < 15*time.Second {
            delay = time.Duration(float64(delay) * 1.5)
        }
    }
}
```

```ruby Ruby theme={"theme":"css-variables"}
# gem install faraday
require 'faraday'
require 'json'

def get_job(id)
    res = Faraday.get("https://async.api.zenrows.com/v1/jobs/#{id}") do |req|
        req.headers['X-API-Key'] = 'YOUR_ZENROWS_API_KEY'
    end
    JSON.parse(res.body)
end

terminal = ['completed', 'failed', 'stopped', 'deleted']
deadline = Time.now + 600
delay = 2.0
loop do
    job = get_job('JOB_ID')
    run = job['latest_run']
    if run && terminal.include?(run['status'])
        p run['stats']
        break
    end
    raise 'timeout waiting for job' if Time.now > deadline
    sleep(delay)
    delay = [delay * 1.5, 15.0].min  # back off gradually, capped at 15s
end
```

```bash cURL theme={"theme":"css-variables"}
# cURL has no loop of its own; poll with a small shell loop until the run is terminal.
delay=2
while :; do
  status=$(curl -s "https://async.api.zenrows.com/v1/jobs/JOB_ID" \
    -H "X-API-Key: YOUR_ZENROWS_API_KEY" | jq -r '.latest_run.status')
  echo "status: $status"
  case "$status" in completed|failed|stopped|deleted) break ;; esac
  sleep "$delay"
  delay=$(( delay < 15 ? delay + delay/2 + 1 : 15 ))  # back off, capped at 15s
done
```

### Why a run failed

When a run ends with status `failed` for a reason that affects the whole run, the run carries two extra fields:

* `failure_reason`: a stable code you can branch on.
* `failure_detail`: a human-readable explanation, such as which credit cap was reached and when it resets.

| `failure_reason` | Meaning |
| - | - |
| `insufficient_credits` | Your account has no credits available. |
| `subscription_inactive` | Your subscription isn't active. |
| `api_key_cap_reached` | The API key reached one of its [credit caps](https://docs.zenrows.com/first-steps/api-key-credit-caps.md). See [API key credit caps and Batch](#api-key-credit-caps-and-batch). |

> [!WARNING]
>
> `failure_reason` is an open list. New values can be added at any time, so your code must accept values not listed here, for example by falling back to showing `failure_detail`.

### API key credit caps and Batch

A Batch job uses the [credit caps](https://docs.zenrows.com/first-steps/api-key-credit-caps.md) of the API key it runs with. A capped key affects Batch in three ways:

* **Refused requests.** Starting a job, adding tasks, resuming, or rerunning with a key that's at one of its caps returns `402` with the problem `code` `api_key_cap_reached`. The `detail` names the cap and when it resets.
* **A run in progress stops.** If the key reaches a cap during a run, the run stops with status `failed` and `failure_reason` `api_key_cap_reached`, and `failure_detail` says which cap and when it resets. Tasks already in progress finish. The remaining tasks stay `pending`: they aren't processed and aren't charged. Because a run processes many tasks in parallel, it can go further over a cap than single requests do before it stops, so leave room in caps for keys you use with Batch.
* **Scheduled runs are checked when they start.** If the key is capped, the account has no credits, or the subscription is inactive, the run is recorded as `failed` right away with the matching `failure_reason` and a `failure_detail`. Nothing is scraped.

To recover:

1. Raise or remove the cap in the dashboard (**Settings**, **API keys**, the key's menu, **Credit caps**), or wait for the cap window to reset.
2. Rerun only the tasks that didn't complete with `POST /jobs/{job_id}/rerun?status=failed,pending` (see [Reruns and retrying failures](#5-reruns-and-retrying-failures)).

   A scheduled run refused at start has no tasks, so there is nothing to filter. Rerun the whole job with `POST /jobs/{job_id}/rerun`, or let the next scheduled run pick it up.

### List and paginate jobs

List your jobs with `GET /jobs`, optionally filtered by `status` (`open` or `closed`) and `type` (`regular` or `scheduled`), and page with `cursor` until the response has no `next_cursor`. `limit` defaults to 50, up to 100.

```python Python theme={"theme":"css-variables"}
## pip install requests
import requests

response = requests.get('https://async.api.zenrows.com/v1/jobs',
                        headers={'X-API-Key': 'YOUR_ZENROWS_API_KEY'},
                        params={'status': 'closed', 'type': 'regular'})
print(response.json())
```

```javascript Node.js theme={"theme":"css-variables"}
const page = await api("GET", "/jobs", { query: { status: "closed", type: "regular" } });
console.log(page.jobs);
```

```java Java theme={"theme":"css-variables"}
import org.apache.hc.client5.http.fluent.Request;

public class ListJobs {
    public static void main(final String... args) throws Exception {
        String response = Request.get("https://async.api.zenrows.com/v1/jobs?status=closed&type=regular")
                .addHeader("X-API-Key", "YOUR_ZENROWS_API_KEY")
                .execute().returnContent().asString();
        System.out.println(response);
    }
}
```

```php PHP theme={"theme":"css-variables"}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://async.api.zenrows.com/v1/jobs?status=closed&type=regular');
curl_setopt($ch, CURLOPT_HTTPHEADER, ['X-API-Key: YOUR_ZENROWS_API_KEY']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
echo curl_exec($ch) . PHP_EOL;
curl_close($ch);
?>
```

```go Go theme={"theme":"css-variables"}
package main

import (
    "io"
    "log"
    "net/http"
)

func main() {
    req, err := http.NewRequest("GET", "https://async.api.zenrows.com/v1/jobs?status=closed&type=regular", nil)
    if err != nil {
        log.Fatalln(err)
    }
    req.Header.Set("X-API-Key", "YOUR_ZENROWS_API_KEY")
    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        log.Fatalln(err)
    }
    defer resp.Body.Close()
    body, _ := io.ReadAll(resp.Body)
    log.Println(string(body))
}
```

```ruby Ruby theme={"theme":"css-variables"}
# gem install faraday
require 'faraday'

conn = Faraday.new
res = conn.get('https://async.api.zenrows.com/v1/jobs') do |req|
    req.headers['X-API-Key'] = 'YOUR_ZENROWS_API_KEY'
    req.params['status'] = 'closed'
    req.params['type'] = 'regular'
end
print(res.body)
```

```bash cURL theme={"theme":"css-variables"}
curl "https://async.api.zenrows.com/v1/jobs?status=closed&type=regular" \
  -H "X-API-Key: YOUR_ZENROWS_API_KEY"
```

The cursor loop is the same as for results, and `GET /jobs/{id}/runs` pages identically.

```python Python theme={"theme":"css-variables"}
## pip install requests
import requests

headers = {'X-API-Key': 'YOUR_ZENROWS_API_KEY'}
cursor = None
while True:
    page = requests.get('https://async.api.zenrows.com/v1/jobs', headers=headers,
                        params={'status': 'closed', 'type': 'regular', 'cursor': cursor}).json()
    for job in page['jobs']:
        latest = job.get('latest_run')
        print(job['job_id'], job['status'], latest['stats']['total'] if latest else 0)
    cursor = page.get('next_cursor')  # absent on the last page
    if not cursor:
        break
```

```javascript Node.js theme={"theme":"css-variables"}
async function* iterJobs({ status, type } = {}) {
  let cursor;
  do {
    const page = await api("GET", "/jobs", { query: { status, type, cursor } });
    yield* page.jobs;
    cursor = page.next_cursor;
  } while (cursor);
}

for await (const job of iterJobs({ status: "closed", type: "regular" })) {
  console.log(job.job_id, job.status, job.latest_run?.stats.total ?? 0);
}
```

```java Java theme={"theme":"css-variables"}
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.hc.client5.http.fluent.Request;

public class ListJobsPaged {
    static final ObjectMapper M = new ObjectMapper();

    public static void main(final String... args) throws Exception {
        String key = "YOUR_ZENROWS_API_KEY";
        String cursor = null;
        do {
            String url = "https://async.api.zenrows.com/v1/jobs?status=closed&type=regular"
                    + (cursor != null ? "&cursor=" + cursor : "");
            JsonNode page = M.readTree(Request.get(url).addHeader("X-API-Key", key)
                    .execute().returnContent().asString());
            for (JsonNode job : page.path("jobs")) {
                long total = job.path("latest_run").path("stats").path("total").asLong(0);
                System.out.println(job.path("job_id").asText() + " " + job.path("status").asText() + " " + total);
            }
            cursor = page.path("next_cursor").asText(null);
        } while (cursor != null && !cursor.isEmpty());
    }
}
```

```php PHP theme={"theme":"css-variables"}
<?php
$key = 'YOUR_ZENROWS_API_KEY';
$cursor = null;
do {
    $url = 'https://async.api.zenrows.com/v1/jobs?status=closed&type=regular'
        . ($cursor ? '&cursor=' . urlencode($cursor) : '');
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ["X-API-Key: $key"]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $page = json_decode(curl_exec($ch), true);
    curl_close($ch);
    foreach ($page['jobs'] as $job) {
        $total = $job['latest_run']['stats']['total'] ?? 0;
        echo "{$job['job_id']} {$job['status']} $total" . PHP_EOL;
    }
    $cursor = $page['next_cursor'] ?? null;
} while ($cursor);
?>
```

```go Go theme={"theme":"css-variables"}
package main

import (
    "encoding/json"
    "io"
    "log"
    "net/http"
)

func main() {
    key := "YOUR_ZENROWS_API_KEY"
    cursor := ""
    for {
        url := "https://async.api.zenrows.com/v1/jobs?status=closed&type=regular"
        if cursor != "" {
            url += "&cursor=" + cursor
        }
        req, _ := http.NewRequest("GET", url, nil)
        req.Header.Set("X-API-Key", key)
        resp, err := http.DefaultClient.Do(req)
        if err != nil {
            log.Fatalln(err)
        }
        body, _ := io.ReadAll(resp.Body)
        resp.Body.Close()
        var page struct {
            Jobs []struct {
                JobID     string `json:"job_id"`
                Status    string `json:"status"`
                LatestRun *struct {
                    Stats struct {
                        Total int `json:"total"`
                    } `json:"stats"`
                } `json:"latest_run"`
            } `json:"jobs"`
            NextCursor string `json:"next_cursor"`
        }
        json.Unmarshal(body, &page)
        for _, job := range page.Jobs {
            total := 0
            if job.LatestRun != nil {
                total = job.LatestRun.Stats.Total
            }
            log.Println(job.JobID, job.Status, total)
        }
        cursor = page.NextCursor
        if cursor == "" {
            break
        }
    }
}
```

```ruby Ruby theme={"theme":"css-variables"}
# gem install faraday
require 'faraday'
require 'json'

key = 'YOUR_ZENROWS_API_KEY'
cursor = nil
loop do
    res = Faraday.get('https://async.api.zenrows.com/v1/jobs') do |req|
        req.headers['X-API-Key'] = key
        req.params['status'] = 'closed'
        req.params['type'] = 'regular'
        req.params['cursor'] = cursor if cursor
    end
    page = JSON.parse(res.body)
    page['jobs'].each do |job|
        total = job.dig('latest_run', 'stats', 'total') || 0
        puts "#{job['job_id']} #{job['status']} #{total}"
    end
    cursor = page['next_cursor']
    break unless cursor
end
```

```bash cURL theme={"theme":"css-variables"}
cursor=""
while :; do
  page=$(curl -s "https://async.api.zenrows.com/v1/jobs?status=closed&type=regular&cursor=$cursor" \
    -H "X-API-Key: YOUR_ZENROWS_API_KEY")
  echo "$page" | jq -r '.jobs[] | [.job_id, .status, (.latest_run.stats.total // 0)] | @tsv'
  cursor=$(echo "$page" | jq -r '.next_cursor // empty')
  [ -z "$cursor" ] && break
done
```

### Control the current run

Stop, pause, or resume a job's **latest run**. Each endpoint is a `POST` with no request body and returns the refreshed run object on `200`.

| Endpoint | Purpose |
| - | - |
| `POST /jobs/{id}/stop` | Stop the current run (terminal). |
| `POST /jobs/{id}/cancel` | Alias for `/stop`, identical behavior. |
| `POST /jobs/{id}/pause` | Reversibly suspend the current run. |
| `POST /jobs/{id}/resume` | Resume a paused run. |

```python Python theme={"theme":"css-variables"}
## pip install requests
import requests
headers = {'X-API-Key': 'YOUR_ZENROWS_API_KEY'}

# Stop (terminal). /cancel is an identical alias.
requests.post('https://async.api.zenrows.com/v1/jobs/JOB_ID/stop', headers=headers)

# Pause the current run, then resume it later.
requests.post('https://async.api.zenrows.com/v1/jobs/JOB_ID/pause', headers=headers)
requests.post('https://async.api.zenrows.com/v1/jobs/JOB_ID/resume', headers=headers)
```

```javascript Node.js theme={"theme":"css-variables"}
// Stop (terminal). /cancel is an identical alias.
await api("POST", "/jobs/JOB_ID/stop");

// Pause the current run, then resume it later.
await api("POST", "/jobs/JOB_ID/pause");
await api("POST", "/jobs/JOB_ID/resume");
```

```java Java theme={"theme":"css-variables"}
import org.apache.hc.client5.http.fluent.Request;

public class ControlRun {
    public static void main(final String... args) throws Exception {
        String key = "YOUR_ZENROWS_API_KEY";
        String base = "https://async.api.zenrows.com/v1/jobs/JOB_ID";
        // Stop (terminal); /cancel is an identical alias.
        Request.post(base + "/stop").addHeader("X-API-Key", key).execute().discardContent();
        // Pause and resume the current run.
        Request.post(base + "/pause").addHeader("X-API-Key", key).execute().discardContent();
        Request.post(base + "/resume").addHeader("X-API-Key", key).execute().discardContent();
    }
}
```

```php PHP theme={"theme":"css-variables"}
<?php
function control($action) {
    $ch = curl_init("https://async.api.zenrows.com/v1/jobs/JOB_ID/$action");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['X-API-Key: YOUR_ZENROWS_API_KEY']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $res = curl_exec($ch);
    curl_close($ch);
    return $res;
}
echo control('stop');   // /cancel is an identical alias
echo control('pause');
echo control('resume');
?>
```

```go Go theme={"theme":"css-variables"}
package main

import (
    "io"
    "log"
    "net/http"
)

func control(action string) {
    req, _ := http.NewRequest("POST", "https://async.api.zenrows.com/v1/jobs/JOB_ID/"+action, nil)
    req.Header.Set("X-API-Key", "YOUR_ZENROWS_API_KEY")
    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        log.Fatalln(err)
    }
    defer resp.Body.Close()
    body, _ := io.ReadAll(resp.Body)
    log.Println(string(body))
}

func main() {
    control("stop") // /cancel is an identical alias
    control("pause")
    control("resume")
}
```

```ruby Ruby theme={"theme":"css-variables"}
# gem install faraday
require 'faraday'
conn = Faraday.new
conn.headers['X-API-Key'] = 'YOUR_ZENROWS_API_KEY'

# Stop (terminal); /cancel is an identical alias.
conn.post('https://async.api.zenrows.com/v1/jobs/JOB_ID/stop')
# Pause and resume the current run.
conn.post('https://async.api.zenrows.com/v1/jobs/JOB_ID/pause')
conn.post('https://async.api.zenrows.com/v1/jobs/JOB_ID/resume')
```

```bash cURL theme={"theme":"css-variables"}
# Stop the current run (terminal). /cancel is an identical alias.
curl -X POST "https://async.api.zenrows.com/v1/jobs/JOB_ID/stop" -H "X-API-Key: YOUR_ZENROWS_API_KEY"

# Pause the current run, then resume it later.
curl -X POST "https://async.api.zenrows.com/v1/jobs/JOB_ID/pause"  -H "X-API-Key: YOUR_ZENROWS_API_KEY"
curl -X POST "https://async.api.zenrows.com/v1/jobs/JOB_ID/resume" -H "X-API-Key: YOUR_ZENROWS_API_KEY"
```

**Stop and cancel.** `/stop` moves the latest run from `running` or `pending` to the terminal state `stopped`. No new tasks are picked up, tasks already in flight may still finish and record a result, and pending tasks are left as-is (not re-queued, not failed). Result bodies are kept; to remove them, follow up with `DELETE /jobs/{id}/runs/{run_id}` (see [Delete a job or a run](#delete-a-job-or-a-run)). It is idempotent on an already-stopped run, returns `409 run_not_stoppable` if the run is `completed`, `failed` or `deleted` (use a rerun to start fresh), and `404` on a deleted job. `/stop` sends no webhook event. `/cancel` is a pure alias for `/stop`.

**Pause and resume.** `/pause` reversibly suspends the latest run: the dispatcher stops polling its queue, while the run's `status` (`running` or `pending`) is unchanged, since pause is orthogonal to status. Tasks already in flight may still settle. `/resume` restarts polling. Both are idempotent (pausing a paused run, or resuming an active run, is a no-op), and both return `409 run_not_stoppable` when the latest run is terminal.

> [!WARNING]
>
> In-flight gateway calls still consume credits while a pause takes effect. For a hard cost-stop, use `/stop` (or `/cancel`) instead.

> [!NOTE]
>
> This is not the same as pausing a **schedule**. For scheduled jobs, `POST /jobs/{id}/schedule/state` controls whether new runs fire. The `/pause` and `/resume` endpoints here act on the current run.

### Delete a job or a run

You can remove data yourself when you no longer need it. Two levels are available: delete a single run's results, or delete an entire job.

| Endpoint | Purpose |
| - | - |
| `DELETE /jobs/{id}/runs/{run_id}` | Delete one run's stored results, keeping the job and its other runs. |
| `DELETE /jobs/{id}` | Delete the whole job, including every run and result. |

> [!NOTE]
>
> You are not required to delete anything to manage storage. A successful result stays readable through the API for **14 days**, counted from the task's `updated_at`: when it finished, or when a partial rerun carried it over, and the stored body is deleted automatically within 30 days of being scraped. These endpoints are for removing data sooner than that.

```python Python theme={"theme":"css-variables"}
## pip install requests
import requests
headers = {'X-API-Key': 'YOUR_ZENROWS_API_KEY'}

# Delete one run's results, keeping the job.
requests.delete('https://async.api.zenrows.com/v1/jobs/JOB_ID/runs/RUN_ID', headers=headers)

# Delete the whole job (all runs and results).
requests.delete('https://async.api.zenrows.com/v1/jobs/JOB_ID', headers=headers)
```

```javascript Node.js theme={"theme":"css-variables"}
// Delete one run's results, keeping the job.
await api("DELETE", "/jobs/JOB_ID/runs/RUN_ID");

// Delete the whole job (all runs and results).
await api("DELETE", "/jobs/JOB_ID");
```

```java Java theme={"theme":"css-variables"}
import org.apache.hc.client5.http.fluent.Request;

public class DeleteJob {
    public static void main(final String... args) throws Exception {
        String key = "YOUR_ZENROWS_API_KEY";
        String base = "https://async.api.zenrows.com/v1/jobs/JOB_ID";
        // Delete one run's results, keeping the job.
        Request.delete(base + "/runs/RUN_ID").addHeader("X-API-Key", key).execute().discardContent();
        // Delete the whole job (all runs and results).
        Request.delete(base).addHeader("X-API-Key", key).execute().discardContent();
    }
}
```

```php PHP theme={"theme":"css-variables"}
<?php
function del($path) {
    $ch = curl_init("https://async.api.zenrows.com/v1$path");
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['X-API-Key: YOUR_ZENROWS_API_KEY']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $res = curl_exec($ch);
    curl_close($ch);
    return $res;
}
echo del('/jobs/JOB_ID/runs/RUN_ID'); // one run's results
echo del('/jobs/JOB_ID');             // the whole job
?>
```

```go Go theme={"theme":"css-variables"}
package main

import (
    "log"
    "net/http"
)

func del(path string) {
    req, _ := http.NewRequest("DELETE", "https://async.api.zenrows.com/v1"+path, nil)
    req.Header.Set("X-API-Key", "YOUR_ZENROWS_API_KEY")
    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        log.Fatalln(err)
    }
    defer resp.Body.Close()
    log.Println(resp.Status)
}

func main() {
    del("/jobs/JOB_ID/runs/RUN_ID") // one run's results
    del("/jobs/JOB_ID")             // the whole job
}
```

```ruby Ruby theme={"theme":"css-variables"}
# gem install faraday
require 'faraday'
conn = Faraday.new
conn.headers['X-API-Key'] = 'YOUR_ZENROWS_API_KEY'

# Delete one run's results, keeping the job.
conn.delete('https://async.api.zenrows.com/v1/jobs/JOB_ID/runs/RUN_ID')
# Delete the whole job (all runs and results).
conn.delete('https://async.api.zenrows.com/v1/jobs/JOB_ID')
```

```bash cURL theme={"theme":"css-variables"}
# Delete one run's results, keeping the job.
curl -X DELETE "https://async.api.zenrows.com/v1/jobs/JOB_ID/runs/RUN_ID" -H "X-API-Key: YOUR_ZENROWS_API_KEY"

# Delete the whole job (all runs and results).
curl -X DELETE "https://async.api.zenrows.com/v1/jobs/JOB_ID" -H "X-API-Key: YOUR_ZENROWS_API_KEY"
```

**Delete a run.** `DELETE /jobs/{id}/runs/{run_id}` removes that run's stored result bodies while leaving the job and its other runs in place. Use it once you have downloaded what you need from the run. It returns `202 Accepted` and is idempotent, so deleting an already-deleted run is safe. It returns `409 run_has_descendants` when a later partial rerun reuses this run's results; delete those runs first, or delete the whole job.

**Delete a job.** `DELETE /jobs/{id}` removes the entire job, including every run and result, and frees its active-job slot. Deletion of the stored contents happens in the background, so the request returns `202 Accepted` right away and the data is cleared shortly after. Once deleted, `GET /jobs/{id}` returns `404` and the job no longer appears in the jobs list. Stopping a run first is not required; deleting a job with an active run stops it as part of the delete.

> [!NOTE]
>
> Delete is permanent. Download or export any results you want to keep before deleting a run or a job.

## 3. Collect your results

Retrieve the scraped content once a run completes.

### Download content

List a run's results with `GET /jobs/{job_id}/results`, filtered by `status` (`successful`, `failed`, `processing` for tasks that are pending or in progress, or `all`, the default) and paged with the `cursor` query parameter until the response has no `next_cursor`.

These read the job's latest run. To read an earlier run, such as the one a rerun replaced, use `GET /jobs/{job_id}/runs/{run_id}/results` and `GET /jobs/{job_id}/runs/{run_id}/tasks/{task_id}/content`. They take the same parameters. A task keeps its `task_id` across runs, so the same id reads its result in each run.

> [!NOTE]
>
> Each row's `result_url` is a presigned link valid for 2 hours, so fetch it promptly, and re-list the run to get fresh links. A successful task's body stays available for 14 days, counted from the task's `updated_at`: when it finished, or when a partial rerun carried it over. After that its row comes back with `status: "expired"` and no `result_url`, and `GET /jobs/{job_id}/tasks/{task_id}/content` returns `410 result_expired`. The `successful` filter still returns expired rows, so skip any row without a `result_url`. To remove results sooner, see [Delete a job or a run](#delete-a-job-or-a-run).

```python Python theme={"theme":"css-variables"}
## pip install requests
import requests

response = requests.get('https://async.api.zenrows.com/v1/jobs/JOB_ID/results',
                        headers={'X-API-Key': 'YOUR_ZENROWS_API_KEY'},
                        params={'status': 'successful'})
page = response.json()
for row in page['results']:
    print(row.get('external_id') or row['task_id'], '->', row.get('result_url', row['status']))
print('next_cursor:', page.get('next_cursor'))  # absent on the last page
```

```javascript Node.js theme={"theme":"css-variables"}
const page = await api("GET", "/jobs/JOB_ID/results", { query: { status: "successful" } });
for (const row of page.results) {
  console.log(row.external_id ?? row.task_id, "->", row.result_url);
}
console.log("next_cursor:", page.next_cursor);
```

```java Java theme={"theme":"css-variables"}
import org.apache.hc.client5.http.fluent.Request;

public class GetResults {
    public static void main(final String... args) throws Exception {
        String response = Request.get("https://async.api.zenrows.com/v1/jobs/JOB_ID/results?status=successful")
                .addHeader("X-API-Key", "YOUR_ZENROWS_API_KEY")
                .execute().returnContent().asString();
        System.out.println(response);
    }
}
```

```php PHP theme={"theme":"css-variables"}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://async.api.zenrows.com/v1/jobs/JOB_ID/results?status=successful');
curl_setopt($ch, CURLOPT_HTTPHEADER, ['X-API-Key: YOUR_ZENROWS_API_KEY']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
echo curl_exec($ch) . PHP_EOL;
curl_close($ch);
?>
```

```go Go theme={"theme":"css-variables"}
package main

import (
    "io"
    "log"
    "net/http"
)

func main() {
    req, err := http.NewRequest("GET", "https://async.api.zenrows.com/v1/jobs/JOB_ID/results?status=successful", nil)
    if err != nil {
        log.Fatalln(err)
    }
    req.Header.Set("X-API-Key", "YOUR_ZENROWS_API_KEY")
    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        log.Fatalln(err)
    }
    defer resp.Body.Close()
    body, _ := io.ReadAll(resp.Body)
    log.Println(string(body))
}
```

```ruby Ruby theme={"theme":"css-variables"}
# gem install faraday
require 'faraday'

conn = Faraday.new
res = conn.get('https://async.api.zenrows.com/v1/jobs/JOB_ID/results') do |req|
    req.headers['X-API-Key'] = 'YOUR_ZENROWS_API_KEY'
    req.params['status'] = 'successful'
end
print(res.body)
```

```bash cURL theme={"theme":"css-variables"}
curl "https://async.api.zenrows.com/v1/jobs/JOB_ID/results?status=successful" \
  -H "X-API-Key: YOUR_ZENROWS_API_KEY"
```

To page through every result and download each body, loop over the pages until the response has no `next_cursor`, fetching each presigned `result_url` promptly.

```python Python theme={"theme":"css-variables"}
## pip install requests
import os, requests

headers = {'X-API-Key': 'YOUR_ZENROWS_API_KEY'}
os.makedirs('out', exist_ok=True)
cursor = None
while True:
    page = requests.get('https://async.api.zenrows.com/v1/jobs/JOB_ID/results',
                        headers=headers, params={'status': 'successful', 'cursor': cursor}).json()
    for row in page['results']:
        if not row.get('result_url'):
            continue  # expired: the body aged past its retention window
        # result_url is a presigned link, valid 2h, so fetch it promptly.
        content = requests.get(row['result_url']).content
        with open(f"out/{row.get('external_id') or row['task_id']}", 'wb') as f:
            f.write(content)
    cursor = page.get('next_cursor')  # absent on the last page
    if not cursor:
        break
```

```javascript Node.js theme={"theme":"css-variables"}
async function* iterResults(jobId, status = "all") {
  let cursor;
  do {
    const page = await api("GET", `/jobs/${jobId}/results`, { query: { status, cursor } });
    yield* page.results;
    cursor = page.next_cursor;
  } while (cursor);
}

import { writeFile } from "node:fs/promises";

for await (const row of iterResults("JOB_ID", "successful")) {
  if (!row.result_url) continue; // expired: the body aged past its retention window
  // row.result_url is a presigned link, valid 2h, so fetch it promptly.
  const bytes = Buffer.from(await (await fetch(row.result_url)).arrayBuffer());
  await writeFile(`./out/${row.external_id ?? row.task_id}`, bytes);
}
```

```java Java theme={"theme":"css-variables"}
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.hc.client5.http.fluent.Request;
import java.nio.file.Files;
import java.nio.file.Path;

public class DownloadResults {
    static final ObjectMapper M = new ObjectMapper();

    public static void main(final String... args) throws Exception {
        String key = "YOUR_ZENROWS_API_KEY";
        String cursor = null;
        do {
            String url = "https://async.api.zenrows.com/v1/jobs/JOB_ID/results?status=successful"
                    + (cursor != null ? "&cursor=" + cursor : "");
            JsonNode page = M.readTree(Request.get(url).addHeader("X-API-Key", key)
                    .execute().returnContent().asString());
            for (JsonNode row : page.path("results")) {
                if (!row.hasNonNull("result_url")) continue; // expired
                // result_url is a presigned link, valid 2h, so fetch it promptly.
                byte[] bytes = Request.get(row.path("result_url").asText())
                        .execute().returnContent().asBytes();
                String name = row.path("external_id").asText(row.path("task_id").asText());
                Files.write(Path.of("out", name), bytes);
            }
            cursor = page.path("next_cursor").asText(null);
        } while (cursor != null && !cursor.isEmpty());
    }
}
```

```php PHP theme={"theme":"css-variables"}
<?php
$key = 'YOUR_ZENROWS_API_KEY';
@mkdir('out');
$cursor = null;
do {
    $url = 'https://async.api.zenrows.com/v1/jobs/JOB_ID/results?status=successful'
        . ($cursor ? '&cursor=' . urlencode($cursor) : '');
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ["X-API-Key: $key"]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $page = json_decode(curl_exec($ch), true);
    curl_close($ch);
    foreach ($page['results'] as $row) {
        if (empty($row['result_url'])) continue; // expired
        // result_url is a presigned link, valid 2h, so fetch it promptly.
        $name = $row['external_id'] ?? $row['task_id'];
        file_put_contents("out/$name", file_get_contents($row['result_url']));
    }
    $cursor = $page['next_cursor'] ?? null;
} while ($cursor);
?>
```

```go Go theme={"theme":"css-variables"}
package main

import (
    "encoding/json"
    "io"
    "log"
    "net/http"
    "os"
    "path/filepath"
)

func get(url, key string) []byte {
    req, _ := http.NewRequest("GET", url, nil)
    if key != "" {
        req.Header.Set("X-API-Key", key)
    }
    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        log.Fatalln(err)
    }
    defer resp.Body.Close()
    body, _ := io.ReadAll(resp.Body)
    return body
}

func main() {
    key := "YOUR_ZENROWS_API_KEY"
    os.MkdirAll("out", 0o755)
    cursor := ""
    for {
        url := "https://async.api.zenrows.com/v1/jobs/JOB_ID/results?status=successful"
        if cursor != "" {
            url += "&cursor=" + cursor
        }
        var page struct {
            Results []struct {
                TaskID     string `json:"task_id"`
                ExternalID string `json:"external_id"`
                ResultURL  string `json:"result_url"`
            } `json:"results"`
            NextCursor string `json:"next_cursor"`
        }
        json.Unmarshal(get(url, key), &page)
        for _, row := range page.Results {
            if row.ResultURL == "" {
                continue // expired: the body aged past its retention window
            }
            // result_url is a presigned link, valid 2h, so fetch it promptly.
            name := row.ExternalID
            if name == "" {
                name = row.TaskID
            }
            os.WriteFile(filepath.Join("out", name), get(row.ResultURL, ""), 0o644)
        }
        cursor = page.NextCursor
        if cursor == "" {
            break
        }
    }
}
```

```ruby Ruby theme={"theme":"css-variables"}
# gem install faraday
require 'faraday'
require 'json'

key = 'YOUR_ZENROWS_API_KEY'
Dir.mkdir('out') unless Dir.exist?('out')
cursor = nil
loop do
    res = Faraday.get('https://async.api.zenrows.com/v1/jobs/JOB_ID/results') do |req|
        req.headers['X-API-Key'] = key
        req.params['status'] = 'successful'
        req.params['cursor'] = cursor if cursor
    end
    page = JSON.parse(res.body)
    page['results'].each do |row|
        next unless row['result_url'] # expired
        # result_url is a presigned link, valid 2h, so fetch it promptly.
        name = row['external_id'] || row['task_id']
        File.write("out/#{name}", Faraday.get(row['result_url']).body, mode: 'wb')
    end
    cursor = page['next_cursor']
    break unless cursor
end
```

```bash cURL theme={"theme":"css-variables"}
# Page with a shell loop, then download each presigned result_url.
mkdir -p out
cursor=""
while :; do
  page=$(curl -s "https://async.api.zenrows.com/v1/jobs/JOB_ID/results?status=successful&cursor=$cursor" \
    -H "X-API-Key: YOUR_ZENROWS_API_KEY")
  echo "$page" | jq -r '.results[] | select(.result_url) | [(.external_id // .task_id), .result_url] | @tsv' \
    | while IFS=$'\t' read -r name url; do curl -s "$url" -o "out/$name"; done
  cursor=$(echo "$page" | jq -r '.next_cursor // empty')
  [ -z "$cursor" ] && break
done
```

You can also fetch one task's body directly with `GET /jobs/{job_id}/tasks/{task_id}/content`.

* `200`: returns the content
* `409 task_not_ready`: the task is still pending or processing
* `410 result_expired`: the body aged past its 14-day availability window
* `422`: the task failed and the body holds the stored error.

```python Python theme={"theme":"css-variables"}
## pip install requests
import requests

# 200 = content; 409 = still pending/processing; 422 = failed (body is the error)
response = requests.get('https://async.api.zenrows.com/v1/jobs/JOB_ID/tasks/TASK_ID/content',
                        headers={'X-API-Key': 'YOUR_ZENROWS_API_KEY'})
print(response.status_code)
print(response.text)
```

```javascript Node.js theme={"theme":"css-variables"}
// 200 = content; 409 = still pending/processing; 422 = failed (body is the error)
const content = await api("GET", "/jobs/JOB_ID/tasks/TASK_ID/content");
```

```java Java theme={"theme":"css-variables"}
import org.apache.hc.client5.http.fluent.Request;

public class TaskContent {
    public static void main(final String... args) throws Exception {
        // 200 = content; 409 = still pending/processing; 422 = failed (body is the error)
        String response = Request.get("https://async.api.zenrows.com/v1/jobs/JOB_ID/tasks/TASK_ID/content")
                .addHeader("X-API-Key", "YOUR_ZENROWS_API_KEY")
                .execute().returnContent().asString();
        System.out.println(response);
    }
}
```

```php PHP theme={"theme":"css-variables"}
<?php
// 200 = content; 409 = still pending/processing; 422 = failed (body is the error)
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://async.api.zenrows.com/v1/jobs/JOB_ID/tasks/TASK_ID/content');
curl_setopt($ch, CURLOPT_HTTPHEADER, ['X-API-Key: YOUR_ZENROWS_API_KEY']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
echo curl_getinfo($ch, CURLINFO_HTTP_CODE) . PHP_EOL;
echo $response . PHP_EOL;
curl_close($ch);
?>
```

```go Go theme={"theme":"css-variables"}
package main

import (
    "io"
    "log"
    "net/http"
)

func main() {
    // 200 = content; 409 = still pending/processing; 422 = failed (body is the error)
    req, err := http.NewRequest("GET", "https://async.api.zenrows.com/v1/jobs/JOB_ID/tasks/TASK_ID/content", nil)
    if err != nil {
        log.Fatalln(err)
    }
    req.Header.Set("X-API-Key", "YOUR_ZENROWS_API_KEY")
    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        log.Fatalln(err)
    }
    defer resp.Body.Close()
    body, _ := io.ReadAll(resp.Body)
    log.Println(resp.StatusCode, string(body))
}
```

```ruby Ruby theme={"theme":"css-variables"}
# gem install faraday
require 'faraday'

# 200 = content; 409 = still pending/processing; 422 = failed (body is the error)
conn = Faraday.new
res = conn.get('https://async.api.zenrows.com/v1/jobs/JOB_ID/tasks/TASK_ID/content') do |req|
    req.headers['X-API-Key'] = 'YOUR_ZENROWS_API_KEY'
end
print(res.status)
print(res.body)
```

```bash cURL theme={"theme":"css-variables"}
# 200 = content; 409 = still pending/processing; 422 = failed (body is the error)
curl -i "https://async.api.zenrows.com/v1/jobs/JOB_ID/tasks/TASK_ID/content" \
  -H "X-API-Key: YOUR_ZENROWS_API_KEY"
```

> [!TIP]
>
> A failed task's results row already carries `row.error` (`{ code, detail, ... }`), so you rarely need the content endpoint to inspect a failure. Treat the error `code` as a hint: it does not yet reliably distinguish blocked, not-found, and timeout.

### Bulk export (ZIP)

Bundle an entire run's result bodies into a single ZIP. Start the export with `POST /jobs/{job_id}/runs/{run_id}/exports`, poll the export until `status` is `completed`, then download the presigned `download_url`.

> [!NOTE]
>
> The API presigns `download_url` fresh on each poll, valid for 2 hours. The export itself expires 12 hours after creation; polling it after that returns `410 result_expired`, so start a new export. A run whose combined results exceed 100 GiB fails with a clear error instead of producing a partial archive. An export of a partial-rerun run holds only the tasks that run scraped itself, not the results it carried over.

```python Python theme={"theme":"css-variables"}
## pip install requests
import requests

started = requests.post('https://async.api.zenrows.com/v1/jobs/JOB_ID/runs/RUN_ID/exports',
                        headers={'X-API-Key': 'YOUR_ZENROWS_API_KEY'}).json()
print(started['export_id'], started['status'])
# Poll the export by id until status == 'completed', then download started['download_url'].
```

```javascript Node.js theme={"theme":"css-variables"}
const started = await api("POST", "/jobs/JOB_ID/runs/RUN_ID/exports");
console.log(started.export_id, started.status);
// Poll the export by id until status === 'completed', then download download_url.
```

```java Java theme={"theme":"css-variables"}
import org.apache.hc.client5.http.fluent.Request;

public class StartExport {
    public static void main(final String... args) throws Exception {
        String response = Request.post("https://async.api.zenrows.com/v1/jobs/JOB_ID/runs/RUN_ID/exports")
                .addHeader("X-API-Key", "YOUR_ZENROWS_API_KEY")
                .execute().returnContent().asString();
        System.out.println(response);
        // Poll the export by id until status is "completed", then download download_url.
    }
}
```

```php PHP theme={"theme":"css-variables"}
<?php
$ch = curl_init('https://async.api.zenrows.com/v1/jobs/JOB_ID/runs/RUN_ID/exports');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['X-API-Key: YOUR_ZENROWS_API_KEY']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
echo curl_exec($ch) . PHP_EOL;
curl_close($ch);
// Poll the export by id until status is "completed", then download download_url.
?>
```

```go Go theme={"theme":"css-variables"}
package main

import (
    "io"
    "log"
    "net/http"
)

func main() {
    req, err := http.NewRequest("POST", "https://async.api.zenrows.com/v1/jobs/JOB_ID/runs/RUN_ID/exports", nil)
    if err != nil {
        log.Fatalln(err)
    }
    req.Header.Set("X-API-Key", "YOUR_ZENROWS_API_KEY")
    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        log.Fatalln(err)
    }
    defer resp.Body.Close()
    body, _ := io.ReadAll(resp.Body)
    log.Println(string(body))
    // Poll the export by id until status is "completed", then download download_url.
}
```

```ruby Ruby theme={"theme":"css-variables"}
# gem install faraday
require 'faraday'

conn = Faraday.new
res = conn.post('https://async.api.zenrows.com/v1/jobs/JOB_ID/runs/RUN_ID/exports') do |req|
    req.headers['X-API-Key'] = 'YOUR_ZENROWS_API_KEY'
end
print(res.body)
# Poll the export by id until status is "completed", then download download_url.
```

```bash cURL theme={"theme":"css-variables"}
# Start the export, then poll the returned export_id until status is "completed".
curl -X POST "https://async.api.zenrows.com/v1/jobs/JOB_ID/runs/RUN_ID/exports" \
  -H "X-API-Key: YOUR_ZENROWS_API_KEY"

curl "https://async.api.zenrows.com/v1/jobs/JOB_ID/runs/RUN_ID/exports/EXPORT_ID" \
  -H "X-API-Key: YOUR_ZENROWS_API_KEY"
```

Start the export, poll until it is `completed`, then download the ZIP.

```python Python theme={"theme":"css-variables"}
## pip install requests
import time, requests

headers = {'X-API-Key': 'YOUR_ZENROWS_API_KEY'}
base = 'https://async.api.zenrows.com/v1/jobs/JOB_ID/runs/RUN_ID/exports'

exp = requests.post(base, headers=headers).json()
while exp['status'] not in ('completed', 'failed'):
    time.sleep(3)
    exp = requests.get(f"{base}/{exp['export_id']}", headers=headers).json()
if exp['status'] == 'failed':
    raise RuntimeError(exp.get('error'))

with open('results.zip', 'wb') as f:
    f.write(requests.get(exp['download_url']).content)
```

```javascript Node.js theme={"theme":"css-variables"}
import { writeFile } from "node:fs/promises";

let exp = await api("POST", "/jobs/JOB_ID/runs/RUN_ID/exports");
while (exp.status !== "completed" && exp.status !== "failed") {
  await new Promise((r) => setTimeout(r, 3000));
  exp = await api("GET", `/jobs/JOB_ID/runs/RUN_ID/exports/${exp.export_id}`);
}
if (exp.status === "failed") throw new Error(exp.error);

const zip = Buffer.from(await (await fetch(exp.download_url)).arrayBuffer());
await writeFile("results.zip", zip);
```

```java Java theme={"theme":"css-variables"}
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.hc.client5.http.fluent.Request;
import java.nio.file.Files;
import java.nio.file.Path;

public class ExportRun {
    static final ObjectMapper M = new ObjectMapper();

    public static void main(final String... args) throws Exception {
        String key = "YOUR_ZENROWS_API_KEY";
        String base = "https://async.api.zenrows.com/v1/jobs/JOB_ID/runs/RUN_ID/exports";

        JsonNode exp = M.readTree(Request.post(base).addHeader("X-API-Key", key)
                .execute().returnContent().asString());
        String id = exp.path("export_id").asText();
        while (!exp.path("status").asText().equals("completed") && !exp.path("status").asText().equals("failed")) {
            Thread.sleep(3000);
            exp = M.readTree(Request.get(base + "/" + id).addHeader("X-API-Key", key)
                    .execute().returnContent().asString());
        }
        if (exp.path("status").asText().equals("failed")) throw new RuntimeException(exp.path("error").asText());

        byte[] zip = Request.get(exp.path("download_url").asText()).execute().returnContent().asBytes();
        Files.write(Path.of("results.zip"), zip);
    }
}
```

```php PHP theme={"theme":"css-variables"}
<?php
$key = 'YOUR_ZENROWS_API_KEY';
$base = 'https://async.api.zenrows.com/v1/jobs/JOB_ID/runs/RUN_ID/exports';

function call($method, $url, $key) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ["X-API-Key: $key"]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $res = curl_exec($ch);
    curl_close($ch);
    return json_decode($res, true);
}

$exp = call('POST', $base, $key);
while (!in_array($exp['status'], ['completed', 'failed'], true)) {
    sleep(3);
    $exp = call('GET', "$base/{$exp['export_id']}", $key);
}
if ($exp['status'] === 'failed') throw new RuntimeException($exp['error'] ?? 'export failed');

file_put_contents('results.zip', file_get_contents($exp['download_url']));
?>
```

```go Go theme={"theme":"css-variables"}
package main

import (
    "encoding/json"
    "io"
    "log"
    "net/http"
    "os"
    "time"
)

func call(method, url, key string) map[string]any {
    req, _ := http.NewRequest(method, url, nil)
    if key != "" {
        req.Header.Set("X-API-Key", key)
    }
    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        log.Fatalln(err)
    }
    defer resp.Body.Close()
    body, _ := io.ReadAll(resp.Body)
    var out map[string]any
    json.Unmarshal(body, &out)
    return out
}

func main() {
    key := "YOUR_ZENROWS_API_KEY"
    base := "https://async.api.zenrows.com/v1/jobs/JOB_ID/runs/RUN_ID/exports"

    exp := call("POST", base, key)
    id, _ := exp["export_id"].(string)
    for exp["status"] != "completed" && exp["status"] != "failed" {
        time.Sleep(3 * time.Second)
        exp = call("GET", base+"/"+id, key)
    }
    if exp["status"] == "failed" {
        log.Fatalln(exp["error"])
    }

    req, _ := http.NewRequest("GET", exp["download_url"].(string), nil)
    resp, _ := http.DefaultClient.Do(req)
    defer resp.Body.Close()
    out, _ := os.Create("results.zip")
    defer out.Close()
    io.Copy(out, resp.Body)
}
```

```ruby Ruby theme={"theme":"css-variables"}
# gem install faraday
require 'faraday'
require 'json'

key = 'YOUR_ZENROWS_API_KEY'
base = 'https://async.api.zenrows.com/v1/jobs/JOB_ID/runs/RUN_ID/exports'

exp = JSON.parse(Faraday.post(base) { |r| r.headers['X-API-Key'] = key }.body)
until %w[completed failed].include?(exp['status'])
    sleep 3
    exp = JSON.parse(Faraday.get("#{base}/#{exp['export_id']}") { |r| r.headers['X-API-Key'] = key }.body)
end
raise(exp['error'] || 'export failed') if exp['status'] == 'failed'

File.write('results.zip', Faraday.get(exp['download_url']).body, mode: 'wb')
```

```bash cURL theme={"theme":"css-variables"}
base="https://async.api.zenrows.com/v1/jobs/JOB_ID/runs/RUN_ID/exports"
started=$(curl -s -X POST "$base" -H "X-API-Key: YOUR_ZENROWS_API_KEY")
id=$(echo "$started" | jq -r '.export_id')

while :; do
  exp=$(curl -s "$base/$id" -H "X-API-Key: YOUR_ZENROWS_API_KEY")
  status=$(echo "$exp" | jq -r '.status')
  case "$status" in completed|failed) break ;; esac
  sleep 3
done
[ "$status" = "failed" ] && { echo "export failed"; exit 1; }

curl -s "$(echo "$exp" | jq -r '.download_url')" -o results.zip
```

## 4. Webhooks and notifications

Get notified when a run finishes, and secure those callbacks.

### Set up webhooks

Attach a webhook so the API POSTs one event to your HTTPS URL when a run finishes on its own: `run.completed` when it completes, or `run.failed` when an account-level error ends it, for example on running out of credits. Stopping a run yourself sends no event. Set `signature: true` for HMAC-signed deliveries (see [Manage HMAC keys](#manage-hmac-keys)).

You can attach it on the submit body, read it with `GET /jobs/{id}/webhook`, replace it with `PUT /jobs/{id}/webhook` (send both `url` and `signature`), remove it with `DELETE /jobs/{id}/webhook`, and probe a receiver with `POST /webhook/test`.

**Delivery.** Each delivery is a `POST` with `Content-Type: application/json`, `User-Agent: zenrows-webhook/v1`, an `X-ZenRows-Event-Id` header, and, when signed, an `X-Signature` header. Answer with any `2xx` within 10 seconds; acknowledge first and process the event afterwards. A delivery that fails, times out or gets a non-2xx answer is retried with exponential backoff, starting at 30 seconds and growing up to 8 hours between attempts, for up to 3 days, and then dropped. Because a retry can repeat an event you already received, deduplicate on `X-ZenRows-Event-Id`.

**Payload.** The body uses the schema `zenrows.webhook/v1`. `external_id` and `metadata` are the job's own, and appear only when you set them. `failure_reason` and `failure_detail` appear only on `run.failed`.

```json theme={"theme":"css-variables"}
{
  "schema": "zenrows.webhook/v1",
  "event_id": "01JA7Q3B6R6V7D0Y3S5W2T9M4K",
  "event_type": "run.completed",
  "occurred_at": "2027-01-15T09:12:44Z",
  "job_id": "01JA7PZ4Y8M3E6F9C2B1N5K7QH",
  "external_id": "nightly-catalog",
  "metadata": { "team": "pricing" },
  "run_id": "01JA7PZ4Y9T2R8V6X4C0B3N1MD",
  "run_sequence": 1,
  "stats": { "total": 2, "completed": 2, "successful": 2, "failed": 0, "spend": { "credits": 50, "cost": 0.05 } }
}
```

> [!WARNING]
>
> `signature: true` needs an active HMAC key on your account. Create one first with `POST /v1/hmac/keys/rotate`, as shown in [Manage HMAC keys](#manage-hmac-keys); without it, the request fails with `400 webhook_signing_requires_active_key`. To try these samples before you create a key, set `signature` to `false`.

```python Python theme={"theme":"css-variables"}
## pip install requests
import requests, json

headers = {'X-API-Key': 'YOUR_ZENROWS_API_KEY', 'Content-Type': 'application/json'}
webhook = {'url': 'https://your-app.com/webhooks/zenrows', 'signature': True}

# Set or replace the webhook on an existing job:
requests.put('https://async.api.zenrows.com/v1/jobs/JOB_ID/webhook', headers=headers, data=json.dumps(webhook))

# Probe a receiver before wiring it up:
probe = requests.post('https://async.api.zenrows.com/v1/webhook/test', headers=headers, data=json.dumps(webhook)).json()
print(probe['delivered'], probe['status_code'])

# Stop deliveries:
requests.delete('https://async.api.zenrows.com/v1/jobs/JOB_ID/webhook', headers={'X-API-Key': 'YOUR_ZENROWS_API_KEY'})
```

```javascript Node.js theme={"theme":"css-variables"}
const webhook = { url: "https://your-app.com/webhooks/zenrows", signature: true };

// At submit time, include it on the body: { ..., webhook }.
// Or manage it on an existing job:
await api("PUT", "/jobs/JOB_ID/webhook", { body: webhook });
await api("DELETE", "/jobs/JOB_ID/webhook"); // stop deliveries

// Verify a receiver before wiring it to a job:
const probe = await api("POST", "/webhook/test", { body: webhook });
console.log(probe.delivered, probe.status_code);
```

```java Java theme={"theme":"css-variables"}
import org.apache.hc.client5.http.fluent.Request;
import org.apache.hc.core5.http.ContentType;

public class Webhook {
    public static void main(final String... args) throws Exception {
        String key = "YOUR_ZENROWS_API_KEY";
        String webhook = "{\"url\":\"https://your-app.com/webhooks/zenrows\",\"signature\":true}";

        // Set or replace the webhook on an existing job:
        Request.put("https://async.api.zenrows.com/v1/jobs/JOB_ID/webhook")
                .addHeader("X-API-Key", key).bodyString(webhook, ContentType.APPLICATION_JSON)
                .execute().discardContent();

        // Probe a receiver:
        String probe = Request.post("https://async.api.zenrows.com/v1/webhook/test")
                .addHeader("X-API-Key", key).bodyString(webhook, ContentType.APPLICATION_JSON)
                .execute().returnContent().asString();
        System.out.println(probe);

        // Stop deliveries:
        Request.delete("https://async.api.zenrows.com/v1/jobs/JOB_ID/webhook")
                .addHeader("X-API-Key", key).execute().discardContent();
    }
}
```

```php PHP theme={"theme":"css-variables"}
<?php
$key = 'YOUR_ZENROWS_API_KEY';
$webhook = json_encode(['url' => 'https://your-app.com/webhooks/zenrows', 'signature' => true]);

// Set or replace the webhook on an existing job:
$ch = curl_init('https://async.api.zenrows.com/v1/jobs/JOB_ID/webhook');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS, $webhook);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["X-API-Key: $key", 'Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_exec($ch);
curl_close($ch);

// Probe a receiver:
$ch = curl_init('https://async.api.zenrows.com/v1/webhook/test');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $webhook);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["X-API-Key: $key", 'Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
echo curl_exec($ch) . PHP_EOL;
curl_close($ch);
?>
```

```go Go theme={"theme":"css-variables"}
package main

import (
    "bytes"
    "io"
    "log"
    "net/http"
)

func main() {
    webhook := `{ "url": "https://your-app.com/webhooks/zenrows", "signature": true }`

    // Set or replace the webhook on an existing job:
    putReq, _ := http.NewRequest("PUT", "https://async.api.zenrows.com/v1/jobs/JOB_ID/webhook", bytes.NewBufferString(webhook))
    putReq.Header.Set("X-API-Key", "YOUR_ZENROWS_API_KEY")
    putReq.Header.Set("Content-Type", "application/json")
    if _, err := http.DefaultClient.Do(putReq); err != nil {
        log.Fatalln(err)
    }

    // Probe a receiver:
    testReq, _ := http.NewRequest("POST", "https://async.api.zenrows.com/v1/webhook/test", bytes.NewBufferString(webhook))
    testReq.Header.Set("X-API-Key", "YOUR_ZENROWS_API_KEY")
    testReq.Header.Set("Content-Type", "application/json")
    resp, err := http.DefaultClient.Do(testReq)
    if err != nil {
        log.Fatalln(err)
    }
    defer resp.Body.Close()
    body, _ := io.ReadAll(resp.Body)
    log.Println(string(body))
}
```

```ruby Ruby theme={"theme":"css-variables"}
# gem install faraday
require 'faraday'
require 'json'

conn = Faraday.new
conn.headers['X-API-Key'] = 'YOUR_ZENROWS_API_KEY'
conn.headers['Content-Type'] = 'application/json'
webhook = { url: 'https://your-app.com/webhooks/zenrows', signature: true }.to_json

# Set or replace the webhook on an existing job:
conn.put('https://async.api.zenrows.com/v1/jobs/JOB_ID/webhook', webhook)

# Probe a receiver:
puts conn.post('https://async.api.zenrows.com/v1/webhook/test', webhook).body

# Stop deliveries:
conn.delete('https://async.api.zenrows.com/v1/jobs/JOB_ID/webhook')
```

```bash cURL theme={"theme":"css-variables"}
# Set or replace the webhook on an existing job:
curl -X PUT "https://async.api.zenrows.com/v1/jobs/JOB_ID/webhook" \
  -H "X-API-Key: YOUR_ZENROWS_API_KEY" -H "Content-Type: application/json" \
  -d '{ "url": "https://your-app.com/webhooks/zenrows", "signature": true }'

# Probe a receiver:
curl -X POST "https://async.api.zenrows.com/v1/webhook/test" \
  -H "X-API-Key: YOUR_ZENROWS_API_KEY" -H "Content-Type: application/json" \
  -d '{ "url": "https://your-app.com/webhooks/zenrows", "signature": false }'

# Stop deliveries:
curl -X DELETE "https://async.api.zenrows.com/v1/jobs/JOB_ID/webhook" \
  -H "X-API-Key: YOUR_ZENROWS_API_KEY"
```

> [!TIP]
>
> Webhook delivery is best effort: a delivery that keeps failing is dropped after 3 days of retries. The run state and result URLs remain the reliable source of truth, so poll `GET /jobs/{id}` if an event never arrives.

When a run fails, the webhook receives a `run.failed` event. It carries the run's `failure_reason` and `failure_detail`, the same fields described in [Why a run failed](#why-a-run-failed).

### Manage HMAC keys

Signed webhook deliveries need an active HMAC key for your organization. Rotation uses two slots, an active key plus a candidate, so you can roll keys without downtime.

* `POST /hmac/keys/rotate` creates the first key or stages a candidate (the secret is returned once)
* `POST /hmac/keys/rotate/finalize` promotes the candidate and retires the old key
* `DELETE /hmac/keys/rotate` discards a staged candidate
* `GET /hmac/keys` lists key metadata without secrets

```python Python theme={"theme":"css-variables"}
## pip install requests
import requests
headers = {'X-API-Key': 'YOUR_ZENROWS_API_KEY'}

created = requests.post('https://async.api.zenrows.com/v1/hmac/keys/rotate', headers=headers).json()
print(created)  # store created['secret'] now; it is returned only once

requests.post('https://async.api.zenrows.com/v1/hmac/keys/rotate/finalize', headers=headers)
# requests.delete('https://async.api.zenrows.com/v1/hmac/keys/rotate', headers=headers)  # discard candidate
print(requests.get('https://async.api.zenrows.com/v1/hmac/keys', headers=headers).json())
```

```javascript Node.js theme={"theme":"css-variables"}
const created = await api("POST", "/hmac/keys/rotate");
console.log(created.kid, created.secret); // the secret is returned ONCE, so store it now

await api("POST", "/hmac/keys/rotate/finalize"); // promote candidate -> active, retire the old
// await api("DELETE", "/hmac/keys/rotate");     // or discard the candidate
console.log(await api("GET", "/hmac/keys"));     // metadata only; never returns secrets
```

```java Java theme={"theme":"css-variables"}
import org.apache.hc.client5.http.fluent.Request;

public class HmacKeys {
    public static void main(final String... args) throws Exception {
        String key = "YOUR_ZENROWS_API_KEY";

        String created = Request.post("https://async.api.zenrows.com/v1/hmac/keys/rotate")
                .addHeader("X-API-Key", key).execute().returnContent().asString();
        System.out.println(created); // store the secret now; it is returned only once

        Request.post("https://async.api.zenrows.com/v1/hmac/keys/rotate/finalize")
                .addHeader("X-API-Key", key).execute().discardContent();
        // Request.delete("https://async.api.zenrows.com/v1/hmac/keys/rotate")
        //         .addHeader("X-API-Key", key).execute().discardContent(); // discard candidate

        String list = Request.get("https://async.api.zenrows.com/v1/hmac/keys")
                .addHeader("X-API-Key", key).execute().returnContent().asString();
        System.out.println(list);
    }
}
```

```php PHP theme={"theme":"css-variables"}
<?php
$key = 'YOUR_ZENROWS_API_KEY';
function call($method, $path, $key) {
    $ch = curl_init('https://async.api.zenrows.com/v1' . $path);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ["X-API-Key: $key"]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $res = curl_exec($ch);
    curl_close($ch);
    return $res;
}

echo call('POST', '/hmac/keys/rotate', $key) . PHP_EOL;          // store the secret now
call('POST', '/hmac/keys/rotate/finalize', $key);                // promote the candidate
// call('DELETE', '/hmac/keys/rotate', $key);                    // or discard the candidate
echo call('GET', '/hmac/keys', $key) . PHP_EOL;                  // metadata only
?>
```

```go Go theme={"theme":"css-variables"}
package main

import (
    "io"
    "log"
    "net/http"
)

func call(method, path string) string {
    req, _ := http.NewRequest(method, "https://async.api.zenrows.com/v1"+path, nil)
    req.Header.Set("X-API-Key", "YOUR_ZENROWS_API_KEY")
    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        log.Fatalln(err)
    }
    defer resp.Body.Close()
    body, _ := io.ReadAll(resp.Body)
    return string(body)
}

func main() {
    log.Println(call("POST", "/hmac/keys/rotate"))           // store the secret now
    call("POST", "/hmac/keys/rotate/finalize")               // promote the candidate
    // call("DELETE", "/hmac/keys/rotate")                   // or discard the candidate
    log.Println(call("GET", "/hmac/keys"))                   // metadata only
}
```

```ruby Ruby theme={"theme":"css-variables"}
# gem install faraday
require 'faraday'

conn = Faraday.new
conn.headers['X-API-Key'] = 'YOUR_ZENROWS_API_KEY'

puts conn.post('https://async.api.zenrows.com/v1/hmac/keys/rotate').body   # store the secret now
conn.post('https://async.api.zenrows.com/v1/hmac/keys/rotate/finalize')    # promote the candidate
# conn.delete('https://async.api.zenrows.com/v1/hmac/keys/rotate')         # or discard the candidate
puts conn.get('https://async.api.zenrows.com/v1/hmac/keys').body           # metadata only
```

```bash cURL theme={"theme":"css-variables"}
# Create the active key or stage a candidate (the secret is returned once):
curl -X POST "https://async.api.zenrows.com/v1/hmac/keys/rotate" -H "X-API-Key: YOUR_ZENROWS_API_KEY"

# Promote the candidate to active and retire the old key:
curl -X POST "https://async.api.zenrows.com/v1/hmac/keys/rotate/finalize" -H "X-API-Key: YOUR_ZENROWS_API_KEY"

# Or discard the staged candidate:
curl -X DELETE "https://async.api.zenrows.com/v1/hmac/keys/rotate" -H "X-API-Key: YOUR_ZENROWS_API_KEY"

# List key metadata (never returns secrets):
curl "https://async.api.zenrows.com/v1/hmac/keys" -H "X-API-Key: YOUR_ZENROWS_API_KEY"
```

### Verify signed webhooks

When `signature: true`, each delivery includes an `X-Signature` header in the form `t=<unix>,v1=<hex>,kid=<key id>`, where `t` is the Unix timestamp of the attempt, `v1` is the signature, and `kid` identifies the key used.

To verify a delivery:

1. Look up the secret that matches the delivery's `kid`. Keep both keys during a [rotation](#manage-hmac-keys).
2. Base64-decode the secret to its 32 key bytes. The API returns it base64-encoded, and the HMAC key is the decoded bytes, not the text.
3. Compute `HMAC-SHA256(key, "<t>.<raw_body>")`, signing the timestamp, a literal dot, and the raw request body, as lowercase hex.
4. Compare the result to `v1` in constant time. If they match, the delivery is authentic.
5. Reject a delivery whose `t` is more than 5 minutes from your clock, so a captured delivery can't be replayed later.

The SDKs do all of this in one call: `verify_webhook_signature` in [Python](https://docs.zenrows.com/batch/sdk/python.md#signed-webhooks-hmac-keys), `verifyWebhookSignature` in [Node.js](https://docs.zenrows.com/batch/sdk/nodejs.md#signed-webhooks-hmac-keys) and `VerifyWebhookSignature` in [Go](https://docs.zenrows.com/batch/sdk/go.md#webhooks-and-hmac-keys).

Always sign the raw request body, never a re-serialized version, or the signature will not match. If `signature` is `false`, no `X-Signature` header is sent, so authenticate the callback another way, such as a secret path in the URL. Either way, deduplicate on the `X-ZenRows-Event-Id` header, since the same delivery can arrive more than once.

The examples below check the timestamp and compare the expected signature to `v1` in your receiver.

```python Python theme={"theme":"css-variables"}
import hmac, hashlib, base64, time

def verify(raw_body: bytes, t: str, v1: str, secret_b64: str) -> bool:
    if abs(time.time() - int(t)) > 300:  # reject replays older than 5 minutes
        return False
    secret = base64.b64decode(secret_b64)
    expected = hmac.new(secret, f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, v1)
```

```javascript Node.js theme={"theme":"css-variables"}
import crypto from "node:crypto";

// SECRETS maps kid -> the base64 secret you captured at /hmac/keys/rotate.
function verifyWebhook(rawBody, signatureHeader, SECRETS) {
  const parts = Object.fromEntries(
    signatureHeader.split(",").map((kv) => kv.split("="))
  ); // { t, v1, kid }
  const secret = SECRETS[parts.kid];
  if (!secret) return false;
  if (Math.abs(Date.now() / 1000 - Number(parts.t)) > 300) return false; // replay window

  const expected = crypto
    .createHmac("sha256", Buffer.from(secret, "base64"))
    .update(`${parts.t}.${rawBody}`)
    .digest("hex");

  // constant-time compare
  const a = Buffer.from(expected), b = Buffer.from(parts.v1);
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}

// Express-style receiver (capture the raw body!):
// app.post("/zr", express.raw({ type: "*/*" }), (req, res) => {
//   const eventId = req.header("X-ZenRows-Event-Id");      // dedup on this
//   const sig = req.header("X-Signature");                 // absent => unsigned
//   if (sig && !verifyWebhook(req.body.toString(), sig, SECRETS)) return res.sendStatus(401);
//   if (alreadyHandled(eventId)) return res.sendStatus(200);
//   handle(JSON.parse(req.body.toString()));
//   res.sendStatus(200);
// });
```

```java Java theme={"theme":"css-variables"}
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Base64;

public class VerifyWebhook {
    static boolean verify(String rawBody, String t, String v1, String secretB64) throws Exception {
        if (Math.abs(System.currentTimeMillis() / 1000 - Long.parseLong(t)) > 300) return false; // replay window
        byte[] secret = Base64.getDecoder().decode(secretB64);
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret, "HmacSHA256"));
        byte[] digest = mac.doFinal((t + "." + rawBody).getBytes(StandardCharsets.UTF_8));
        StringBuilder hex = new StringBuilder();
        for (byte x : digest) hex.append(String.format("%02x", x));
        return MessageDigest.isEqual(
            hex.toString().getBytes(StandardCharsets.UTF_8), v1.getBytes(StandardCharsets.UTF_8));
    }
}
```

```php PHP theme={"theme":"css-variables"}
<?php
function verify($rawBody, $t, $v1, $secretB64) {
    if (abs(time() - (int) $t) > 300) return false; // replay window
    $secret = base64_decode($secretB64);
    $expected = hash_hmac('sha256', $t . '.' . $rawBody, $secret);
    return hash_equals($expected, $v1);
}
?>
```

```go Go theme={"theme":"css-variables"}
package main

import (
    "crypto/hmac"
    "crypto/sha256"
    "encoding/base64"
    "encoding/hex"
    "strconv"
    "time"
)

func verify(rawBody, t, v1, secretB64 string) bool {
    ts, err := strconv.ParseInt(t, 10, 64)
    if err != nil {
        return false
    }
    if d := time.Now().Unix() - ts; d > 300 || d < -300 { // replay window
        return false
    }
    secret, err := base64.StdEncoding.DecodeString(secretB64)
    if err != nil {
        return false
    }
    mac := hmac.New(sha256.New, secret)
    mac.Write([]byte(t + "." + rawBody))
    expected := hex.EncodeToString(mac.Sum(nil))
    return hmac.Equal([]byte(expected), []byte(v1))
}
```

```ruby Ruby theme={"theme":"css-variables"}
require 'openssl'
require 'base64'

def verify(raw_body, t, v1, secret_b64)
    return false if (Time.now.to_i - t.to_i).abs > 300 # replay window
    secret = Base64.decode64(secret_b64)
    expected = OpenSSL::HMAC.hexdigest('SHA256', secret, "#{t}.#{raw_body}")
    OpenSSL.secure_compare(expected, v1)
end
```

```bash cURL theme={"theme":"css-variables"}
# Verification happens in your receiver, not in a request. With openssl:
# T and BODY come from the delivery; SECRET_B64 is your base64 key.
# Reject the delivery if T is more than 300 seconds from now (replay window).
now=$(date +%s); [ $(( now > T ? now - T : T - now )) -le 300 ] || echo "stale delivery"
key_hex=$(printf '%s' "$SECRET_B64" | base64 -d | xxd -p -c 256)
printf '%s' "${T}.${BODY}" | openssl dgst -sha256 -mac HMAC -macopt "hexkey:$key_hex"
# Compare the printed hex digest against the v1 value from X-Signature.
```

## 5. Reruns and retrying failures

`POST /jobs/{job_id}/rerun` replays a job as a new run. Add `?status=failed` to re-run only the failures (append `,pending` to also include tasks that never started).

Already-successful tasks carry over, so you only re-scrape, and only pay for, what failed. The response reports `retried_tasks` and `inherited_tasks`.

Every rerun returns `202 Accepted` and writes the new run's tasks in the background: `latest_run.ingest_status` reads `pending` until they're all written, then `done`. Until then, results pages for the new run can be partial, and another rerun or add-tasks call returns `409 run_not_terminal`. Send an `Idempotency-Key` so a retried rerun can't start a second run (see [Idempotency](#idempotency)).

A job runs one run at a time. Start a rerun only after the previous run is `completed`, `stopped`, or `failed`; while it's `pending` or `running`, the API answers `409 run_not_terminal`. A partial rerun that matches no task returns `409 no_matching_tasks`; a scheduled run refused at start has no tasks, so run a full rerun for it.

> [!WARNING]
>
> Partial reruns (filtering by `?status=failed` or `?status=failed,pending`) must start within **10 days** of when the run you're retrying started. That is the job's latest run, not its first. After that, the API returns `409 partial_rerun_window_expired`; start a full rerun instead, which replays every task regardless of previous status.

```python Python theme={"theme":"css-variables"}
## pip install requests
import requests

headers = {'X-API-Key': 'YOUR_ZENROWS_API_KEY'}

# Retry only the failures (drop params for a full rerun):
response = requests.post('https://async.api.zenrows.com/v1/jobs/JOB_ID/rerun',
                        headers=headers, params={'status': 'failed'})
data = response.json()
print('new run', data['latest_run']['run_id'], 'retried', data['retried_tasks'], 'inherited', data['inherited_tasks'])
```

```javascript Node.js theme={"theme":"css-variables"}
// Retry only failures (add ",pending" to also re-run tasks that never started,
// or drop the query for a full rerun that replays every task):
const retry = await api("POST", "/jobs/JOB_ID/rerun", { query: { status: "failed" } });
console.log("new run", retry.latest_run.run_id, "retried", retry.retried_tasks, "inherited", retry.inherited_tasks);
```

```java Java theme={"theme":"css-variables"}
import org.apache.hc.client5.http.fluent.Request;

public class Rerun {
    public static void main(final String... args) throws Exception {
        String key = "YOUR_ZENROWS_API_KEY";

        // Retry only the failures (drop the query string for a full rerun):
        String response = Request.post("https://async.api.zenrows.com/v1/jobs/JOB_ID/rerun?status=failed")
                .addHeader("X-API-Key", key).execute().returnContent().asString();
        System.out.println(response); // includes retried_tasks and inherited_tasks
    }
}
```

```php PHP theme={"theme":"css-variables"}
<?php
$key = 'YOUR_ZENROWS_API_KEY';

// Retry only the failures (drop the query string for a full rerun):
$ch = curl_init('https://async.api.zenrows.com/v1/jobs/JOB_ID/rerun?status=failed');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["X-API-Key: $key"]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
echo curl_exec($ch) . PHP_EOL; // includes retried_tasks and inherited_tasks
curl_close($ch);
?>
```

```go Go theme={"theme":"css-variables"}
package main

import (
    "io"
    "log"
    "net/http"
)

func main() {
    // Retry only the failures (drop the query string for a full rerun).
    req, err := http.NewRequest("POST", "https://async.api.zenrows.com/v1/jobs/JOB_ID/rerun?status=failed", nil)
    if err != nil {
        log.Fatalln(err)
    }
    req.Header.Set("X-API-Key", "YOUR_ZENROWS_API_KEY")
    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        log.Fatalln(err)
    }
    defer resp.Body.Close()
    body, _ := io.ReadAll(resp.Body)
    log.Println(string(body)) // includes retried_tasks and inherited_tasks
}
```

```ruby Ruby theme={"theme":"css-variables"}
# gem install faraday
require 'faraday'

conn = Faraday.new
conn.headers['X-API-Key'] = 'YOUR_ZENROWS_API_KEY'

# Retry only the failures (drop the status param for a full rerun):
res = conn.post('https://async.api.zenrows.com/v1/jobs/JOB_ID/rerun') do |req|
    req.params['status'] = 'failed'
end
print(res.body) # includes retried_tasks and inherited_tasks
```

```bash cURL theme={"theme":"css-variables"}
# Retry only the failures (drop ?status=failed for a full rerun):
curl -X POST "https://async.api.zenrows.com/v1/jobs/JOB_ID/rerun?status=failed" \
  -H "X-API-Key: YOUR_ZENROWS_API_KEY"
```

## 6. Cost

Estimate spend before you submit, and read actual spend after a run.

### Estimate cost

Each task costs the credits of its tier, the same as on Fetch, and the rate card is small and stable, so you can estimate cost on the client with no API call.

* 1 credit (basic request)
* 5 credits (JavaScript rendering)
* 10 credits (premium proxy)
* 25 credits (both)
* a 1 to 25 credit range for `mode=auto`

Sum the tier across your tasks. The estimate assumes each URL succeeds once, so it is a single number unless a task uses `mode=auto`.

> [!NOTE]
>
> The estimate assumes each URL succeeds once, so it is a single number unless a task uses `mode=auto`. For more details on credit costs, see the [Pricing Page](https://docs.zenrows.com/first-steps/pricing.md#cost-multipliers-for-fetch).

```python Python theme={"theme":"css-variables"}
def task_cost(params):
    if str(params.get('mode')) == 'auto':
        return (1, 25)
    js = str(params.get('js_render')) == 'true'
    proxy = str(params.get('premium_proxy')) == 'true'
    c = 25 if js and proxy else 10 if proxy else 5 if js else 1
    return (c, c)

def estimate(body):
    job = body.get('zenrows_params', {})
    lo = hi = 0
    for t in body.get('tasks', []):
        a, b = task_cost({**job, **t.get('zenrows_params', {})})
        lo += a
        hi += b
    return {'tasks': len(body.get('tasks', [])), 'min': lo, 'max': hi, 'exact': lo == hi}
```

```javascript Node.js theme={"theme":"css-variables"}
const TIERS = { base: 1, js: 5, proxy: 10, both: 25 }; // credits per successful request

function taskCost(params = {}) {
  const v = (x) => String(x) === "true";
  if (String(params.mode) === "auto") return { min: 1, max: 25 }; // dynamic
  const js = v(params.js_render), proxy = v(params.premium_proxy);
  const c = js && proxy ? TIERS.both : proxy ? TIERS.proxy : js ? TIERS.js : TIERS.base;
  return { min: c, max: c };
}

function estimate(submitBody) {
  const job = submitBody.zenrows_params ?? {};
  let min = 0, max = 0;
  for (const t of submitBody.tasks ?? []) {
    const { min: a, max: b } = taskCost({ ...job, ...(t.zenrows_params ?? {}) });
    min += a; max += b;
  }
  return { tasks: (submitBody.tasks ?? []).length, min, max, exact: min === max };
}
```

```java Java theme={"theme":"css-variables"}
import java.util.List;
import java.util.Map;

public class Estimate {
    static int[] taskCost(Map<String, String> p) {
        if ("auto".equals(p.get("mode"))) return new int[]{1, 25};
        boolean js = "true".equals(p.get("js_render"));
        boolean proxy = "true".equals(p.get("premium_proxy"));
        int c = js && proxy ? 25 : proxy ? 10 : js ? 5 : 1;
        return new int[]{c, c};
    }

    // Merge job-level and per-task params before calling taskCost for each task,
    // then sum the min and max across all tasks.
    static int[] estimate(List<Map<String, String>> mergedTaskParams) {
        int min = 0, max = 0;
        for (Map<String, String> p : mergedTaskParams) {
            int[] c = taskCost(p);
            min += c[0];
            max += c[1];
        }
        return new int[]{min, max};
    }
}
```

```php PHP theme={"theme":"css-variables"}
<?php
function task_cost($params) {
    if (($params['mode'] ?? '') === 'auto') return [1, 25];
    $js = ($params['js_render'] ?? '') === 'true';
    $proxy = ($params['premium_proxy'] ?? '') === 'true';
    $c = $js && $proxy ? 25 : ($proxy ? 10 : ($js ? 5 : 1));
    return [$c, $c];
}

function estimate($body) {
    $job = $body['zenrows_params'] ?? [];
    $min = 0; $max = 0;
    foreach (($body['tasks'] ?? []) as $t) {
        [$a, $b] = task_cost(array_merge($job, $t['zenrows_params'] ?? []));
        $min += $a; $max += $b;
    }
    return ['tasks' => count($body['tasks'] ?? []), 'min' => $min, 'max' => $max, 'exact' => $min === $max];
}
?>
```

```go Go theme={"theme":"css-variables"}
package main

func taskCost(p map[string]string) (int, int) {
    if p["mode"] == "auto" {
        return 1, 25
    }
    js := p["js_render"] == "true"
    proxy := p["premium_proxy"] == "true"
    switch {
    case js && proxy:
        return 25, 25
    case proxy:
        return 10, 10
    case js:
        return 5, 5
    default:
        return 1, 1
    }
}

// Merge job-level and per-task params before calling taskCost for each task,
// then sum the min and max across all tasks.
func estimate(mergedTaskParams []map[string]string) (int, int) {
    min, max := 0, 0
    for _, p := range mergedTaskParams {
        lo, hi := taskCost(p)
        min += lo
        max += hi
    }
    return min, max
}
```

```ruby Ruby theme={"theme":"css-variables"}
def task_cost(params)
    return [1, 25] if params['mode'].to_s == 'auto'
    js = params['js_render'].to_s == 'true'
    proxy = params['premium_proxy'].to_s == 'true'
    c = js && proxy ? 25 : proxy ? 10 : js ? 5 : 1
    [c, c]
end

def estimate(body)
    job = body['zenrows_params'] || {}
    min = 0; max = 0
    (body['tasks'] || []).each do |t|
        a, b = task_cost(job.merge(t['zenrows_params'] || {}))
        min += a; max += b
    end
    { tasks: (body['tasks'] || []).length, min: min, max: max, exact: min == max }
end
```

```bash cURL theme={"theme":"css-variables"}
# Cost estimation is client-side arithmetic on the rate card, not an API call.
# Tiers (credits per successful request): base=1, js_render=5, premium_proxy=10, both=25, mode=auto=1..25.
# Sum the tier for each task. Example with jq over a submit body in body.json:
jq '[.tasks[] | (.zenrows_params // {}) as $p
      | (if ($p.mode? == "auto") then 25
        elif ($p.js_render? == "true" and $p.premium_proxy? == "true") then 25
        elif ($p.premium_proxy? == "true") then 10
        elif ($p.js_render? == "true") then 5
        else 1 end)] | add' body.json
```

### Check actual cost

Once a run finishes, you can read the credits it actually consumed at two levels:

* **Run total:** the `spend` object on `latest_run.stats`, read from the `GET /jobs/{id}` response shown below.
* **Per task:** `GET /jobs/{id}/tasks/{task_id}/history` (or `GET /jobs/{id}/runs/{run_id}/tasks/{task_id}/history` for an earlier run) lists each attempt with its own `spend` object. Result rows don't carry a `spend` field.

Batch bills at Fetch rates. Successful tasks are billed, and so are tasks that fail because the target answered `404` or `410`, the same as on Fetch. Other failed tasks aren't billed. Because those `404` and `410` tasks show as `failed`, read `stats.spend` rather than counting successes. A task's attempt history shows what each attempt was charged. Treat this figure as an indicative signal. Your Zenrows account statement remains the authoritative record for billing.

```python Python theme={"theme":"css-variables"}
## pip install requests
import requests

job = requests.get('https://async.api.zenrows.com/v1/jobs/JOB_ID',
                  headers={'X-API-Key': 'YOUR_ZENROWS_API_KEY'}).json()
spend = job['latest_run']['stats'].get('spend')
if spend:
    print('credits:', spend['credits'], 'cost:', spend['cost'])
```

```javascript Node.js theme={"theme":"css-variables"}
const job = await api("GET", "/jobs/JOB_ID");
const spend = job.latest_run.stats.spend; // { credits, cost }, absent until there's spend
if (spend) console.log("credits:", spend.credits, "cost:", spend.cost);
```

```java Java theme={"theme":"css-variables"}
import org.apache.hc.client5.http.fluent.Request;

public class ActualCost {
    public static void main(final String... args) throws Exception {
        String response = Request.get("https://async.api.zenrows.com/v1/jobs/JOB_ID")
                .addHeader("X-API-Key", "YOUR_ZENROWS_API_KEY")
                .execute().returnContent().asString();
        System.out.println(response); // read latest_run.stats.spend from this JSON
    }
}
```

```php PHP theme={"theme":"css-variables"}
<?php
$ch = curl_init('https://async.api.zenrows.com/v1/jobs/JOB_ID');
curl_setopt($ch, CURLOPT_HTTPHEADER, ['X-API-Key: YOUR_ZENROWS_API_KEY']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$job = json_decode(curl_exec($ch), true);
curl_close($ch);
$spend = $job['latest_run']['stats']['spend'] ?? null;
if ($spend) echo "credits: {$spend['credits']} cost: {$spend['cost']}" . PHP_EOL;
?>
```

```go Go theme={"theme":"css-variables"}
package main

import (
    "io"
    "log"
    "net/http"
)

func main() {
    req, err := http.NewRequest("GET", "https://async.api.zenrows.com/v1/jobs/JOB_ID", nil)
    if err != nil {
        log.Fatalln(err)
    }
    req.Header.Set("X-API-Key", "YOUR_ZENROWS_API_KEY")
    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        log.Fatalln(err)
    }
    defer resp.Body.Close()
    body, _ := io.ReadAll(resp.Body)
    log.Println(string(body)) // read latest_run.stats.spend from this JSON
}
```

```ruby Ruby theme={"theme":"css-variables"}
# gem install faraday
require 'faraday'
require 'json'

conn = Faraday.new
job = JSON.parse(conn.get('https://async.api.zenrows.com/v1/jobs/JOB_ID') { |req|
    req.headers['X-API-Key'] = 'YOUR_ZENROWS_API_KEY'
}.body)
spend = job.dig('latest_run', 'stats', 'spend')
puts "credits: #{spend['credits']} cost: #{spend['cost']}" if spend
```

```bash cURL theme={"theme":"css-variables"}
# Read latest_run.stats.spend from the job response:
curl "https://async.api.zenrows.com/v1/jobs/JOB_ID" \
  -H "X-API-Key: YOUR_ZENROWS_API_KEY"
```

## 7. Reference

Behaviors and error details that apply across the API.

### Idempotency

Send an `Idempotency-Key` header on a submit (`POST /jobs`), a rerun (`POST /jobs/{job_id}/rerun`) or an add-tasks call (`POST /jobs/{job_id}/tasks`), so a retry can't create a second job or run, or append the same tasks twice. Other routes ignore the header. A key can be up to 128 characters; a longer one returns `400 invalid_argument`. Keys last 24 hours and belong to your account; an add-tasks key also belongs to its job.

* **Same key, same request:** the API replays the original status and body, so a retry after a timeout or a dropped connection is safe. For a rerun, the request is the job and its `?status=` filter.
* **Same key, different request:** the body must match byte for byte, including field order and whitespace. A different body, or a different `?status=` on a rerun, returns `409 idempotency_key_conflict`.
* **Same key while the first attempt is still running:** `409 idempotency_key_conflict`. Retry shortly.
* **A refused submit or rerun doesn't use up the key.** A submit or rerun the API refuses before it creates the job or run, for example with `400`, `409 no_matching_tasks` or `429 quota_exceeded`, leaves the key free: fix the cause and retry with the same key.
* **Add-tasks keeps its key, refused or not.** A retry with the same body is checked again, and a corrected body needs a new key, since the same key with a different body is `409 idempotency_key_conflict`.
* **The credit check runs first.** A retry of a call that succeeded returns `402` if the account has run out of credits since.

On add-tasks, a retry after a call that failed part way, such as a `503` after the tasks were stored or a lost response, finishes that call: the retried tasks keep the same task IDs, so the job gets no duplicate rows and `stats.total` counts each task once.

```python Python theme={"theme":"css-variables"}
## pip install requests
import requests, json

headers = {'X-API-Key': 'YOUR_ZENROWS_API_KEY', 'Content-Type': 'application/json',
          'Idempotency-Key': 'nightly-2026-06-08'}
payload = {'type': 'regular', 'status': 'closed',
          'tasks': [{'url': 'https://www.scrapingcourse.com/ecommerce/'}]}
response = requests.post('https://async.api.zenrows.com/v1/jobs', headers=headers, data=json.dumps(payload))
print(response.status_code, response.json())
```

```javascript Node.js theme={"theme":"css-variables"}
const job = await api("POST", "/jobs", {
  headers: { "Idempotency-Key": "nightly-2026-06-08" },
  body: { type: "regular", status: "closed", tasks: [{ url: "https://www.scrapingcourse.com/ecommerce/" }] },
});
console.log(job.job_id);
```

```java Java theme={"theme":"css-variables"}
import org.apache.hc.client5.http.fluent.Request;
import org.apache.hc.core5.http.ContentType;

public class Idempotent {
    public static void main(final String... args) throws Exception {
        String body = "{\"type\":\"regular\",\"status\":\"closed\",\"tasks\":[{\"url\":\"https://www.scrapingcourse.com/ecommerce/\"}]}";
        String response = Request.post("https://async.api.zenrows.com/v1/jobs")
                .addHeader("X-API-Key", "YOUR_ZENROWS_API_KEY")
                .addHeader("Idempotency-Key", "nightly-2026-06-08")
                .bodyString(body, ContentType.APPLICATION_JSON)
                .execute().returnContent().asString();
        System.out.println(response);
    }
}
```

```php PHP theme={"theme":"css-variables"}
<?php
$ch = curl_init('https://async.api.zenrows.com/v1/jobs');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
    'type' => 'regular', 'status' => 'closed',
    'tasks' => [['url' => 'https://www.scrapingcourse.com/ecommerce/']],
]));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'X-API-Key: YOUR_ZENROWS_API_KEY',
    'Idempotency-Key: nightly-2026-06-08',
    'Content-Type: application/json',
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
echo curl_exec($ch) . PHP_EOL;
curl_close($ch);
?>
```

```go Go theme={"theme":"css-variables"}
package main

import (
    "bytes"
    "io"
    "log"
    "net/http"
)

func main() {
    payload := []byte(`{"type":"regular","status":"closed","tasks":[{"url":"https://www.scrapingcourse.com/ecommerce/"}]}`)
    req, err := http.NewRequest("POST", "https://async.api.zenrows.com/v1/jobs", bytes.NewBuffer(payload))
    if err != nil {
        log.Fatalln(err)
    }
    req.Header.Set("X-API-Key", "YOUR_ZENROWS_API_KEY")
    req.Header.Set("Idempotency-Key", "nightly-2026-06-08")
    req.Header.Set("Content-Type", "application/json")
    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        log.Fatalln(err)
    }
    defer resp.Body.Close()
    body, _ := io.ReadAll(resp.Body)
    log.Println(resp.StatusCode, string(body))
}
```

```ruby Ruby theme={"theme":"css-variables"}
# gem install faraday
require 'faraday'
require 'json'

conn = Faraday.new
res = conn.post('https://async.api.zenrows.com/v1/jobs') do |req|
    req.headers['X-API-Key'] = 'YOUR_ZENROWS_API_KEY'
    req.headers['Idempotency-Key'] = 'nightly-2026-06-08'
    req.headers['Content-Type'] = 'application/json'
    req.body = { type: 'regular', status: 'closed',
                tasks: [{ url: 'https://www.scrapingcourse.com/ecommerce/' }] }.to_json
end
print(res.status)
print(res.body)
```

```bash cURL theme={"theme":"css-variables"}
curl -X POST "https://async.api.zenrows.com/v1/jobs" \
  -H "X-API-Key: YOUR_ZENROWS_API_KEY" \
  -H "Idempotency-Key: nightly-2026-06-08" \
  -H "Content-Type: application/json" \
  -d '{ "type": "regular", "status": "closed", "tasks": [{ "url": "https://www.scrapingcourse.com/ecommerce/" }] }'
```

> [!WARNING]
>
> If you never saw the answer, such as after a timeout or a dropped connection, resend the same body with the same key: you get the original response if the submit went through. A `503` that arrives after the job was created has no stored response, so its retry returns `409 idempotency_key_conflict`. Check whether the job was created by listing your recent jobs, then either use its `job_id` or submit again with a new key. A late `503` can leave a visible job with a `stopped` run, which is safe to `DELETE`.

### Error handling reference

Errors use RFC 9457 problem JSON (`application/problem+json`) with a stable `code` you can branch on, a `title`, a `detail` explaining the case, the HTTP `status`, and a `type` URL that links to the code's entry in [API error codes](https://docs.zenrows.com/api-error-codes.md#batch). A `400` adds `invalid_tasks[]` with `{index, reason, value}` for each bad task. Task-level failures are not HTTP errors; they appear as `failed` rows in the results, each with its own `error` object.

Success codes: `POST /jobs` returns `201 Created`, or `202 Accepted` when the job has 10,000 or more tasks (inline or from a CSV); both carry the same body. Scheduled-job submits return `201`. Every rerun returns `202`. `DELETE` on a job or a run returns `202`. Every response carries an `X-Request-ID` header; include it when you contact support.

| HTTP | `code` | Meaning and fix |
| - | - | - |
| 400 | `invalid_argument` | Validation failed. Read `detail` and `invalid_tasks[]`; for example `url_too_long`, `invalid_external_id`, `unknown_param` or `method_param_conflict`. |
| 400 | `callback_url_must_be_https` / `callback_url_unresolvable` / `webhook_signing_requires_active_key` | The webhook `url` isn't a resolvable `https` URL, or signing was requested before the account has an active HMAC key. |
| 401 | `unauthenticated` / `subscription_inactive` | `unauthenticated`: missing or invalid API key. `subscription_inactive`: the key is valid, but the subscription is past due, unpaid, incomplete or paused; fix it in [Billing](https://app.zenrows.com/billing) (or Azure Marketplace if you subscribed there). |
| 402 | `payment_required` / `api_key_cap_reached` | `payment_required`: no credits available, or the plan doesn't include the API. `api_key_cap_reached`: the API key reached one of its [credit caps](#api-key-credit-caps-and-batch); `detail` names the cap and when it resets. |
| 403 | `permission_denied` | Batch isn't enabled for this account. Contact support. |
| 404 | `not_found` / `file_input_not_found` | Job, run, task, export, webhook or CSV upload missing, deleted, or not owned by your account. |
| 409 | `run_not_terminal` | A rerun while the previous run is `pending` or `running`, or an add-tasks call while the run is still writing its tasks. Wait, or stop the run first. |
| 409 | `idempotency_key_conflict` | The key was reused with a different request, or while the first attempt is still running. See [Idempotency](#idempotency). |
| 409 | `job_not_open` / `last_batch_received` | Adding tasks to a job that's closed, past its first run, or already sent `last_batch: true`. Open a new job. |
| 409 | `run_not_stoppable` | Stop, pause or resume on a run that is `completed`, `failed` or `deleted`. Start a rerun instead. |
| 409 | `no_prior_run` / `no_matching_tasks` / `partial_rerun_window_expired` | The rerun has nothing to replay, the `?status=` filter matched no task, or the partial-rerun window (10 days from when the run you retry started) has passed. Run a full rerun. |
| 409 | `run_has_descendants` | A later partial rerun reuses this run's results. Delete those runs first, or the whole job. |
| 409 | `task_not_ready` | On `/content`: the task is still pending or processing. Poll again. |
| 409 | `conflict` | The action doesn't apply to this job right now; `detail` says why, for example an operation a scheduled job doesn't support. |
| 410 | `result_expired` | On `/content`: the result is past its 14-day retention window; rerun to scrape it again. On an export: the export is more than 12 hours old; start a new one. |
| 422 | (on `/content`) | The task failed; the body is the stored error. |
| 429 | `quota_exceeded` | An account limit; `detail` says which: 3 active jobs (shared with [Crawl](https://docs.zenrows.com/crawl/introduction.md); a job counts until it's deleted, or closed with its latest run ended), 5 scheduled jobs, or 100,000 tasks in one open job. Wait for a run to end, close an open job whose run has ended, or delete a job. Retrying doesn't help. |
| 500 / 503 | `internal` | A server-side failure. Retry with a backoff, with the same `Idempotency-Key` on a submit, rerun or add-tasks call. |

[API error codes](https://docs.zenrows.com/api-error-codes.md#batch) lists every Batch code, including the HMAC and CSV upload ones, with its meaning. On a non-2xx response, read the `code` and, for a `400`, the `invalid_tasks` array from the problem body.

```python Python theme={"theme":"css-variables"}
## pip install requests
import requests

r = requests.post('https://async.api.zenrows.com/v1/jobs',
                  headers={'X-API-Key': 'YOUR_ZENROWS_API_KEY', 'Content-Type': 'application/json'},
                  json={'type': 'regular', 'status': 'closed', 'tasks': [{'url': 'not-a-url'}]})
if not r.ok:
    problem = r.json()  # RFC 7807: { type, title, status, detail, code, invalid_tasks? }
    print(r.status_code, problem.get('code'), problem.get('invalid_tasks'))
```

```javascript Node.js theme={"theme":"css-variables"}
// The api() helper throws an object carrying the structured problem details.
try {
  await api("POST", "/jobs", { body: { type: "regular", status: "closed", tasks: [{ url: "not-a-url" }] } });
} catch (e) {
  console.error(e.status, e.code, e.problem?.invalid_tasks);
}
```

```java Java theme={"theme":"css-variables"}
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.hc.client5.http.fluent.Request;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.io.entity.EntityUtils;

public class ErrorHandling {
    static final ObjectMapper M = new ObjectMapper();

    public static void main(final String... args) throws Exception {
        String body = "{\"type\":\"regular\",\"status\":\"closed\",\"tasks\":[{\"url\":\"not-a-url\"}]}";
        ClassicHttpResponse resp = (ClassicHttpResponse) Request.post("https://async.api.zenrows.com/v1/jobs")
                .addHeader("X-API-Key", "YOUR_ZENROWS_API_KEY")
                .bodyString(body, ContentType.APPLICATION_JSON)
                .execute().returnResponse();
        if (resp.getCode() >= 400) {
            JsonNode problem = M.readTree(EntityUtils.toString(resp.getEntity())); // RFC 7807
            System.out.println(resp.getCode() + " " + problem.path("code").asText() + " " + problem.path("invalid_tasks"));
        }
    }
}
```

```php PHP theme={"theme":"css-variables"}
<?php
$ch = curl_init('https://async.api.zenrows.com/v1/jobs');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['type' => 'regular', 'status' => 'closed', 'tasks' => [['url' => 'not-a-url']]]));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['X-API-Key: YOUR_ZENROWS_API_KEY', 'Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$res = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($status >= 400) {
    $problem = json_decode($res, true); // RFC 7807
    echo $status, ' ', $problem['code'] ?? '', PHP_EOL;
    print_r($problem['invalid_tasks'] ?? []);
}
?>
```

```go Go theme={"theme":"css-variables"}
package main

import (
    "bytes"
    "encoding/json"
    "io"
    "log"
    "net/http"
)

func main() {
    payload := []byte(`{"type":"regular","status":"closed","tasks":[{"url":"not-a-url"}]}`)
    req, _ := http.NewRequest("POST", "https://async.api.zenrows.com/v1/jobs", bytes.NewBuffer(payload))
    req.Header.Set("X-API-Key", "YOUR_ZENROWS_API_KEY")
    req.Header.Set("Content-Type", "application/json")
    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        log.Fatalln(err)
    }
    defer resp.Body.Close()
    body, _ := io.ReadAll(resp.Body)
    if resp.StatusCode >= 400 {
        var problem struct {
            Code         string `json:"code"`
            InvalidTasks []any  `json:"invalid_tasks"`
        }
        json.Unmarshal(body, &problem) // RFC 7807
        log.Println(resp.StatusCode, problem.Code, problem.InvalidTasks)
    }
}
```

```ruby Ruby theme={"theme":"css-variables"}
# gem install faraday
require 'faraday'
require 'json'

res = Faraday.post('https://async.api.zenrows.com/v1/jobs') do |req|
    req.headers['X-API-Key'] = 'YOUR_ZENROWS_API_KEY'
    req.headers['Content-Type'] = 'application/json'
    req.body = { type: 'regular', status: 'closed', tasks: [{ url: 'not-a-url' }] }.to_json
end
unless res.success?
    problem = JSON.parse(res.body) # RFC 7807
    puts "#{res.status} #{problem['code']}"
    p problem['invalid_tasks']
end
```

```bash cURL theme={"theme":"css-variables"}
# -i shows the status line; the body is the RFC 7807 problem with code and invalid_tasks.
curl -i -X POST "https://async.api.zenrows.com/v1/jobs" \
  -H "X-API-Key: YOUR_ZENROWS_API_KEY" -H "Content-Type: application/json" \
  -d '{ "type": "regular", "status": "closed", "tasks": [{ "url": "not-a-url" }] }'
```

## Next steps

* [Troubleshooting](https://docs.zenrows.com/batch/troubleshooting.md): find a symptom and its fix.
* [FAQ](https://docs.zenrows.com/batch/faq.md): access, pricing, limits and scheduling.
* SDKs: [Python](https://docs.zenrows.com/batch/sdk/python.md), [Node.js](https://docs.zenrows.com/batch/sdk/nodejs.md) and [Go](https://docs.zenrows.com/batch/sdk/go.md) wrap every call on this page.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.