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

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

1. `GET /key` to find the workspace.
2. `POST .../posts/generate` with an `Idempotency-Key`. If the answer is `needs_input`, answer the question and send it again with the same key.
3. Optionally `PATCH .../posts/{postId}` to change the text.
4. `POST .../posts/{postId}/schedule`.

## Before you start

* A [key](/api/authentication.md) 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

```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));

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);
});
```

```python Python
import os
import time
import uuid
from datetime import datetime, time as dtime, timedelta, timezone

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.status = status
        self.code = error.get("code")
        self.details = error.get("details") or {}
        self.request_id = request_id


def api(method, path, body=None, idempotency_key=None, tries=4):
    """One call, with retries for 429 and 5xx. Pass the same idempotency_key for every attempt."""
    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=330
            )
        except requests.RequestException:
            if attempt == tries:
                raise
            time.sleep(attempt)
            continue
        if res.status_code == 204:
            return None
        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 generate(workspace_id, prompt, answer):
    idempotency_key = str(uuid.uuid4())  # reused if the model asks a question
    answers = []
    for _ in range(3):
        body = {"prompt": prompt, "versions": 2}
        if answers:
            body["answers"] = answers
        result = api(
            "POST",
            f"/workspaces/{workspace_id}/posts/generate",
            body=body,
            idempotency_key=idempotency_key,
        )
        if result["status"] == "done":
            return result
        # status == "needs_input": free, not stored. Answer and send again with the same key.
        answers.append({"question": result["question"], "answer": answer(result["question"])})
    raise RuntimeError("The model kept asking questions")


def main():
    info = api("GET", "/key")
    workspace = next((w for w in info["workspaces"] if w["isMain"]), info["workspaces"][0])
    print("Using workspace", workspace["name"])

    def answer(question):
        print("The model asks:", question)
        return "Founders at seed stage, in a friendly tone."  # answer it from your own data

    result = generate(workspace["id"], "Why founders should write down their weekly wins", answer)
    print(f"Credits left: {result['creditsLeft']}, failed versions: {result['failed']}")

    # Each version is a saved draft. Choose one (here: the first).
    post = result["posts"][0]
    print(post["linkedInText"])

    # Optional: change the text. PATCH takes "content"; the limit is 3,000 characters.
    api(
        "PATCH",
        f"/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.
    when = datetime.combine(
        (datetime.now(timezone.utc) + timedelta(days=2)).date(), dtime(9, 0), timezone.utc
    )
    try:
        scheduled = api(
            "POST",
            f"/workspaces/{workspace['id']}/posts/{post['id']}/schedule",
            body={"scheduledAt": when.isoformat().replace("+00:00", "Z")},
        )
        print("Scheduled for", scheduled["scheduledAt"], scheduled["timezone"])
    except ApiError as err:
        if err.code == "linkedin_not_connected":
            print("Connect LinkedIn first:", err.details.get("reconnectPath"))
        elif err.code == "scheduled_too_soon":
            print("Pick a time at least a minute ahead")
        elif err.code == "forbidden" and err.details.get("reason") == "approval_required":
            print("Approvals are on: an approver must approve the post first")
        else:
            raise


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"

# 1. Workspace
WS=$(curl -s $BASE/key -H "$H_KEY" | jq -r '.workspaces[] | select(.isMain) | .id')

# 2. Generate (re-run with the same Idempotency-Key to replay, never to pay twice)
KEY=$(uuidgen)
curl -s -X POST $BASE/workspaces/$WS/posts/generate \
  -H "$H_KEY" -H "Content-Type: application/json" -H "Idempotency-Key: $KEY" \
  -d '{"prompt": "Why founders should write down their weekly wins", "versions": 2}' > gen.json
jq -r '.status' gen.json   # "done", or "needs_input" with a .question

# If needs_input, send again with the SAME key and the answer:
# -d '{"prompt": "...", "versions": 2, "answers": [{"question": "<the question>", "answer": "<yours>"}]}'

POST=$(jq -r '.postIds[0]' gen.json)

# 3. Optional edit
curl -s -X PATCH $BASE/workspaces/$WS/posts/$POST \
  -H "$H_KEY" -H "Content-Type: application/json" \
  -d '{"content": "Your edited text"}'

# 4. Schedule (at least one minute ahead)
curl -s -X POST $BASE/workspaces/$WS/posts/$POST/schedule \
  -H "$H_KEY" -H "Content-Type: application/json" \
  -d '{"scheduledAt": "2026-12-07T09:00:00Z"}'
```

## What each step returns

* **Generate** answers `200` with `status: "done"`, `postIds`, `posts` (each a draft with `origin: "api"`), `failed` (versions that failed and were not charged), `suggestedFirstComment` and `creditsLeft`. With `status: "needs_input"` it answers `question` and `attempt` instead, and charges nothing.
* **Schedule** answers the schedule state: `status: "scheduled"`, `scheduledAt`, the workspace-local date and time, `timezone` and `scheduleVersion`.

## Variations and options

* **Five angles in one request:** `POST .../posts/generate-batch`. Same body, no `versions`.
* **Stream the text** as it is written: add `Accept: text/event-stream`. See [Jobs and streaming](/api/jobs-and-streaming.md#stream-a-post-generation).
* **Use a content style:** add `"contentStyleId": "preset:story"` from [Content styles](/api/recipes/content-styles.md).
* **Cancel:** `POST .../posts/{postId}/cancel-schedule` returns 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

> [accordion] 402 insufficient\_credits
>
> `details` shows `needed` and `balance`. Nothing was charged. Add credits or wait for the monthly reset.

> [accordion] 400 idempotency\_key\_required
>
> Send an `Idempotency-Key` header on the generate call.

> [accordion] 409 idempotency\_conflict
>
> You reused a key with a different prompt. Create a new key for each new request.

> [accordion] 409 post\_locked
>
> The post is in review, approved or published, so it cannot be edited. Edit another draft.

> [accordion] 429 rate\_limited
>
> Wait `Retry-After` seconds. The script above does this for you. See [Rate limits](/api/rate-limits.md).

> [card] [Idempotency](/api/idempotency.md)
>
> How the key works.

> [card] [Errors](/api/errors.md)
>
> All codes.
