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

# Recipe: carousels

> Create an AI carousel with the API, follow its job, download the PDF, then add, redraw, remove and move slides.

A carousel is a set of slides that LinkedIn shows as a swipeable document. Through the API you create an AI carousel from a prompt (or from your own slide texts), wait for its job, download the PDF, then change slides.

Creating a carousel costs 50 credits, held when you start and charged when the PDF is built. Adding or redrawing a slide costs 10 per slide credits, up to 50 per change, and only for slides that succeed. Removing and moving slides is free.

The flow:

1. Optionally `GET /carousel-templates` to browse the built-in templates.
2. `POST .../carousels` with an `Idempotency-Key`. It answers `202` with a `jobId`.
3. Poll `GET /jobs/{jobId}` or stream `GET /jobs/{jobId}/events` until `done`.
4. `GET .../carousels/{id}` for the slides and a PDF link.
5. `POST .../carousels/{id}/changes` with `ops` to change slides. That is another job.

> [!NOTE]
>
> `GET /carousel-templates` lists the built-in templates (`key`, `name`, `group`, `tone`, `recommendedSlides`, `sizes`, `isPremium` and `locked`). Carousels created through the API are AI artwork carousels: you shape their look with `stylePreset` (`photo`, `editorial_illustration`, `flat_vector`, `3d_clay`, `line_art`, `watercolor`, `isometric`, `minimal`, `bold_poster`, `risograph`, `paper_cut`, `blueprint`), `size` and `useBrandKit`. The create call does not take a template key.

## Create options

| Field | Meaning |
| - | - |
| `prompt` | What the carousel is about. Up to 50,000 characters. |
| `slides` | Your own texts, one per slide, instead of a prompt. Needs at least 2. When you send them, the slides use your text as written. |
| `slideCount` | 3 to 12, default 8. Used when you send a `prompt`. |
| `size` | `portrait` (default, 1080 by 1350) or `square`. |
| `stylePreset` | One of the presets above, or `null`. |
| `references` | Up to 20 uploaded pictures: objects with an `objectId` (UUID) and a `role` of `style`, `subject` or `logo`. |
| `useBrandKit` | `true` applies the workspace brand kit. |

Send `prompt` or `slides`. Only one carousel can be drawn at a time in an organization: a second create while one runs answers `409 carousel_in_progress`.

## The script

```javascript JavaScript
import { randomUUID } from "node:crypto";

const BASE = process.env.POSTCHAMP_BASE_URL ?? "https://api.postchampai.com";
const KEY = process.env.POSTCHAMP_API_KEY;
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

async function api(method, path, { body, idempotencyKey, tries = 4 } = {}) {
  for (let attempt = 1; ; attempt++) {
    let res;
    try {
      res = await fetch(`${BASE}/api/v1${path}`, {
        method,
        headers: {
          "x-api-key": KEY,
          ...(body ? { "Content-Type": "application/json" } : {}),
          ...(idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {}),
        },
        body: body ? JSON.stringify(body) : undefined,
      });
    } catch (err) {
      if (attempt >= tries) throw err;
      await sleep(1000 * attempt);
      continue;
    }
    const json = await res.json();
    if (res.ok) return json;
    const retryable = res.status === 429 || res.status >= 500 ||
      (res.status === 409 && json.error?.details?.reason === "request_in_progress");
    if (retryable && attempt < tries) {
      await sleep((Number(res.headers.get("Retry-After")) || 2 * attempt) * 1000);
      continue;
    }
    const e = new Error(`${res.status} ${json.error?.code}: ${json.error?.message}`);
    e.code = json.error?.code;
    e.requestId = res.headers.get("X-Request-Id");
    throw e;
  }
}

async function waitForJob(jobId, { intervalMs = 3000, timeoutMs = 10 * 60_000 } = {}) {
  const started = Date.now();
  while (Date.now() - started < timeoutMs) {
    const job = await api("GET", `/jobs/${jobId}`);
    if (job.status === "done") return job;
    if (job.status === "failed") throw new Error(job.message ?? "The job failed");
    await sleep(intervalMs);
  }
  throw new Error("Timed out waiting for the job");
}

async function main() {
  const { workspaces } = await api("GET", "/key");
  const ws = (workspaces.find((w) => w.isMain) ?? workspaces[0]).id;

  // 1. Create. The idempotency key makes a retry return the same carousel.
  const started = await api("POST", `/workspaces/${ws}/carousels`, {
    idempotencyKey: randomUUID(),
    body: {
      prompt: "5 habits of founders who ship weekly",
      slideCount: 6,
      size: "portrait",
      stylePreset: "flat_vector",
    },
  });
  console.log("Queued", started.id, started.jobId);

  // 2. Wait for the PDF. (Or stream: see "Jobs and streaming".)
  await waitForJob(started.jobId);

  // 3. Read it.
  const carousel = await api("GET", `/workspaces/${ws}/carousels/${started.id}`);
  console.log(`${carousel.slides.length} slides, PDF: ${carousel.pdfUrl}`);
  console.log(`The link expires at ${carousel.pdfUrlExpiresAt}`); // about 5 minutes: download now

  // 4. Change it: redraw slide 2, add one at position 3, move the first slide to the end.
  const [first, second] = carousel.slides;
  const change = await api("POST", `/workspaces/${ws}/carousels/${carousel.id}/changes`, {
    idempotencyKey: randomUUID(),
    body: {
      expectedRevision: carousel.revision, // refuse if someone else changed it meanwhile
      ops: [
        { op: "redraw", slideId: second.id, instruction: "Use a bolder headline" },
        { op: "add", prompt: "Habit 6: write it down", position: 3 },
        { op: "move", slideId: first.id, toPosition: carousel.slides.length },
      ],
    },
  });
  console.log(`Change queued: ${change.paidSlides} slides to pay for`);
  await waitForJob(change.jobId);

  const updated = await api("GET", `/workspaces/${ws}/carousels/${carousel.id}`);
  console.log(`Now ${updated.slides.length} slides at revision ${updated.revision}`);
}

main().catch((err) => {
  if (err.code === "carousel_in_progress") console.error("Another carousel is being drawn. Try again soon.");
  else if (err.code === "insufficient_credits") console.error("Not enough credits.");
  else console.error(err.message, err.requestId ? `(request ${err.requestId})` : "");
  process.exit(1);
});
```

```python Python
import os
import time
import uuid

import requests

BASE = os.environ.get("POSTCHAMP_BASE_URL", "https://api.postchampai.com")
KEY = os.environ["POSTCHAMP_API_KEY"]


class ApiError(Exception):
    def __init__(self, status, body, request_id):
        error = (body or {}).get("error", {})
        super().__init__(f"{status} {error.get('code')}: {error.get('message')}")
        self.code = error.get("code")
        self.request_id = request_id


def api(method, path, body=None, idempotency_key=None, tries=4):
    headers = {"x-api-key": KEY}
    if idempotency_key:
        headers["Idempotency-Key"] = idempotency_key
    for attempt in range(1, tries + 1):
        try:
            res = requests.request(method, f"{BASE}/api/v1{path}", headers=headers, json=body, timeout=60)
        except requests.RequestException:
            if attempt == tries:
                raise
            time.sleep(attempt)
            continue
        data = res.json()
        if res.ok:
            return data
        reason = (data.get("error", {}).get("details") or {}).get("reason")
        retryable = res.status_code in (429, 500, 502, 503) or (
            res.status_code == 409 and reason == "request_in_progress"
        )
        if retryable and attempt < tries:
            time.sleep(int(res.headers.get("Retry-After", 2 * attempt)))
            continue
        raise ApiError(res.status_code, data, res.headers.get("X-Request-Id"))


def wait_for_job(job_id, interval=3, timeout=600):
    deadline = time.time() + timeout
    while time.time() < deadline:
        job = api("GET", f"/jobs/{job_id}")
        if job["status"] == "done":
            return job
        if job["status"] == "failed":
            raise RuntimeError(job.get("message", "The job failed"))
        time.sleep(interval)
    raise TimeoutError("Timed out waiting for the job")


def main():
    workspaces = api("GET", "/key")["workspaces"]
    ws = next((w for w in workspaces if w["isMain"]), workspaces[0])["id"]

    # 1. Create. The idempotency key makes a retry return the same carousel.
    started = api(
        "POST",
        f"/workspaces/{ws}/carousels",
        idempotency_key=str(uuid.uuid4()),
        body={
            "prompt": "5 habits of founders who ship weekly",
            "slideCount": 6,
            "size": "portrait",
            "stylePreset": "flat_vector",
        },
    )
    print("Queued", started["id"], started["jobId"])

    # 2. Wait for the PDF.
    wait_for_job(started["jobId"])

    # 3. Read it.
    carousel = api("GET", f"/workspaces/{ws}/carousels/{started['id']}")
    print(f"{len(carousel['slides'])} slides, PDF: {carousel['pdfUrl']}")
    print("The link expires at", carousel["pdfUrlExpiresAt"])  # about 5 minutes: download now

    # 4. Change it: redraw slide 2, add one at position 3, move the first slide to the end.
    first, second = carousel["slides"][0], carousel["slides"][1]
    change = api(
        "POST",
        f"/workspaces/{ws}/carousels/{carousel['id']}/changes",
        idempotency_key=str(uuid.uuid4()),
        body={
            "expectedRevision": carousel["revision"],  # refuse if someone else changed it meanwhile
            "ops": [
                {"op": "redraw", "slideId": second["id"], "instruction": "Use a bolder headline"},
                {"op": "add", "prompt": "Habit 6: write it down", "position": 3},
                {"op": "move", "slideId": first["id"], "toPosition": len(carousel["slides"])},
            ],
        },
    )
    print("Change queued:", change["paidSlides"], "slides to pay for")
    wait_for_job(change["jobId"])

    updated = api("GET", f"/workspaces/{ws}/carousels/{carousel['id']}")
    print(f"Now {len(updated['slides'])} slides at revision {updated['revision']}")


if __name__ == "__main__":
    try:
        main()
    except ApiError as err:
        raise SystemExit(f"{err} (request {err.request_id})")
```

```bash curl
export BASE=https://api.postchampai.com/api/v1
export H_KEY="x-api-key: $POSTCHAMP_API_KEY"
WS=$(curl -s $BASE/key -H "$H_KEY" | jq -r '.workspaces[] | select(.isMain) | .id')

# 1. Create (202)
curl -s -X POST $BASE/workspaces/$WS/carousels \
  -H "$H_KEY" -H "Content-Type: application/json" -H "Idempotency-Key: $(uuidgen)" \
  -d '{"prompt": "5 habits of founders who ship weekly", "slideCount": 6, "stylePreset": "flat_vector"}' > started.json
ID=$(jq -r .id started.json); JOB=$(jq -r .jobId started.json)

# 2. Poll the job until status is done or failed
curl -s $BASE/jobs/$JOB -H "$H_KEY"
# or stream it:
# curl -N $BASE/jobs/$JOB/events -H "$H_KEY"

# 3. Read the carousel (slides, pdfUrl valid about 5 minutes)
curl -s $BASE/workspaces/$WS/carousels/$ID -H "$H_KEY" > carousel.json
SLIDE=$(jq -r '.slides[1].id' carousel.json)

# 4. Change it (202, new jobId)
curl -s -X POST $BASE/workspaces/$WS/carousels/$ID/changes \
  -H "$H_KEY" -H "Content-Type: application/json" -H "Idempotency-Key: $(uuidgen)" \
  -d "{\"ops\": [{\"op\": \"redraw\", \"slideId\": \"$SLIDE\", \"instruction\": \"Use a bolder headline\"}, {\"op\": \"add\", \"prompt\": \"Habit 6: write it down\", \"position\": 3}]}"
```

## The carousel

`GET .../carousels/{id}` returns:

```json
{
  "id": "4cbd208e-358a-54d6-ae41-7e1d253b8a2c",
  "kind": "ai_artwork",
  "title": "Placeholder text",
  "size": "portrait",
  "width": 1080,
  "height": 1350,
  "status": "ready",
  "progress": 100,
  "revision": 0,
  "slideCount": 3,
  "error": null,
  "hasPdf": true,
  "jobId": "carousel-build:4cbd208e-358a-54d6-ae41-7e1d253b8a2c:0",
  "slides": [
    {
      "id": "0adac3e5-1750-4471-af5f-40628a7f19db",
      "position": 0,
      "prompt": "Hook: ship weekly",
      "status": "ready",
      "url": "https://...presigned image url...",
      "drawing": false,
      "lastError": null
    }
  ],
  "pdfUrl": "https://...presigned pdf url...",
  "pdfUrlExpiresAt": "2026-12-05T11:26:22.567Z"
}
```

The answer is shortened. `status` is `ready` when the PDF is built and `failed` when the build failed (`error` says why). `pdfUrl` and each slide `url` are presigned links that expire, the PDF link after about 5 minutes. Read the carousel again for a fresh link. `pdfUrl` is `null` until a PDF exists.

## Change operations

`ops` takes 1 to 40 operations per change:

| `op` | Fields | Cost |
| - | - | - |
| `add` | `prompt`, optional `position` (0-based) | 10 per slide credits |
| `redraw` | `slideId`, optional `instruction`, optional `referenceObjectIds` (up to 3) | 10 per slide credits |
| `remove` | `slideId` | Free |
| `move` | `slideId`, `toPosition` | Free |

A change answers `202` with `id`, `jobId` (it ends with the new revision), `revision`, the accepted `ops`, `paidSlides` and `upTo`. Credits are charged only for slides that succeed. `expectedRevision` is optional: with it, a carousel that changed since you read it answers `409 conflict` with `reason: "carousel_changed"`.

## Errors and retries

* **A failed job.** The job's `message` says why, and the hold is released ("You weren't charged"). Create the carousel again with a **new** `Idempotency-Key`: the old key replays the failed carousel.
* **`409 carousel_in_progress`.** Wait for the running carousel's job, then try again.
* **`409 carousel_locked`.** The carousel is on a post waiting for approval. Changes are paused.
* **`409 conflict` with `already_done`.** The change was already made. Read the carousel.
* **A lost response.** Retry with the same key: you get the same carousel id and `Idempotent-Replayed: true`.

See [Errors](/api/errors.md) for the full list.

> [card] [Jobs and streaming](/api/jobs-and-streaming.md)
>
> Stream a job instead of polling.

> [card] [Infographics](/api/recipes/infographics.md)
>
> Another long job.
