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

# Building workflows

> Master guide to creating, configuring, testing, and managing automated pipelines via REST API, MCP, and AI Copilot.

# Building Workflows

Workflows automate multi-step processes across social media platforms, AI models, RSS feeds, webhooks, and third-party integrations. This guide covers how to build, test, publish, and activate workflows programmatically via the REST API or through AI tools.

***

## 🏗️ Workflow Architecture

Every Posttu workflow consists of:

1. **Container (`Workflow`)**: Stores workspace metadata (name, description, active status) and versions.
2. **Draft Version (`WorkflowVersion`)**: The editable canvas workspace containing a **Trigger** and one or more **Steps**.
3. **Trigger (`WorkflowTrigger`)**: The event or schedule that initiates execution (e.g. `schedule`, `webhook`, `rss_new_item`, `channel_new_comment`).
4. **Steps (`WorkflowStep`)**: Action nodes (e.g. `ai_ask_ai`, `x_create_post`, `http_request`, `condition`, `loop`, `delay`, `code`) arranged in a linked list sequence or nested within containers.
5. **Expressions (`{{...}}`)**: Dynamic template tags that reference data from triggers, preceding steps, or loop iterations.
6. **Published Version**: An immutable release snapshot promoted from the draft. Workflows must be published before they can be activated in production.

***

## ⚡ 6-Step Workflow Construction Protocol

Follow this 6-step lifecycle to build, verify, and launch a complete workflow:

```mermaid theme={null}
flowchart TD
    A["1. Discover Pieces & Connections"] --> B["2. Create Workflow Container"]
    B --> C["3. Configure Starter Trigger"]
    C --> D["4. Upsert Steps, Branches & Loops"]
    D --> E["5. Test Workflow Draft"]
    E --> F["6. Publish Draft & Activate"]
```

***

### Step 1: Discover Available Integrations, Pieces & Connections

Before constructing steps, inspect the piece catalog to discover available actions, input schemas, and active workspace authorizations:

```bash theme={null}
# 1. Search available pieces by keyword (matches piece, action, and trigger names)
curl "https://posttu.com/api/v1/workflow/pieces?search=x&includeProps=true" \
  -H "Authorization: Bearer YOUR_API_KEY"

# 2. Inspect complete property schemas for a single piece
curl "https://posttu.com/api/v1/workflow/pieces/slack" \
  -H "Authorization: Bearer YOUR_API_KEY"

# 3. List active third-party connections to obtain valid __connectionId values
curl "https://posttu.com/api/v1/workflow/connections?pieceNames=slack,x" \
  -H "Authorization: Bearer YOUR_API_KEY"
```

***

### Step 2: Create a Workflow Container

Create a new workflow container to receive an empty draft version:

```bash theme={null}
curl -X POST "https://posttu.com/api/v1/workflow" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Weekly Tech Digest",
    "description": "Compiles TechCrunch RSS feed items and schedules a weekly digest on X"
  }'
```

Save the returned `id` (e.g. `wkf_abc123`) for subsequent requests.

***

### Step 3: Configure the Workflow Trigger

Attach and configure the starter trigger for the workflow draft. For `schedule` triggers, always specify `scheduleType` (`"cron"`, `"interval"`, or `"preset"`) inside `settings` — otherwise the scheduler defaults to daily at 9:00 AM UTC:

```bash theme={null}
curl -X POST "https://posttu.com/api/v1/workflow/wkf_abc123/trigger" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "schedule",
    "displayName": "Every Monday at 9 AM",
    "cronExpression": "0 9 * * 1",
    "settings": {
      "scheduleType": "cron",
      "cronExpression": "0 9 * * 1",
      "timezone": "UTC"
    }
  }'
```

#### Supported Trigger Types

| Type | Name | Description | Output Data Expressions |
| - | - | - | - |
| **Schedule** | `schedule` | Cron, interval, or preset schedule trigger | `{{trigger.scheduledTime}}`, `{{trigger.timezone}}`, `{{trigger.executionCount}}` |
| **Webhook** | `webhook` | Inbound HTTP endpoint (`/api/workflows/{id}`) | `{{trigger.body}}`, `{{trigger.headers}}`, `{{trigger.query}}`, `{{trigger.method}}`, `{{trigger.timestamp}}` |
| **RSS Feed** | `rss_new_item` | Polls RSS/Atom feeds (`settings.rss_feed_url`) for new items | `{{trigger.title}}`, `{{trigger.link}}`, `{{trigger.description}}`, `{{trigger.summary}}`, `{{trigger.pubDate}}` |
| **Social Comment** | `channel_new_comment` | Triggers on new comments on a channel | `{{trigger.payload.text}}`, `{{trigger.payload.postId}}`, `{{trigger.payload.sentiment}}`, `{{trigger.commentId}}`, `{{trigger.channelId}}` |
| **Social Mention** | `channel_new_mention` | Triggers on new mentions/tags | `{{trigger.payload.text}}`, `{{trigger.payload.sourceUrl}}`, `{{trigger.mentionId}}`, `{{trigger.channelId}}` |
| **Conversation** | `channel_new_conversation_message` | Inbound DM / chat message | `{{trigger.payload.contentPreview}}`, `{{trigger.payload.senderId}}`, `{{trigger.payload.senderName}}`, `{{trigger.conversationId}}` |

> [!TIP]
>
> If using the `webhook` trigger, call `GET /api/v1/workflow/wkf_abc123/webhook` after setting the trigger to retrieve the unique public inbound URL (`https://posttu.com/api/workflows/wkf_abc123`).

***

### Step 4: Add Action Steps, Branches & Loops

Add execution steps to the draft canvas using `POST /api/v1/workflow/{id}/step`. Steps can be linear, placed inside conditional branches, or placed inside loop iterators.

#### 1. Linear Action Step (AI Text Completion)

`ai_ask_ai` accepts `prompt` (required), optional `systemPrompt`, `inputText`, `creativity`, `maxRetries`, and `continueOnFail`, and returns `{ text, usage, finishReason }`:

```bash theme={null}
curl -X POST "https://posttu.com/api/v1/workflow/wkf_abc123/step" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "ai_ask_ai",
    "displayName": "Generate Tweet Summary",
    "settings": {
      "prompt": "Summarize this article into a compelling 280-character post.",
      "inputText": "{{trigger.description}}"
    }
  }'
```

#### 2. Social Platform Post Action (`channel`) vs Third-Party Integrations (`__connectionId`)

* **Posttu social publishing actions** (e.g. `x_create_post`) take a connected Posttu social `channel` ID (from `GET /api/v1/channels/list`).
* **Third-party piece actions** requiring external OAuth/API credentials (e.g. Gmail, Notion, HubSpot) pass `"__connectionId"` from `GET /api/v1/workflow/connections`.

```bash theme={null}
curl -X POST "https://posttu.com/api/v1/workflow/wkf_abc123/step" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "x_create_post",
    "displayName": "Post to X",
    "afterStepId": "step_789xyz",
    "settings": {
      "channel": "ch_x_456",
      "text": "{{steps.step_789xyz.text}}",
      "shouldPostImmediately": true
    }
  }'
```

#### 3. Conditional Router Step (`condition`)

The condition router splits flow execution into branches:

```bash theme={null}
curl -X POST "https://posttu.com/api/v1/workflow/wkf_abc123/step" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "condition",
    "displayName": "Evaluate Priority",
    "settings": {
      "branches": {
        "branches": [
          {
            "id": "branch_urgent",
            "name": "Urgent Alert",
            "conditions": {
              "operator": "AND",
              "conditions": [
                {
                  "field": "trigger.body.priority",
                  "operator": "TEXT_EXACTLY_MATCHES",
                  "value": "urgent"
                }
              ]
            }
          },
          {
            "id": "otherwise",
            "name": "Otherwise",
            "conditions": {
              "operator": "AND",
              "conditions": []
            }
          }
        ],
        "defaultBranchId": "otherwise"
      },
      "evaluateAll": false,
      "combineStrategy": "KEYED_OBJECT"
    }
  }'
```

> [!IMPORTANT]
>
> **Condition Router Field Syntax**: In `condition.field`, provide the raw dot-path string (e.g. `"trigger.body.priority"`, `"steps.step_1.status"`). Avoid wrapping `field` in `{{...}}`.

#### 4. Adding Steps Inside a Condition Branch

To place an action node inside a specific branch, set `parentStepId` to the condition step's ID, and set `branchId` to the branch's ID:

```bash theme={null}
curl -X POST "https://posttu.com/api/v1/workflow/wkf_abc123/step" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "slack_send_channel_message",
    "displayName": "Send Urgent Slack Alert",
    "parentStepId": "step_cond_123",
    "branchId": "branch_urgent",
    "settings": {
      "channel": "C0123456789",
      "text": "Urgent incident detected: {{trigger.body.message}}"
    }
  }'
```

#### 5. Loop Iteration Step (`loop`)

To iterate over a list of items:

```bash theme={null}
curl -X POST "https://posttu.com/api/v1/workflow/wkf_abc123/step" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "loop",
    "displayName": "Loop Over Posts",
    "settings": {
      "items": "{{trigger.body.posts}}",
      "itemVariableName": "item"
    }
  }'
```

Inside the loop body, child steps use `parentStepId: "<loop_step_id>"` and access current item properties via `{{loop.item.property}}` and `{{loop.index}}`.

***

### Step 5: Test Workflow Draft

Run an isolated test execution against the draft version to verify parameter resolution and output values. `triggerPayload` becomes the root `trigger` object (so for `webhook` triggers that reference `trigger.body.*`, wrap fields inside `"body"`):

```bash theme={null}
# 1. Trigger a test run with sample payload
curl -X POST "https://posttu.com/api/v1/workflow/wkf_abc123/test" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "triggerPayload": {
      "body": {
        "priority": "urgent",
        "message": "Production alert spike"
      }
    }
  }'

# 2. Inspect step outputs and execution logs
curl "https://posttu.com/api/v1/workflow/runs/run_xyz789" \
  -H "Authorization: Bearer YOUR_API_KEY"
```

***

### Step 6: Publish Draft (and Pause / Re-Activate)

Publishing a draft creates an immutable release version **and automatically activates** production schedules and event listeners. Use `/active` afterwards to pause (`isActive: false`) or re-activate (`isActive: true`) a published workflow:

```bash theme={null}
# 1. Publish the draft version (promotes snapshot AND activates production triggers)
curl -X POST "https://posttu.com/api/v1/workflow/wkf_abc123/publish" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "note": "Initial production launch" }'

# 2. Optional: Pause or re-activate an already-published workflow
curl -X POST "https://posttu.com/api/v1/workflow/wkf_abc123/active" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "isActive": false }'
```

***

## 🔤 Dynamic Expression Syntax & Convergence

Step settings support Mustache template expressions to pass data between nodes.

### Expression Namespaces

| Namespace | Example | Description |
| - | - | - |
| **Trigger Payload** | `{{trigger.body.text}}` | Data passed by the starter trigger |
| **Step Output** | `{{steps.step_1.body}}` | Output property from a preceding action node |
| **Condition Convergence** | `{{steps.cond_1.mergedData.branch_urgent}}` | Aggregated output of branch execution after condition converges |
| **Loop Context** | `{{loop.item.title}}`, `{{loop.index}}` | Current item and 0-based index inside a loop container |
| **Variables** | `{{variables.my_key}}` | Organization or workflow environment variables |

### Branch Convergence Output (`mergedData`)

When a `condition` router finishes executing its matching branches, the outputs from all branches converge into the condition step's output under `mergedData`:

* **`KEYED_OBJECT`** (Default): Access branch results via `{{steps.<condition_id>.mergedData.<branchId>}}`.
* **`ARRAY`**: Access branch results by array index via `{{steps.<condition_id>.mergedData[0]}}`.
* **`DEEP_MERGE`**: Access combined object properties via `{{steps.<condition_id>.mergedData.<field>}}`.

***

## 📋 Complete Blueprint: Inbound Webhook to Router & Platform Post

Below is a complete multi-step blueprint demonstrating webhook triggers, condition branching, and downstream execution:

```bash theme={null}
# 1. Create Workflow Container
WORKFLOW_ID=$(curl -s -X POST "https://posttu.com/api/v1/workflow" \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"name": "Alert Automation", "description": "Routes alerts based on priority"}' | jq -r '.data.id')

# 2. Configure Webhook Starter Trigger
curl -s -X POST "https://posttu.com/api/v1/workflow/$WORKFLOW_ID/trigger" \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"name": "webhook", "displayName": "Inbound Webhook", "settings": {}}'

# 3. Add Condition Router Step
COND_ID=$(curl -s -X POST "https://posttu.com/api/v1/workflow/$WORKFLOW_ID/step" \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "condition",
    "displayName": "Check Severity",
    "settings": {
      "branches": {
        "branches": [
          {
            "id": "critical",
            "name": "Critical Alerts",
            "conditions": {
              "operator": "AND",
              "conditions": [
                {
                  "field": "trigger.body.severity",
                  "operator": "TEXT_EXACTLY_MATCHES",
                  "value": "CRITICAL"
                }
              ]
            }
          },
          {
            "id": "otherwise",
            "name": "Otherwise",
            "conditions": { "operator": "AND", "conditions": [] }
          }
        ],
        "defaultBranchId": "otherwise"
      },
      "evaluateAll": false
    }
  }' | jq -r '.data.id')

# 4. Add Step inside Critical Branch
curl -s -X POST "https://posttu.com/api/v1/workflow/$WORKFLOW_ID/step" \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d "{
    \"name\": \"x_create_post\",
    \"displayName\": \"Post Incident to Status Feed\",
    \"parentStepId\": \"$COND_ID\",
    \"branchId\": \"critical\",
    \"settings\": {
      \"channel\": \"ch_status_feed\",
      \"text\": \"Service Alert: {{trigger.body.summary}}\",
      \"shouldPostImmediately\": true
    }
  }"

# 5. Publish (creates immutable release snapshot and activates triggers)
curl -s -X POST "https://posttu.com/api/v1/workflow/$WORKFLOW_ID/publish" \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"note": "V1 release"}'
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.