# Execute workflows

Send a `steps` array and a `context` object to the Workflow API. Steps run in order and add named outputs to context. The API returns those outputs, or the custom response from a [Respond step](/docs/respond).

## Endpoint

```
POST https://newprd.reecall.io/workflows/execute
```

## Authentication

Send your [API key](/docs/authentication) in the `Authorization` header:

```bash
Authorization: Bearer sk_YOUR_API_KEY
```

## Request format

### Headers

```
Content-Type: application/json
Authorization: Bearer sk_YOUR_API_KEY
```

### Body structure

```jsonc
{
  "steps": [
    // Array of workflow steps to execute
  ],
  "context": {
    // Initial data/variables for the workflow
  },
}
```

### Execution options

The optional `options` object accepts:

| Field | Type | Default | Effect |
| --- | --- | --- | --- |
| `timeout` | Number, 1 to 30000 milliseconds | `30000` | Limits how long the endpoint waits for a response. It does not cancel operations already running. |
| `validateOnly` | Boolean | Execution runs when omitted | Skips execution and returns no step outputs. |

`validateOnly: true` skips execution. The current endpoint invokes validation but does not reject its returned validation errors, so a successful validate-only response does not establish that every step is valid.

## Basic example

### Simple API call + email

Replace the example API URL with your endpoint and use a Mailjet sender configured for your deployment. The Request step stores the response under `user_data`; the Email step reads the recipient and name from its `data` field.

```bash
curl --location 'https://newprd.reecall.io/workflows/execute' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer sk_YOUR_API_KEY' \
--data-raw '{
  "steps": [
    {
      "type": "request",
      "output": "user_data",
      "config": {
        "url": "https://api.example.com/users/{{ userId }}",
        "method": "GET"
      }
    },
    {
      "type": "email",
      "output": "email_sent",
      "config": {
        "to": "{{ user_data.data.email }}",
        "from": "noreply@company.com",
        "subject": "Hello {{ user_data.data.name }}!",
        "htmlPart": "<h1>Welcome!</h1>"
      }
    }
  ],
  "context": {
    "userId": "123"
  }
}'
```

## Response format

### Success response

Without a Respond step, the endpoint returns named top-level outputs and execution metadata. `duration` is in milliseconds; `stepsExecuted` counts top-level steps.

```json
{
  "success": true,
  "outputs": {
    "user_data": {
      "status": 200,
      "data": { "name": "Alice", "email": "alice@example.com" },
      "headers": {}
    },
    "email_sent": {
      "messageId": 123456789,
      "status": "success",
      "to": "alice@example.com"
    }
  },
  "duration": 1234,
  "stepsExecuted": 2,
  "metadata": {
    "startedAt": "2025-12-16T10:00:00.000Z",
    "completedAt": "2025-12-16T10:00:01.234Z"
  }
}
```

### Error response

```json
{
  "success": false,
  "error": {
    "code": "EXECUTION_ERROR",
    "message": "Error description"
  }
}
```

A Respond step returns its configured body directly, without the success envelope shown above. Generic step failures return HTTP 500 with `EXECUTION_ERROR`; request validation and template failures return HTTP 400 with `VALIDATION_ERROR` or `TEMPLATE_ERROR`. A failed Request step stops execution, so a later Rule or Respond cannot handle that failure unless a Batch captures it as data.

## Common patterns

### 1. Data enrichment

Fetch a user's profile and orders, then return both response bodies:

```json
{
  "steps": [
    {
      "type": "request",
      "output": "user",
      "config": {
        "url": "https://api.example.com/users/{{ userId }}",
        "method": "GET"
      }
    },
    {
      "type": "request",
      "output": "orders",
      "config": {
        "url": "https://api.example.com/users/{{ userId }}/orders",
        "method": "GET"
      }
    },
    {
      "type": "respond",
      "config": {
        "status": 200,
        "body": {
          "user": "{{ user.data }}",
          "orders": "{{ orders.data }}"
        }
      }
    }
  ],
  "context": {
    "userId": "123"
  }
}
```

### 2. AI analysis

Analyze text with AI and return structured results:

```json
{
  "steps": [
    {
      "type": "agent",
      "output": "analysis",
      "config": {
        "provider": "openai",
        "model": "gpt-4o-mini",
        "input": "{{ feedbackText }}",
        "outputSchema": {
          "type": "object",
          "properties": {
            "sentiment": { "type": "string" },
            "score": { "type": "number" }
          }
        }
      }
    },
    {
      "type": "respond",
      "config": {
        "status": 200,
        "body": {
          "sentiment": "{{ analysis.output.sentiment }}",
          "score": "{{ analysis.output.score }}"
        }
      }
    }
  ],
  "context": {
    "feedbackText": "This product is amazing! I love it."
  }
}
```

### 3. Conditional logic

Execute different steps based on conditions:

```json
{
  "steps": [
    {
      "type": "rule",
      "output": "notification",
      "config": {
        "rules": [
          {
            "conditions": [
              {
                "source": "orderTotal",
                "filter": "GREATER_THAN",
                "value": 100
              }
            ],
            "then": [
              {
                "type": "email",
                "output": "premium_email",
                "config": {
                  "to": "{{ customerEmail }}",
                  "from": "vip@company.com",
                  "subject": "Premium Order Confirmation",
                  "htmlPart": "<h1>Thank you for your premium order!</h1>"
                }
              }
            ]
          },
          {
            "then": [
              {
                "type": "email",
                "output": "standard_email",
                "config": {
                  "to": "{{ customerEmail }}",
                  "from": "orders@company.com",
                  "subject": "Order Confirmation",
                  "htmlPart": "<h1>Thank you for your order!</h1>"
                }
              }
            ]
          }
        ]
      }
    }
  ],
  "context": {
    "orderTotal": 150,
    "customerEmail": "customer@example.com"
  }
}
```

### 4. Batch processing

Fetch users, orders, and products in parallel. Each Batch child reads the same parent context and stores its result under `all_data`:

```json
{
  "steps": [
    {
      "type": "batch",
      "output": "all_data",
      "config": {
        "steps": [
          {
            "type": "request",
            "output": "users",
            "config": {
              "url": "https://api.example.com/users",
              "method": "GET"
            }
          },
          {
            "type": "request",
            "output": "orders",
            "config": {
              "url": "https://api.example.com/orders",
              "method": "GET"
            }
          },
          {
            "type": "request",
            "output": "products",
            "config": {
              "url": "https://api.example.com/products",
              "method": "GET"
            }
          }
        ],
        "mode": "all"
      }
    },
    {
      "type": "respond",
      "config": {
        "status": 200,
        "body": {
          "users": "{{ all_data.users.data }}",
          "orders": "{{ all_data.orders.data }}",
          "products": "{{ all_data.products.data }}"
        }
      }
    }
  ],
  "context": {}
}
```

### 5. Array iteration

Send an email to each recipient, one at a time. Each Map result contains the full iteration context, including the recipient and the email result:

```json
{
  "steps": [
    {
      "type": "map",
      "output": "sent_emails",
      "config": {
        "source": "recipients",
        "steps": [
          {
            "type": "email",
            "output": "email",
            "config": {
              "to": "{{ item.email }}",
              "from": "newsletter@company.com",
              "subject": "Hello {{ item.name }}!",
              "htmlPart": "<p>Hi {{ item.name }}, here's your personalized message.</p>"
            }
          }
        ]
      }
    }
  ],
  "context": {
    "recipients": [
      { "name": "Alice", "email": "alice@example.com" },
      { "name": "Bob", "email": "bob@example.com" },
      { "name": "Charlie", "email": "charlie@example.com" }
    ]
  }
}
```

## Key concepts

### Context

The `context` object supplies the workflow's initial data. Steps can access it with [Morpher templates](/docs/morpher):

* A field consisting only of `{{ variableName }}` preserves the value's type.
* Text surrounding a template, such as `Hello {{ name }}!`, produces a string.

Supply timestamps, request IDs, and calculated values in context when needed. They are not injected automatically. See [Context management](/docs/context-manipulation) for nested step scope and result paths.

### Step outputs

Each step with an `output` name adds its result to the context of its sequence. A later step with the same name replaces that value:

```jsonc
{
  "type": "request",
  "output": "user_data",  // Results available as {{ user_data.data }}
  "config": { ... }
}
```

### Template syntax

* **String interpolation**: `{{ user.name }}`
* **Typed values**: `{{ user.age }}` as the entire field
* **Nested access**: `{{ user.profile.address.city }}`
* **Helpers**: `{{ user.name | capitalize }}`
* **Branching**: Use a Rule step for comparisons; Morpher accepts paths and helper pipelines, not JavaScript expressions.

## Best practices

### 1. Use descriptive output names

Use names that identify the data, such as `customer_profile`. The snippets below show only the `output` field.

```jsonc
// ❌ Bad
{ "output": "data1" }

// ✅ Good
{ "output": "customer_profile" }
```

### 2. Structure your context

Group related configuration and input data. The API key below is a placeholder; supply real credentials at execution time and avoid returning them in responses.

```json
{
  "context": {
    "config": {
      "apiUrl": "https://api.example.com",
      "apiKey": "secret123"
    },
    "data": {
      "userId": "123",
      "orderId": "456"
    }
  }
}
```

### 3. Choose responses with rules

Request errors stop execution, so a later Rule cannot catch a failed HTTP call. This example branches on an available successful result. To collect failures as data, use Batch with `failFast: false` and inspect the child's `error` field.

This Rule is an incomplete step outline. Replace the success branch's `{...}` with your response body before execution.

```json
{
  "type": "rule",
  "config": {
    "rules": [
      {
        "conditions": [
          { "source": "api_call.status", "filter": "EQUALS", "value": 200 }
        ],
        "then": [
          { "type": "respond", "config": { "status": 200, "body": {...} } }
        ]
      },
      {
        "then": [
          { "type": "respond", "config": { "status": 500, "body": { "error": "API call failed" } } }
        ]
      }
    ]
  }
}
```

### 4. Test incrementally

Test one step and inspect its result with Respond before adding dependent steps. These fragments use `...` for configuration you must supply:

```jsonc
// Start simple
{
  "steps": [
    { "type": "request", "output": "data", "config": {...} },
    { "type": "respond", "config": { "body": { "debug": "{{ data }}" } } }
  ]
}

// Then add more steps
{
  "steps": [
    { "type": "request", "output": "data", "config": {...} },
    { "type": "agent", "output": "analysis", "config": {...} },
    { "type": "respond", "config": { "body": {...} } }
  ]
}
```
