> ## 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.

# Examples

> Complete caption, rewrite, batch, history and retry flows

These examples call the live API at `https://api.joip.io` with the [official SDKs](https://docs.joip.io/api-reference/sdks.md). Accepted jobs spend real credits. Use media you have the right and consent to process.

## Caption a batch in one call

Up to ten images per job. `captions()` returns one entry per image, in the order you sent them, so you can zip the results back onto your own records.

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

const joip = new JoipClient({ apiKey: process.env.JOIP_API_KEY });
const urls = [
  "https://joip.com/assets/landing/art-captions.webp",
  "https://cdn.example.com/your-second-image.jpg",
];

const { job, captions } = await joip.captions(
  { media_urls: urls, style: "joi" },
  { idempotencyKey: "album-7-captions" },
);

for (const { index, text, error } of captions) {
  if (text) console.log(urls[index], text);
  else console.warn(urls[index], error.code, error.message);
}
console.log(`${job.state}: ${job.billing.settled_credits} credits`);
```

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

joip = JoipClient(os.environ["JOIP_API_KEY"])
urls = [
    "https://joip.com/assets/landing/art-captions.webp",
    "https://cdn.example.com/your-second-image.jpg",
]

result = joip.captions({"media_urls": urls, "style": "joi"}, idempotency_key="album-7-captions")

for caption in result["captions"]:
    if caption["text"]:
        print(urls[caption["index"]], caption["text"])
    else:
        print(urls[caption["index"]], caption["error"]["code"], caption["error"]["message"])
print(f"{result['job']['state']}: {result['job']['billing']['settled_credits']} credits")
```

A stable `Idempotency-Key` tied to your record (`album-7-captions`) means running the script twice never pays twice: the second run gets the original job back.

## Custom style

Set `style` to `custom` and describe the voice in `custom_instructions` (up to 4,000 characters).

```js theme={"system"}
const { captions } = await joip.captions({
  media_urls: ["https://joip.com/assets/landing/art-captions.webp"],
  style: "custom",
  custom_instructions: "Second person, slow and teasing. Count him down from ten and make him wait for every number.",
});
```

## Rewrite captions

```js JavaScript theme={"system"}
const { captions } = await joip.rewrite({
  items: [{
    media_url: "https://joip.com/assets/landing/art-captions.webp",
    caption: "The original caption",
  }],
  rewrite_mode: "spicier",
});
console.log(captions[0].text);
```

```python Python theme={"system"}
result = joip.rewrite({
    "items": [{
        "media_url": "https://joip.com/assets/landing/art-captions.webp",
        "caption": "The original caption",
    }],
    "rewrite_mode": "spicier",
})
print(result["captions"][0]["text"])
```

Rewrite modes are `improve`, `spicier`, `milder`, `different` and `custom`. See [Captions](https://docs.joip.io/api-reference/captions.md) for every style and media rule.

## Handle a held job

A job held as `needs_review` makes the helpers throw. Store the job ID and stop; never resubmit the same media under a new key.

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

try {
  await joip.captions({ media_urls: urls }, { idempotencyKey: "album-7-captions" });
} catch (error) {
  if (error instanceof JoipJobHeldError) {
    await saveForSupport(error.job.id); // your own storage
  } else if (error instanceof JoipApiError && error.code === "insufficient_credits") {
    console.error("Top up at https://joip.com/credits");
  } else {
    throw error;
  }
}
```

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

try:
    joip.captions({"media_urls": urls}, idempotency_key="album-7-captions")
except JoipJobHeldError as held:
    save_for_support(held.job["id"])  # your own storage
except JoipApiError as error:
    if error.code != "insufficient_credits":
        raise
    print("Top up at https://joip.com/credits")
```

## Submit now, collect later

For a queue worker or a web request that can't wait, submit and store the job ID, then collect it in another process.

```js theme={"system"}
const accepted = await joip.generateCaptions(
  { media_urls: urls, style: "beta" },
  { idempotencyKey: `record-${recordId}-captions` },
);
await saveJobId(recordId, accepted.id);

// Later, anywhere:
const job = await joip.waitForJob(accepted.id); // returns with job.items
for (const item of job.items) console.log(item.index, item.result?.caption_text ?? item.error?.code);
```

## Walk your history

```js theme={"system"}
let spent = 0;
for await (const job of joip.iterJobs({ state: "completed", type: "caption_generation" })) {
  spent += job.billing.settled_credits;
}
console.log(`Completed caption jobs cost ${spent} credits`);
```

The [Generations library](https://joip.com/joip-api?tab=generations) shows the same history in the dashboard.

## Without an SDK

```bash cURL theme={"system"}
export JOIP_API_KEY="joip_live_REPLACE_ME"

curl --fail-with-body https://api.joip.io/v1/captions/generate \
  --header "Authorization: Bearer $JOIP_API_KEY" \
  --header "Content-Type: application/json" \
  --header "Idempotency-Key: album-7-captions" \
  --data '{"media_urls": ["https://joip.com/assets/landing/art-captions.webp"], "style": "joi"}'

curl --fail-with-body "https://api.joip.io/v1/jobs/JOB_ID?include=items" \
  --header "Authorization: Bearer $JOIP_API_KEY"
```

```js fetch theme={"system"}
const response = await fetch("https://api.joip.io/v1/captions/generate", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.JOIP_API_KEY}`,
    "Content-Type": "application/json",
    "Idempotency-Key": "album-7-captions",
  },
  body: JSON.stringify({ media_urls: ["https://joip.com/assets/landing/art-captions.webp"], style: "joi" }),
});
const body = await response.json();
if (!response.ok) throw new Error(`${body.code}: ${body.detail} (${body.request_id})`);
console.log(body.id, response.headers.get("Idempotent-Replayed") === "true" ? "replayed" : "new");
```

## Production retry policy

The SDKs apply the first three rows for you.

| Condition | Action |
| - | - |
| Network failure or timeout after submitting | Retry with the same idempotency key and body |
| `429` | Wait `Retry-After` seconds, then retry |
| `503` | Retry a bounded number of times with backoff and the same idempotency key |
| `409 idempotency_in_progress`, `500`, `502` | Retry shortly with the same key |
| Any other `4xx` | Fix the request, key or account first. [Errors](https://docs.joip.io/api-reference/errors.md) says how for each code |

Record `X-Request-Id` or the problem's `request_id` when diagnosing a failure. Never log Bearer credentials, private media or raw provider payloads.


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