Recipe: generate and schedule a post
A complete script that writes a LinkedIn post with the API, answers the model’s question if it asks one, edits the text and schedules it.
This recipe writes a post from a prompt, picks a version, schedules it and handles the failures you will meet. Generation costs 5 credits per request, however many versions (1 to 3) you ask for. Five variations in one request (generate-batch) cost 5.
The flow:
GET /keyto find the workspace.POST .../posts/generatewith anIdempotency-Key. If the answer isneeds_input, answer the question and send it again with the same key.- Optionally
PATCH .../posts/{postId}to change the text. POST .../posts/{postId}/schedule.
Before you start
- A key in the environment variable
POSTCHAMP_API_KEY. - A connected LinkedIn account in the workspace, or scheduling answers
400 linkedin_not_connected. - Node 18 or later, or Python with
requests.
The script
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 ));
class ApiError extends Error {
constructor (status , body , requestId ) {
super (` ${ status } ${ body ?. error ?. code } : ${ body ?. error ?. message } ` );
this .status = status ;
this .code = body ?.error ?.code ;
this .details = body ?.error ?.details ;
this .requestId = requestId ;
}
}
// One call, with retries for 429 and 5xx. Pass the same idempotencyKey for every attempt.
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 ;
}
if (res .status === 204 ) return null ;
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 ) {
const wait = Number (res .headers .get ("Retry-After" )) || 2 * attempt ;
await sleep (wait * 1000 );
continue ;
}
throw new ApiError (res .status , json , res .headers .get ("X-Request-Id" ));
}
}
async function generate (workspaceId , prompt , answer ) {
const idempotencyKey = randomUUID (); // reused if the model asks a question
let answers = [];
for (let round = 0 ; round < 3 ; round ++ ) {
const result = await api ("POST" , `/workspaces/ ${ workspaceId } /posts/generate` , {
idempotencyKey ,
body: { prompt , versions: 2 , ... (answers .length ? { answers } : {}) },
});
if (result .status === "done" ) return result ;
// status === "needs_input": free, not stored. Answer and send again with the same key.
answers = [... answers , { question: result .question , answer: await answer (result .question ) }];
}
throw new Error ("The model kept asking questions" );
}
async function main () {
const info = await api ("GET" , "/key" );
const workspace = info .workspaces .find ((w ) => w .isMain ) ?? info .workspaces [0 ];
console .log (`Using workspace ${ workspace . name } ` );
const result = await generate (
workspace .id ,
"Why founders should write down their weekly wins" ,
async (question ) => {
console .log (`The model asks: ${ question } ` );
return "Founders at seed stage, in a friendly tone." ; // answer it from your own data
},
);
console .log (`Credits left: ${ result . creditsLeft } , failed versions: ${ result . failed } ` );
// Each version is a saved draft. Choose one (here: the first).
const post = result .posts [0 ];
console .log (post .linkedInText );
// Optional: change the text. PATCH takes "content"; the limit is 3,000 characters.
await api ("PATCH" , `/workspaces/ ${ workspace . id } /posts/ ${ post . id } ` , {
body: { content: ` ${ post . content } \n\n What did you ship this week?` },
});
// Schedule two days from now at 09:00 UTC. Use localDateTime ("2026-12-07T09:00") for workspace time.
const when = new Date (Date .now () + 2 * 24 * 3600 * 1000 );
when .setUTCHours (9 , 0 , 0 , 0 );
try {
const scheduled = await api ("POST" , `/workspaces/ ${ workspace . id } /posts/ ${ post . id } /schedule` , {
body: { scheduledAt: when .toISOString () },
});
console .log (`Scheduled for ${ scheduled . scheduledAt } ( ${ scheduled . timezone } )` );
} catch (err ) {
if (err .code === "linkedin_not_connected" ) {
console .error (`Connect LinkedIn first: ${ err . details ?. reconnectPath } ` );
} else if (err .code === "scheduled_too_soon" ) {
console .error ("Pick a time at least a minute ahead" );
} else if (err .code === "forbidden" && err .details ?.reason === "approval_required" ) {
console .error ("Approvals are on: an approver must approve the post first" );
} else {
throw err ;
}
}
}
main ().catch ((err ) => {
console .error (err .message , err .requestId ? `(request ${ err . requestId } )` : "" );
process .exit (1 );
});
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));
class ApiError extends Error {
constructor(status, body, requestId) {
super(`${status} ${body?.error?.code}: ${body?.error?.message}`);
this.status = status;
this.code = body?.error?.code;
this.details = body?.error?.details;
this.requestId = requestId;
}
}
// One call, with retries for 429 and 5xx. Pass the same idempotencyKey for every attempt.
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;
}
if (res.status === 204) return null;
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) {
const wait = Number(res.headers.get("Retry-After")) || 2 * attempt;
await sleep(wait * 1000);
continue;
}
throw new ApiError(res.status, json, res.headers.get("X-Request-Id"));
}
}
async function generate(workspaceId, prompt, answer) {
const idempotencyKey = randomUUID(); // reused if the model asks a question
let answers = [];
for (let round = 0; round < 3; round++) {
const result = await api("POST", `/workspaces/${workspaceId}/posts/generate`, {
idempotencyKey,
body: { prompt, versions: 2, ...(answers.length ? { answers } : {}) },
});
if (result.status === "done") return result;
// status === "needs_input": free, not stored. Answer and send again with the same key.
answers = [...answers, { question: result.question, answer: await answer(result.question) }];
}
throw new Error("The model kept asking questions");
}
async function main() {
const info = await api("GET", "/key");
const workspace = info.workspaces.find((w) => w.isMain) ?? info.workspaces[0];
console.log(`Using workspace ${workspace.name}`);
const result = await generate(
workspace.id,
"Why founders should write down their weekly wins",
async (question) => {
console.log(`The model asks: ${question}`);
return "Founders at seed stage, in a friendly tone."; // answer it from your own data
},
);
console.log(`Credits left: ${result.creditsLeft}, failed versions: ${result.failed}`);
// Each version is a saved draft. Choose one (here: the first).
const post = result.posts[0];
console.log(post.linkedInText);
// Optional: change the text. PATCH takes "content"; the limit is 3,000 characters.
await api("PATCH", `/workspaces/${workspace.id}/posts/${post.id}`, {
body: { content: `${post.content}\n\nWhat did you ship this week?` },
});
// Schedule two days from now at 09:00 UTC. Use localDateTime ("2026-12-07T09:00") for workspace time.
const when = new Date(Date.now() + 2 * 24 * 3600 * 1000);
when.setUTCHours(9, 0, 0, 0);
try {
const scheduled = await api("POST", `/workspaces/${workspace.id}/posts/${post.id}/schedule`, {
body: { scheduledAt: when.toISOString() },
});
console.log(`Scheduled for ${scheduled.scheduledAt} (${scheduled.timezone})`);
} catch (err) {
if (err.code === "linkedin_not_connected") {
console.error(`Connect LinkedIn first: ${err.details?.reconnectPath}`);
} else if (err.code === "scheduled_too_soon") {
console.error("Pick a time at least a minute ahead");
} else if (err.code === "forbidden" && err.details?.reason === "approval_required") {
console.error("Approvals are on: an approver must approve the post first");
} else {
throw err;
}
}
}
main().catch((err) => {
console.error(err.message, err.requestId ? `(request ${err.requestId})` : "");
process.exit(1);
});What each step returns
- Generate answers
200withstatus: "done",postIds,posts(each a draft withorigin: "api"),failed(versions that failed and were not charged),suggestedFirstCommentandcreditsLeft. Withstatus: "needs_input"it answersquestionandattemptinstead, and charges nothing. - Schedule answers the schedule state:
status: "scheduled",scheduledAt, the workspace-local date and time,timezoneandscheduleVersion.
Variations and options
- Five angles in one request:
POST .../posts/generate-batch. Same body, noversions. - Stream the text as it is written: add
Accept: text/event-stream. See Jobs and streaming. - Use a content style: add
"contentStyleId": "preset:story"from Content styles. - Cancel:
POST .../posts/{postId}/cancel-schedulereturns the post to a draft. - First comment: send
"firstComment": "text"with the schedule call. - Safe rescheduling: the schedule answer has
scheduleVersion. Send it back as"expect": { "scheduleVersion": 1 }to refuse the change when someone else changed the schedule.
If something fails
details shows needed and balance. Nothing was charged. Add credits or wait for the monthly reset.
Send an Idempotency-Key header on the generate call.
You reused a key with a different prompt. Create a new key for each new request.
The post is in review, approved or published, so it cannot be edited. Edit another draft.
Wait Retry-After seconds. The script above does this for you. See Rate limits.
- How the key works.
- All codes.