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

# Jobs and streaming

> Follow carousel and infographic jobs by polling or server-sent events, and stream a post as it is written.

Some work takes longer than one request: drawing a carousel, rendering an infographic. Those calls answer `202 Accepted` right away with a job. You follow the job, then read the result.

Post generation is different. It answers in the same request, and you can ask for a stream of the text as it is written.

## Start a job

Carousel and infographic creation and changes answer `202`:

```json
{
  "id": "c0386bc8-2b65-5563-99d1-0c087eb7e95e",
  "carouselId": "c0386bc8-2b65-5563-99d1-0c087eb7e95e",
  "jobId": "carousel-build:c0386bc8-2b65-5563-99d1-0c087eb7e95e:0",
  "status": "queued"
}
```

Use `jobId` exactly as given. It contains colons, which are valid in the path. Carousel changes answer a new `jobId` that ends in the new revision number (`...:1`). Infographics answer `infographic:<versionId>`.

Credits are held when you start the job and charged when it finishes. If the job fails, the hold is released.

## Read a job

`GET /api/v1/jobs/{jobId}` returns the last known state.

```bash
curl https://api.postchampai.com/api/v1/jobs/carousel-build:4cbd208e-358a-54d6-ae41-7e1d253b8a2c:0 \
  -H "x-api-key: $POSTCHAMP_API_KEY"
```

```json Response 200
{
  "jobRef": "carousel-build:4cbd208e-358a-54d6-ae41-7e1d253b8a2c:0",
  "status": "done",
  "at": "2026-12-05T11:20:52.202Z",
  "percent": 100,
  "result": { "carouselId": "4cbd208e-358a-54d6-ae41-7e1d253b8a2c", "pages": 3, "postsUpdated": 0 }
}
```

| Field | Meaning |
| - | - |
| `jobRef` | The job id. |
| `status` | `queued`, `running`, `progress`, `done` or `failed`. `done` and `failed` are final. |
| `percent` | 0 to 100, when known. |
| `message` | A short human-readable note, such as "Planning the slides". On `failed`, the reason. |
| `result` | On `done`: the ids to read next. Carousels: `carouselId`, `pages`. Infographics: `infographicId`, `versionId`. |
| `at` | When this state was set. |

A job nobody has reported on yet answers `{ "jobRef": "...", "status": "queued" }`. Job state is kept for 24 hours. A job id that does not exist, or that belongs to a workspace your key cannot reach, answers `404 not_found` ("Job not found.").

A failed job looks like this:

```json
{
  "jobRef": "carousel-build:c0386bc8-2b65-5563-99d1-0c087eb7e95e:0",
  "status": "failed",
  "message": "We couldn't plan the slides. You weren't charged. Try again.",
  "at": "2026-12-05T11:20:29.060Z"
}
```

### Poll

Poll every 2 to 5 seconds. Each poll counts toward your [rate limits](/api/rate-limits.md), so prefer the stream for long jobs.

```javascript JavaScript
async function waitForJob(jobId, { intervalMs = 3000, timeoutMs = 10 * 60_000 } = {}) {
  const started = Date.now();
  while (Date.now() - started < timeoutMs) {
    const res = await fetch(`https://api.postchampai.com/api/v1/jobs/${jobId}`, {
      headers: { "x-api-key": process.env.POSTCHAMP_API_KEY },
    });
    if (res.status === 429) {
      await new Promise((r) => setTimeout(r, (Number(res.headers.get("Retry-After")) || 5) * 1000));
      continue;
    }
    if (!res.ok) throw new Error(`${res.status} ${(await res.json()).error.code}`);
    const job = await res.json();
    if (job.status === "done") return job;
    if (job.status === "failed") throw new Error(job.message ?? "Job failed");
    await new Promise((r) => setTimeout(r, intervalMs));
  }
  throw new Error("Timed out waiting for the job");
}
```

```python Python
import os, time, requests

def wait_for_job(job_id, interval=3, timeout=600):
    deadline = time.time() + timeout
    while time.time() < deadline:
        res = requests.get(
            f"https://api.postchampai.com/api/v1/jobs/{job_id}",
            headers={"x-api-key": os.environ["POSTCHAMP_API_KEY"]},
        )
        if res.status_code == 429:
            time.sleep(int(res.headers.get("Retry-After", 5)))
            continue
        res.raise_for_status()
        job = res.json()
        if job["status"] == "done":
            return job
        if job["status"] == "failed":
            raise RuntimeError(job.get("message", "Job failed"))
        time.sleep(interval)
    raise TimeoutError("Timed out waiting for the job")
```

## Stream a job

`GET /api/v1/jobs/{jobId}/events` is a server-sent events stream (`Content-Type: text/event-stream`).

```bash
curl -N https://api.postchampai.com/api/v1/jobs/carousel-build:c0386bc8-2b65-5563-99d1-0c087eb7e95e:0/events \
  -H "x-api-key: $POSTCHAMP_API_KEY"
```

```text
data: {"jobRef":"carousel-build:c0386bc8-2b65-5563-99d1-0c087eb7e95e:0","status":"running","at":"2026-12-05T11:20:18.950Z","message":"Planning the slides"}
id: 1796469618950

data: {"jobRef":"carousel-build:c0386bc8-2b65-5563-99d1-0c087eb7e95e:0","status":"failed","message":"We couldn't plan the slides. You weren't charged. Try again.","at":"2026-12-05T11:20:29.060Z"}
id: 1796469629060
```

How it behaves:

* The **first event is the last known state**, so you never miss where the job is. Then each update follows.
* Every event is an unnamed `message` event. `data` is the same JSON as the job read above. `id` is the event time in milliseconds.
* The stream ends after the first `done` or `failed` event.
* A `: keep-alive` comment arrives every 15 seconds so proxies keep the connection open. Ignore comment lines.
* The server closes the stream after 10 minutes. To resume, open it again. You get the last state first, which is all you need.
* A key that is revoked or expires while a stream is open ends the stream within one keep-alive.
* A key can hold a limited number of streams at once. Over it you get `429 rate_limited` with `Retry-After: 5`.

```javascript JavaScript
// fetch-based SSE reader: EventSource cannot send the x-api-key header
async function streamJob(jobId, onEvent) {
  for (;;) {
    const res = await fetch(`https://api.postchampai.com/api/v1/jobs/${jobId}/events`, {
      headers: { "x-api-key": process.env.POSTCHAMP_API_KEY, Accept: "text/event-stream" },
    });
    if (!res.ok) throw new Error(`${res.status} ${(await res.json()).error.code}`);

    const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
    let buffer = "";
    for (;;) {
      const { value, done } = await reader.read();
      if (done) break; // closed after 10 minutes: reconnect below
      buffer += value;
      let sep;
      while ((sep = buffer.indexOf("\n\n")) !== -1) {
        const block = buffer.slice(0, sep);
        buffer = buffer.slice(sep + 2);
        const data = block.split("\n").filter((l) => l.startsWith("data:")).map((l) => l.slice(5).trim()).join("\n");
        if (!data) continue; // keep-alive comment
        const event = JSON.parse(data);
        onEvent(event);
        if (event.status === "done" || event.status === "failed") return event;
      }
    }
  }
}
```

```python Python
import json, os, requests

def stream_job(job_id, on_event):
    while True:
        with requests.get(
            f"https://api.postchampai.com/api/v1/jobs/{job_id}/events",
            headers={"x-api-key": os.environ["POSTCHAMP_API_KEY"], "Accept": "text/event-stream"},
            stream=True,
            timeout=(10, 60),  # keep-alive arrives every 15 s
        ) as res:
            res.raise_for_status()
            for line in res.iter_lines(decode_unicode=True):
                if not line or not line.startswith("data:"):
                    continue  # blank separator, id: line or keep-alive comment
                event = json.loads(line[5:].strip())
                on_event(event)
                if event["status"] in ("done", "failed"):
                    return event
        # the server closed the stream after 10 minutes: loop to reconnect
```

## Stream a post generation

`POST /api/v1/workspaces/{workspaceId}/posts/generate` (and `generate-batch`) normally answers one JSON body when all versions are written. Send `Accept: text/event-stream` to receive the text as it is written. The request body, credits and `Idempotency-Key` rules are the same.

```bash
curl -N -X POST "https://api.postchampai.com/api/v1/workspaces/$WS/posts/generate" \
  -H "x-api-key: $POSTCHAMP_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Accept: text/event-stream" \
  -H "Idempotency-Key: docs-gen-sse-001" \
  -d '{"prompt": "Three lessons from my first year of freelancing", "versions": 1}'
```

```text
data: {"type":"started","generationGroupId":"7afcdf40-9a89-429a-bf90-4d5e33eeea41","versions":1}

data: {"type":"version_delta","index":0,"text":"This is placeholder text from the test "}

data: {"type":"version_delta","index":0,"text":"model."}

data: {"type":"version_done","index":0,"postId":"66d5daaf-4f21-4d45-9ff3-217b5978f108","text":"This is placeholder text from the test model.","charCount":45}

data: {"type":"done","postIds":["66d5daaf-4f21-4d45-9ff3-217b5978f108"],"creditsLeft":7740}

data: {"type":"result","result":{"status":"done","postIds":["66d5daaf-4f21-4d45-9ff3-217b5978f108"],"posts":[ ... ],"failed":0,"replayed":false,"creditsLeft":7740}}
```

Events are unnamed. Read the `type` field in `data`:

| `type` | Payload | Meaning |
| - | - | - |
| `started` | `generationGroupId`, `versions` | Writing began. Credits are held. |
| `version_delta` | `index`, `text`, `reset?` | More text for version `index`. Append it. If `reset` is `true`, the version is being rewritten: drop what you have first. |
| `version_done` | `index`, `postId`, `text`, `charCount` | Version `index` is final and saved as a draft. |
| `done` | `postIds`, `creditsLeft` | All versions are finished. |
| `error` | `index?`, `code`, `message` | With `index`: that version failed and the others go on. Without: the whole request failed and was not charged. |
| `result` | `result` | The last event. Same body as the JSON answer, including `posts`, `failed` and `replayed`. |

A keep-alive comment (`: keep-alive`) arrives every 15 seconds.

Things to know:

* If the request fails before writing starts (validation, plan, credits, idempotency), you get the normal JSON error with its status, not a stream.
* If the model needs more detail, the stream has one event: `{"type":"result","result":{"status":"needs_input","question":"...","attempt":1}}`. It is free.
* A retry with a key that already finished replays the stored answer as a single `result` event, with the header `Idempotent-Replayed: true`.
* Closing the connection cancels the run.

```javascript
// readSse(res, onEvent) is the same fetch-based reader as streamJob above,
// pointed at the POST response. Here it collects the text per version.
const versions = [];
await readSse(res, (e) => {
  if (e.type === "version_delta") {
    versions[e.index] = e.reset ? e.text : (versions[e.index] ?? "") + e.text;
  } else if (e.type === "result") {
    console.log(e.result.postIds);
  }
});
```

> [card] [Carousel recipe](/api/recipes/carousels.md)
>
> Create a carousel and follow its job.

> [card] [Infographic recipe](/api/recipes/infographics.md)
>
> Create and edit an infographic.

> [card] [Errors](/api/errors.md)
>
> Codes you may meet.

> [card] [Idempotency](/api/idempotency.md)
>
> Keys and replays.
