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:
{
"id" : "c0386bc8-2b65-5563-99d1-0c087eb7e95e" ,
"carouselId" : "c0386bc8-2b65-5563-99d1-0c087eb7e95e" ,
"jobId" : "carousel-build:c0386bc8-2b65-5563-99d1-0c087eb7e95e:0" ,
"status" : "queued"
}
{
"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.
curl https://api.postchampai.com/api/v1/jobs/carousel-build:4cbd208e-358a-54d6-ae41-7e1d253b8a2c:0 \
-H "x-api-key: $POSTCHAMP_API_KEY "
curl https://api.postchampai.com/api/v1/jobs/carousel-build:4cbd208e-358a-54d6-ae41-7e1d253b8a2c:0 \
-H "x-api-key: $POSTCHAMP_API_KEY"{
"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 }
}
{
"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:
{
"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"
}
{
"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, so prefer the stream for long jobs.
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" );
}
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");
}Stream a job
GET /api/v1/jobs/{jobId}/events is a server-sent events stream (Content-Type: text/event-stream).
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 "
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"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
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: 1796469629060How 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
messageevent.datais the same JSON as the job read above.idis the event time in milliseconds. - The stream ends after the first
doneorfailedevent. - A
: keep-alivecomment 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_limitedwithRetry-After: 5.
// 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 ;
}
}
}
}
// 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;
}
}
}
}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.
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}'
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}'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}}
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
resultevent, with the headerIdempotent-Replayed: true. - Closing the connection cancels the run.
// 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 );
}
});
// 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);
}
});- Create a carousel and follow its job.
- Create and edit an infographic.
- Codes you may meet.
- Keys and replays.