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

# Recipe: content styles

> List the built-in styles, create your own with example posts, write a post in a style, and edit or archive it, with the API.

A content style teaches the writer how a kind of post should read: its guidance and a few example posts. PostChamp ships built-in styles (`preset:story`, `preset:contrarian` and others). You can add your own. See [Content styles](/create/content-styles.md) for how they work in the app, and **Settings → Content styles** to manage them there.

All style calls are free. Writing a post with a style costs the usual 5 credits.

The flow:

1. `GET .../content-styles` to list styles.
2. `POST .../content-styles` to create one.
3. `POST .../content-styles/{styleId}/examples` to add more examples.
4. `POST .../posts/generate` with `contentStyleId`.
5. `PATCH`, remove an example, or archive.

## Limits

| What | Limit |
| - | - |
| Name | 60 characters |
| Description | 240 characters |
| Guidance | 4,000 characters |
| One example | 3,000 characters |
| Examples per call | 5 |
| Examples per style | 20 |
| Custom styles per workspace | 50 |

## 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 main() {
  const { workspaces } = await api("GET", "/key");
  const ws = (workspaces.find((w) => w.isMain) ?? workspaces[0]).id;

  // 1. List: built-in styles have ids like "preset:story"
  const { items } = await api("GET", `/workspaces/${ws}/content-styles`);
  console.log(items.map((s) => `${s.id} (${s.kind})`).join(", "));

  // 2. Create your own, with up to 5 examples
  const style = await api("POST", `/workspaces/${ws}/content-styles`, {
    body: {
      name: "Weekly wins",
      description: "Short, factual weekly recaps.",
      guidance: "Open with the number. Three short lines. End with one lesson.",
      examples: ["Shipped 4 features this week. 2 broke. 1 mattered.\n\nThe one that mattered took 20 minutes."],
    },
  });

  // 3. Add more examples (up to 5 per call, 20 per style)
  const withMore = await api("POST", `/workspaces/${ws}/content-styles/${style.id}/examples`, {
    body: { examples: ["Closed 3 deals. Lost 1. Learned more from the loss."] },
  });
  console.log(withMore.examples.map((e) => e.key));

  // 4. Write a post in that style (spends credits: send an Idempotency-Key)
  const result = await api("POST", `/workspaces/${ws}/posts/generate`, {
    idempotencyKey: randomUUID(),
    body: { prompt: "What we shipped this week", contentStyleId: style.id, versions: 1 },
  });
  console.log(result.status, result.postIds);

  // 5. Update the guidance
  await api("PATCH", `/workspaces/${ws}/content-styles/${style.id}`, {
    body: { guidance: "Open with the number. Three short lines. End with a question." },
  });

  // 6. Remove an example. Send the example's key, so a list that changed meanwhile is refused (409 item_moved).
  const fresh = await api("GET", `/workspaces/${ws}/content-styles/${style.id}`);
  const last = fresh.examples.length - 1;
  await api("DELETE", `/workspaces/${ws}/content-styles/${style.id}/examples/${last}?key=${fresh.examples[last].key}`);

  // 7. Archive it. Archived styles disappear from the list unless you ask: ?includeArchived=true
  const archived = await api("DELETE", `/workspaces/${ws}/content-styles/${style.id}`);
  console.log("archived:", archived.archived);
}

main().catch((err) => {
  if (err.code === "conflict" && err.reason === "style_limit") console.error("Archive a style first: the workspace is at its limit.");
  else if (err.code === "conflict" && err.reason === "item_moved") console.error("The examples changed. Read the style again.");
  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=330)
        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 main():
    workspaces = api("GET", "/key")["workspaces"]
    ws = next((w for w in workspaces if w["isMain"]), workspaces[0])["id"]

    # 1. List: built-in styles have ids like "preset:story"
    items = api("GET", f"/workspaces/{ws}/content-styles")["items"]
    print(", ".join(f"{s['id']} ({s['kind']})" for s in items))

    # 2. Create your own, with up to 5 examples
    style = api(
        "POST",
        f"/workspaces/{ws}/content-styles",
        body={
            "name": "Weekly wins",
            "description": "Short, factual weekly recaps.",
            "guidance": "Open with the number. Three short lines. End with one lesson.",
            "examples": ["Shipped 4 features this week. 2 broke. 1 mattered.\n\nThe one that mattered took 20 minutes."],
        },
    )

    # 3. Add more examples (up to 5 per call, 20 per style)
    with_more = api(
        "POST",
        f"/workspaces/{ws}/content-styles/{style['id']}/examples",
        body={"examples": ["Closed 3 deals. Lost 1. Learned more from the loss."]},
    )
    print([e["key"] for e in with_more["examples"]])

    # 4. Write a post in that style (spends credits: send an Idempotency-Key)
    result = api(
        "POST",
        f"/workspaces/{ws}/posts/generate",
        idempotency_key=str(uuid.uuid4()),
        body={"prompt": "What we shipped this week", "contentStyleId": style["id"], "versions": 1},
    )
    print(result["status"], result["postIds"])

    # 5. Update the guidance
    api(
        "PATCH",
        f"/workspaces/{ws}/content-styles/{style['id']}",
        body={"guidance": "Open with the number. Three short lines. End with a question."},
    )

    # 6. Remove an example. Send the example's key, so a list that changed meanwhile is refused (409 item_moved).
    fresh = api("GET", f"/workspaces/{ws}/content-styles/{style['id']}")
    last = len(fresh["examples"]) - 1
    api("DELETE", f"/workspaces/{ws}/content-styles/{style['id']}/examples/{last}?key={fresh['examples'][last]['key']}")

    # 7. Archive it. Archived styles disappear from the list unless you ask: ?includeArchived=true
    archived = api("DELETE", f"/workspaces/{ws}/content-styles/{style['id']}")
    print("archived:", archived["archived"])


if __name__ == "__main__":
    try:
        main()
    except ApiError as err:
        if err.code == "conflict" and err.reason == "style_limit":
            raise SystemExit("Archive a style first: the workspace is at its limit.")
        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. List
curl -s $BASE/workspaces/$WS/content-styles -H "$H_KEY" | jq -r '.items[] | .id'

# 2. Create
STYLE=$(curl -s -X POST $BASE/workspaces/$WS/content-styles \
  -H "$H_KEY" -H "Content-Type: application/json" \
  -d '{"name": "Weekly wins", "guidance": "Open with the number. Three short lines.", "examples": ["Shipped 4 features. 2 broke. 1 mattered."]}' | jq -r .id)

# 3. Add examples
curl -s -X POST $BASE/workspaces/$WS/content-styles/$STYLE/examples \
  -H "$H_KEY" -H "Content-Type: application/json" \
  -d '{"examples": ["Closed 3 deals. Lost 1. Learned more from the loss."]}'

# 4. Write a post in the style
curl -s -X POST $BASE/workspaces/$WS/posts/generate \
  -H "$H_KEY" -H "Content-Type: application/json" -H "Idempotency-Key: $(uuidgen)" \
  -d "{\"prompt\": \"What we shipped this week\", \"contentStyleId\": \"$STYLE\", \"versions\": 1}"

# 5. Remove example 1 (use its key from GET .../content-styles/$STYLE)
curl -s -X DELETE "$BASE/workspaces/$WS/content-styles/$STYLE/examples/1?key=<example key>" -H "$H_KEY"

# 6. Archive
curl -s -X DELETE $BASE/workspaces/$WS/content-styles/$STYLE -H "$H_KEY"
```

## The style object

```json
{
  "id": "c918d554-2992-43ed-891b-758a6fc02f99",
  "kind": "custom",
  "presetKey": null,
  "name": "Weekly wins",
  "description": "Short, factual weekly recaps.",
  "guidance": "Open with the number. Three short lines. End with one lesson.",
  "examples": [
    { "text": "Shipped 4 features this week. 2 broke. 1 mattered.\n\nThe one that mattered took 20 minutes.", "key": "4d4a37a618f4adf8" }
  ],
  "customized": false,
  "archived": false,
  "updatedAt": "2026-12-05T11:22:01.992Z"
}
```

* `kind` is `preset` for built-in styles and `custom` for yours.
* Each example has a `text` and a `key`. The `key` identifies the example for deletion.
* The `index` in the delete path is the example's position in `examples`.

## Rules

* You can read built-in styles and use them in `contentStyleId`. Built-in styles cannot be archived (`400 preset_not_archivable`).
* `DELETE` on a style archives it. An archived style cannot be updated or given examples (`409 conflict`, `style_archived`).

## Errors

| Code | What to do |
| - | - |
| `409 conflict` with `item_moved` | The example list changed. Read the style again, then send the current `key`. |
| `409 conflict` with `style_limit` | Archive a style you do not use. |
| `400 too_many_examples` | Send up to 5 examples per call. |
| `400 style_examples_full` | Remove an example first. |
| `404 not_found` | The style id does not exist in this workspace. |

See [Errors](/api/errors.md) for the rest.

> [card] [Generate and schedule](/api/recipes/generate-and-schedule.md)
>
> Write and schedule a post.

> [card] [Content styles in the app](/create/content-styles.md)
>
> How styles work.
