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

# Recipe: infographics

> Create an infographic with the API, wait for its job, read the image, edit it, list your infographics and delete one.

An infographic turns a prompt (or the text of a post) into an image you can attach to a post. Creating one costs 25 credits and each edit costs 25. Credits are held when you start and charged when the image is ready. A failed run releases the hold. Infographics count toward your plan's daily image cap.

The flow:

1. `POST .../infographics` with an `Idempotency-Key`. It answers `202` with `jobId`.
2. Poll or stream the job until `done`.
3. `GET .../infographics/{id}` for the image URL and versions.
4. `POST .../infographics/{id}/edit` to change it. Each edit is a new version and a new job.

## Create options

| Field | Meaning |
| - | - |
| `prompt` | Required. What the infographic should explain. Up to 50,000 characters. |
| `postContent` | Optional post text to base it on. |
| `kbItemIds` | Up to 20 knowledge base item ids to draw facts from. |
| `renderMode` | `html` (default: exact text, clean layouts) or `ai_image` (an AI-drawn image). |
| `templateKey` | The layout for `html` mode: `infographic-flat-grid`, `infographic-bright-data`, `infographic-mono-line`, `infographic-notebook`, `infographic-magazine`, `infographic-dark-data`, `infographic-blueprint` or `infographic-poster-print`. |
| `stylePreset` | The look for `ai_image` mode (for example `flat_vector` or `watercolor`), or `null`. |
| `aspect` | `portrait` (default), `square` or `landscape`. |
| `references` | Up to 20 uploaded pictures with a role of `style`, `subject` or `logo`. |
| `useBrandKit` | `true` applies the workspace brand kit. |

## 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.reason = json.error?.details?.reason;
    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
  const started = await api("POST", `/workspaces/${ws}/infographics`, {
    idempotencyKey: randomUUID(),
    body: {
      prompt: "The 4 stages of a weekly shipping cadence",
      renderMode: "html",
      templateKey: "infographic-flat-grid",
      aspect: "portrait",
    },
  });
  console.log("Queued", started.id, started.jobId);

  // 2. Wait
  await waitForJob(started.jobId);

  // 3. Read: `url` is a presigned image link that expires, so download it now
  const info = await api("GET", `/workspaces/${ws}/infographics/${started.id}`);
  console.log(info.title, `${info.width}x${info.height}`, info.url);
  console.log(`${info.versions.length} version(s)`);

  // 4. Edit: a new version and a new job
  const edit = await api("POST", `/workspaces/${ws}/infographics/${started.id}/edit`, {
    idempotencyKey: randomUUID(),
    body: { instruction: "Make the title larger" },
  });
  await waitForJob(edit.jobId);
  const edited = await api("GET", `/workspaces/${ws}/infographics/${started.id}`);
  console.log(`${edited.versions.length} versions, current ${edited.currentVersionId}`);

  // 5. List (newest first, cursor pages, limit 1 to 50)
  const page = await api("GET", `/workspaces/${ws}/infographics?limit=5`);
  console.log(page.items.map((i) => `${i.id} ${i.status}`).join("\n"), page.nextCursor);

  // 6. Delete when you no longer need it
  // await api("DELETE", `/workspaces/${ws}/infographics/${started.id}`); // { "deleted": true }
}

main().catch((err) => {
  if (err.code === "conflict" && err.reason === "infographic_in_progress") console.error("Still being made. Wait for its job.");
  else if (err.code === "plan_limit") console.error("A plan or daily image limit was reached.");
  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.reason = (error.get("details") or {}).get("reason")
        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
    started = api(
        "POST",
        f"/workspaces/{ws}/infographics",
        idempotency_key=str(uuid.uuid4()),
        body={
            "prompt": "The 4 stages of a weekly shipping cadence",
            "renderMode": "html",
            "templateKey": "infographic-flat-grid",
            "aspect": "portrait",
        },
    )
    print("Queued", started["id"], started["jobId"])

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

    # 3. Read: "url" is a presigned image link that expires, so download it now
    info = api("GET", f"/workspaces/{ws}/infographics/{started['id']}")
    print(info["title"], f"{info['width']}x{info['height']}", info["url"])
    print(len(info["versions"]), "version(s)")

    # 4. Edit: a new version and a new job
    edit = api(
        "POST",
        f"/workspaces/{ws}/infographics/{started['id']}/edit",
        idempotency_key=str(uuid.uuid4()),
        body={"instruction": "Make the title larger"},
    )
    wait_for_job(edit["jobId"])
    edited = api("GET", f"/workspaces/{ws}/infographics/{started['id']}")
    print(len(edited["versions"]), "versions, current", edited["currentVersionId"])

    # 5. List (newest first, cursor pages, limit 1 to 50)
    page = api("GET", f"/workspaces/{ws}/infographics?limit=5")
    for item in page["items"]:
        print(item["id"], item["status"])
    print(page["nextCursor"])

    # 6. Delete when you no longer need it
    # api("DELETE", f"/workspaces/{ws}/infographics/{started['id']}")  # {"deleted": True}


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/infographics \
  -H "$H_KEY" -H "Content-Type: application/json" -H "Idempotency-Key: $(uuidgen)" \
  -d '{"prompt": "The 4 stages of a weekly shipping cadence", "renderMode": "html", "aspect": "portrait"}' > started.json
ID=$(jq -r .id started.json); JOB=$(jq -r .jobId started.json)

# 2. Poll
curl -s $BASE/jobs/$JOB -H "$H_KEY"

# 3. Read
curl -s $BASE/workspaces/$WS/infographics/$ID -H "$H_KEY" | jq '{title, status, url, versions: [.versions[].status]}'

# 4. Edit (202)
curl -s -X POST $BASE/workspaces/$WS/infographics/$ID/edit \
  -H "$H_KEY" -H "Content-Type: application/json" -H "Idempotency-Key: $(uuidgen)" \
  -d '{"instruction": "Make the title larger"}'

# 5. Delete
curl -s -X DELETE $BASE/workspaces/$WS/infographics/$ID -H "$H_KEY"
```

## The answers

Create and edit answer `202`:

```json
{
  "id": "dea5dabd-4ae0-5c93-a50e-bc86bf75e75d",
  "infographicId": "dea5dabd-4ae0-5c93-a50e-bc86bf75e75d",
  "versionId": "e71da5cf-c8bf-5c5b-b6e4-ed66f47aeb51",
  "jobId": "infographic:e71da5cf-c8bf-5c5b-b6e4-ed66f47aeb51",
  "status": "queued"
}
```

The job ends with a result of `infographicId` and `versionId`. `GET .../infographics/{id}` then returns the infographic (shortened here):

```json
{
  "id": "dea5dabd-4ae0-5c93-a50e-bc86bf75e75d",
  "title": "Hiring in four steps",
  "prompt": "The 4 stages of a weekly shipping cadence",
  "renderMode": "html",
  "templateKey": "infographic-flat-grid",
  "aspect": "portrait",
  "width": 2160,
  "height": 2700,
  "status": "ready",
  "error": null,
  "currentVersionId": "e71da5cf-c8bf-5c5b-b6e4-ed66f47aeb51",
  "url": "https://...presigned image url...",
  "versions": [
    { "id": "e71da5cf-c8bf-5c5b-b6e4-ed66f47aeb51", "versionNo": 1, "instruction": null, "status": "ready", "error": null }
  ],
  "jobId": null,
  "canEdit": true
}
```

The `title` here comes from a test model and does not match the prompt. A real run titles the infographic from your prompt. The list answer (`GET .../infographics`) is `{ items, nextCursor }` with one summary per infographic. See [Pagination](/api/pagination.md).

## Editing

* `instruction` is required. Describe the change in plain words.
* `referenceObjectIds` (up to 3 uploaded pictures) works in `ai_image` mode. `html` mode takes none (`400 references_unsupported`).
* You can edit only an infographic that has a finished version and is not running (`409 conflict`, `infographic_not_ready` or `infographic_in_progress`).
* Each edit is charged when its new version is ready.

## Errors and retries

* **A failed job.** The job's `message` says why and the hold is released. Start again with a new `Idempotency-Key`.
* **`422 prompt_too_long`.** Shorten the prompt or `postContent`.
* **`403 plan_limit`.** A plan or daily image cap was reached. `details.resetsAt` may say when it resets.
* **`409 conflict` with `already_done`.** This request already ran. Read the infographic.
* **Deleting a running infographic** answers `409 conflict` (`infographic_in_progress`). Wait for the job.

> [card] [Jobs and streaming](/api/jobs-and-streaming.md)
>
> Stream the job.

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