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

# SDKs

> Official zero-dependency JavaScript and Python clients, version 0.2.0

Joip publishes two small, auditable clients for the live Captions API v1. Each is one file with no dependencies: download it, read it, and pin it in your repository. Both cover every v1 operation and add what a production integration needs: automatic retries, timeouts, paginators, one-call caption helpers, rate-limit info and structured errors. Both talk to `https://api.joip.io`; pass `baseUrl` (`base_url` in Python) only for controlled testing.

> [!WARNING]
>
> Server-side only. The files are source distributions, not browser bundles or registry packages. Load `JOIP_API_KEY` from server-side secret storage and never import a client into code that runs in a browser or mobile app.

> [card] [JavaScript SDK](https://app.joip.io/sdk/joip.js)
>
> ESM for Node.js 22 and compatible server runtimes.

> [card] [TypeScript types](https://app.joip.io/sdk/joip.d.ts)
>
> Complete declarations for joip.js. Save beside it.

> [card] [Python SDK](https://app.joip.io/sdk/joip.py)
>
> Standard library only, Python 3.9 and newer.

## Install

```bash JavaScript theme={"system"}
mkdir -p vendor/joip
curl --fail --silent --show-error --output vendor/joip/joip.js https://app.joip.io/sdk/joip.js
# Optional, for TypeScript and editor hints:
curl --fail --silent --show-error --output vendor/joip/joip.d.ts https://app.joip.io/sdk/joip.d.ts
```

```bash Python theme={"system"}
mkdir -p vendor/joip
curl --fail --silent --show-error --output vendor/joip/joip.py https://app.joip.io/sdk/joip.py
```

## Caption in one call

`captions()` and `rewrite()` submit the job, wait for it, and return `{ job, captions }`. `captions` has one `{ index, text, error }` per input, in input order: `text` is the caption, or `null` with an `error` when that image failed.

```js JavaScript theme={"system"}
import { JoipClient, JoipJobHeldError } from "./vendor/joip/joip.js";

const joip = new JoipClient({ apiKey: process.env.JOIP_API_KEY });

try {
  const { job, captions } = await joip.captions({
    media_urls: ["https://joip.com/assets/landing/art-captions.webp"],
    style: "joi",
  });
  for (const caption of captions) console.log(caption.index, caption.text ?? caption.error.code);
  console.log(`Cost ${job.billing.settled_credits} credits`);

  const rewritten = await joip.rewrite({
    items: [{ media_url: "https://joip.com/assets/landing/art-captions.webp", caption: captions[0].text }],
    rewrite_mode: "spicier",
  });
  console.log(rewritten.captions[0].text);
} catch (error) {
  if (error instanceof JoipJobHeldError) console.error(`Held for review: ${error.job.id}`);
  else throw error;
}
```

```python Python theme={"system"}
import os
from vendor.joip.joip import JoipClient, JoipJobHeldError

joip = JoipClient(os.environ["JOIP_API_KEY"])

try:
    result = joip.captions({
        "media_urls": ["https://joip.com/assets/landing/art-captions.webp"],
        "style": "joi",
    })
    for caption in result["captions"]:
        print(caption["index"], caption["text"] or caption["error"]["code"])
    print(f"Cost {result['job']['billing']['settled_credits']} credits")

    rewritten = joip.rewrite({
        "items": [{"media_url": "https://joip.com/assets/landing/art-captions.webp", "caption": result["captions"][0]["text"]}],
        "rewrite_mode": "spicier",
    })
    print(rewritten["captions"][0]["text"])
except JoipJobHeldError as held:
    print(f"Held for review: {held.job['id']}")
```

Pass a list of URLs instead of a body for the default `joi` style: `joip.captions([url1, url2])`. A helper throws `JoipJobHeldError` when the job reaches `needs_review`; the error carries `job` and the partial `captions`. Keep the job ID and never resubmit it under a new key.

Each helper generates one `Idempotency-Key` for its submission. Pass `idempotencyKey` (`idempotency_key` in Python) to tie it to your own record, so a retried call can never pay twice. The JavaScript helpers take `wait: { timeoutMs, intervalMs, maxIntervalMs }`; the Python helpers take `wait_timeout` in seconds.

## Retries and timeouts

Every request retries automatically on `429`, `503`, timeouts and network failures, up to `maxRetries` times (default 2). A `Retry-After` header is honoured exactly; without one the client backs off exponentially with jitter from 0.5 seconds. Other `4xx` responses are never retried.

A retried job submission is always safe: the client sends the same `Idempotency-Key` on every attempt, so Joip returns the original job instead of creating a second one.

```js JavaScript theme={"system"}
const joip = new JoipClient({
  apiKey: process.env.JOIP_API_KEY,
  maxRetries: 4,          // 0 turns automatic retries off
  timeoutMs: 15_000,      // per attempt; default 30000
  maxRetryDelayMs: 10_000 // a longer Retry-After is thrown instead of waited
});

// Per request, and with your own AbortSignal:
await joip.credits({ maxRetries: 0, timeoutMs: 5_000, signal: AbortSignal.timeout(8_000) });
```

```python Python theme={"system"}
joip = JoipClient(
    os.environ["JOIP_API_KEY"],
    max_retries=4,        # 0 turns automatic retries off
    timeout=15,           # seconds per attempt; default 30
    max_retry_delay=10,   # a longer Retry-After is raised instead of waited
)

joip.credits(timeout=5)
```

A `Retry-After` longer than `maxRetryDelayMs` (default 30 seconds) is thrown straight away rather than slept on, so an hourly [admission limit](https://docs.joip.io/api-reference/pagination-and-rate-limits.md#job-admission) never blocks your process. Catch it and schedule the retry yourself.

## Paginators

The iterators follow `next_cursor` for you, 100 resources per page.

```js JavaScript theme={"system"}
for await (const job of joip.iterJobs({ state: "failed", type: "caption_generation" })) {
  console.log(job.id, job.error?.code);
}
for await (const item of joip.iterJobItems(jobId)) console.log(item.index, item.state);
for await (const price of joip.iterPricing()) console.log(price.feature_key, price.credits_per_unit);
```

```python Python theme={"system"}
for job in joip.iter_jobs(state="failed", type="caption_generation"):
    print(job["id"], (job.get("error") or {}).get("code"))
for item in joip.iter_job_items(job_id):
    print(item["index"], item["state"])
for price in joip.iter_pricing():
    print(price["feature_key"], price["credits_per_unit"])
```

## Polling

`waitForJob` and `wait_for_job` poll from one second, backing off to five, until the job is terminal or held. They return the job with its `items` included (pass `includeItems: false` / `include_items=False` to skip them). A `needs_review` job is returned at once, because reconciling an ambiguous provider outcome takes far longer than a polling loop; check `state` before reading results. Past `timeoutMs` (default two minutes) they throw `JoipTimeoutError`.

```js theme={"system"}
const accepted = await joip.generateCaptions({ media_urls: [url] }, { idempotencyKey: "record-42" });
const job = await joip.waitForJob(accepted.id, { timeoutMs: 300_000 });
if (job.state === "needs_review") throw new Error(`Joip job ${job.id} is held for review`);
console.log(job.items[0].result?.caption_text);
```

## Errors, replays and rate limits

Every non-2xx response throws `JoipApiError` (Python raises it). It carries:

| Field (JS / Python) | Meaning |
| - | - |
| `status` | The HTTP status. |
| `code` | The stable [error code](https://docs.joip.io/api-reference/errors.md). Branch on this. |
| `param` | The field, parameter or header at fault, or null. |
| `requestId` / `request_id` | Joip's request ID. Log it and quote it to support. |
| `retryAfter` / `retry_after` | `Retry-After` as a number of seconds, or null. |
| `retryable` | True when the same request can succeed later unchanged. |

`retryable` follows the error catalog. The client already retried `429` and `503` before throwing; retry `idempotency_in_progress`, `internal_error` and the `502` codes yourself with the same key.

All errors the SDK throws on purpose extend `JoipError`: `JoipApiError`, `JoipTimeoutError` and `JoipJobHeldError`.

The client also keeps what the last response said:

```js JavaScript theme={"system"}
const accepted = await joip.generateCaptions(body, { idempotencyKey: "record-42" });
accepted.replayed;          // true when Joip answered from an earlier acceptance with this key
joip.rateLimit;             // { limit: 120, remaining: 117, reset: 41 }
joip.lastResponse.requestId;
```

```python Python theme={"system"}
accepted = joip.generate_captions(body, idempotency_key="record-42")
accepted.replayed           # True when Joip answered from an earlier acceptance with this key
joip.rate_limit             # {"limit": 120, "remaining": 117, "reset": 41}
joip.last_response["request_id"]
```

In JavaScript `replayed` is non-enumerable, so it never ends up in `JSON.stringify`. In Python every response is a `dict` subclass with `status`, `request_id`, `replayed` and `rate_limit` attributes.

## Every method

| JavaScript | Python | Calls |
| - | - | - |
| `status()` | `status()` | `GET /status` |
| `account()` | `account()` | `GET /v1/account` |
| `credits()` | `credits()` | `GET /v1/credits` |
| `pricing({ limit, cursor })` | `pricing(limit, cursor)` | `GET /v1/pricing` |
| `jobs({ limit, cursor, state, type })` | `jobs(limit, cursor, state, type)` | `GET /v1/jobs` |
| `job(id, { includeItems })` | `job(id, include_items)` | `GET /v1/jobs/{job_id}` |
| `jobItems(id, { limit, cursor })` | `job_items(id, limit, cursor)` | `GET /v1/jobs/{job_id}/items` |
| `generateCaptions(body, { idempotencyKey })` | `generate_captions(body, idempotency_key)` | `POST /v1/captions/generate` |
| `rewriteCaptions(body, { idempotencyKey })` | `rewrite_captions(body, idempotency_key)` | `POST /v1/captions/rewrite` |
| `iterJobs`, `iterJobItems`, `iterPricing` | `iter_jobs`, `iter_job_items`, `iter_pricing` | Every page of a list |
| `waitForJob(id, options)` | `wait_for_job(id, ...)` | Polls `GET /v1/jobs/{job_id}?include=items` |
| `captions(body)`, `rewrite(body)` | `captions(body)`, `rewrite(body)` | Submit, wait and collect |

Every JavaScript request method also takes `signal`, `timeoutMs` and `maxRetries`; every Python request method takes `timeout` in seconds.

## Versioning and verification

The file header and `VERSION` (`__version__` in Python) name the SDK version; requests send `User-Agent: joip-js/0.2.0` or `joip-python/0.2.0`. Pin a reviewed copy and commit it, or its checksum, so a client change is always explicit. Joip keeps the v1 wire contract stable: a breaking change gets a new versioned route, never a silent SDK change.

```bash Verify the downloaded file theme={"system"}
sha256sum vendor/joip/joip.js vendor/joip/joip.d.ts vendor/joip/joip.py
```

Version 0.2.0 is a drop-in upgrade from 0.1. Two values changed type: `retryAfter` / `retry_after` is now a number of seconds instead of the raw header string, and `waitForJob` now backs off and includes items by default.

> [!NOTE]
>
> Joip doesn't publish registry packages. The files above are the official clients; packages named like Joip on npm or PyPI aren't endorsed.


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