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

# Workflows

> Create and manage automated workflows based on API traffic patterns

## Create Workflow

<api-endpoint method="POST" url="https://api.apitraffic.io/v1/accounts/{accountSid}/environments/{environmentSid}/buckets/{bucketSid}/workflows" />

Create a new automated workflow that triggers based on API traffic patterns and conditions.

### Path Parameters

<ParamField path="accountSid" type="string" required>
  Account identifier (format: `acc_` followed by 27 alphanumeric characters)
</ParamField>

<ParamField path="environmentSid" type="string" required>
  Environment identifier (6 character alphanumeric)
</ParamField>

<ParamField path="bucketSid" type="string" required>
  Bucket identifier
</ParamField>

### Headers

<ParamField header="Authorization" type="string" required>
  Bearer token for authentication
</ParamField>

### Request Body

<ParamField body="name" type="string" required>
  Name of the workflow
</ParamField>

<ParamField body="description" type="string">
  Description of what this workflow does
</ParamField>

<ParamField body="trigger" type="object" required>
  <Expandable title="Trigger Configuration">
    <ParamField body="type" type="string" required>
      Trigger type: `request`, `error`, `threshold`, `schedule`
    </ParamField>

    <ParamField body="conditions" type="array">
      Array of conditions that must be met to trigger the workflow
    </ParamField>

    <ParamField body="schedule" type="string">
      Cron expression for scheduled workflows (required if type is `schedule`)
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="actions" type="array" required>
  <Expandable title="Workflow Actions">
    <ParamField body="type" type="string" required>
      Action type: `webhook`, `email`, `slack`, `activepieces`
    </ParamField>

    <ParamField body="config" type="object" required>
      Configuration specific to the action type
    </ParamField>

    <ParamField body="order" type="number">
      Execution order for this action (default: 0)
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="isActive" type="boolean">
  Whether this workflow should be active (default: true)
</ParamField>

### Response

<ResponseField name="sid" type="string">
  Unique workflow identifier
</ResponseField>

<ResponseField name="accountSid" type="string">
  Account identifier this workflow belongs to
</ResponseField>

<ResponseField name="environmentSid" type="string">
  Environment identifier
</ResponseField>

<ResponseField name="bucketSid" type="string">
  Bucket identifier this workflow is associated with
</ResponseField>

<ResponseField name="name" type="string">
  Name of the workflow
</ResponseField>

<ResponseField name="description" type="string">
  Description of the workflow
</ResponseField>

<ResponseField name="trigger" type="object">
  Trigger configuration
</ResponseField>

<ResponseField name="actions" type="array">
  Array of workflow actions
</ResponseField>

<ResponseField name="isActive" type="boolean">
  Whether the workflow is currently active
</ResponseField>

<ResponseField name="createdAt" type="string">
  ISO 8601 timestamp of workflow creation
</ResponseField>

<RequestExample>
  ```bash cURL theme={null}
  curl -X POST "https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/environments/env123/buckets/bkt_xyz789uvw012rst345abc/workflows" \
    -H "Authorization: Bearer your-jwt-token" \
    -H "Content-Type: application/json" \
    -d '{
      "name": "Error Alert Workflow",
      "description": "Send Slack notification when error rate exceeds 5%",
      "trigger": {
        "type": "threshold",
        "conditions": [
          {
            "metric": "error_rate",
            "operator": "greater_than",
            "value": 5,
            "timeWindow": "5m"
          }
        ]
      },
      "actions": [
        {
          "type": "slack",
          "config": {
            "webhook_url": "https://hooks.slack.com/services/...",
            "channel": "#alerts",
            "message": "🚨 Error rate exceeded 5% in {{bucket.name}}"
          },
          "order": 1
        }
      ],
      "isActive": true
    }'
  ```

  ```javascript Node.js theme={null}
  const response = await fetch('https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/environments/env123/buckets/bkt_xyz789uvw012rst345abc/workflows', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer your-jwt-token',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      name: 'Error Alert Workflow',
      description: 'Send Slack notification when error rate exceeds 5%',
      trigger: {
        type: 'threshold',
        conditions: [
          {
            metric: 'error_rate',
            operator: 'greater_than',
            value: 5,
            timeWindow: '5m'
          }
        ]
      },
      actions: [
        {
          type: 'slack',
          config: {
            webhook_url: 'https://hooks.slack.com/services/...',
            channel: '#alerts',
            message: '🚨 Error rate exceeded 5% in {{bucket.name}}'
          },
          order: 1
        }
      ],
      isActive: true
    })
  });

  const workflow = await response.json();
  console.log(workflow);
  ```

  ```python Python theme={null}
  import requests

  response = requests.post(
      'https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/environments/env123/buckets/bkt_xyz789uvw012rst345abc/workflows',
      headers={
          'Authorization': 'Bearer your-jwt-token',
          'Content-Type': 'application/json'
      },
      json={
          'name': 'Error Alert Workflow',
          'description': 'Send Slack notification when error rate exceeds 5%',
          'trigger': {
              'type': 'threshold',
              'conditions': [
                  {
                      'metric': 'error_rate',
                      'operator': 'greater_than',
                      'value': 5,
                      'timeWindow': '5m'
                  }
              ]
          },
          'actions': [
              {
                  'type': 'slack',
                  'config': {
                      'webhook_url': 'https://hooks.slack.com/services/...',
                      'channel': '#alerts',
                      'message': '🚨 Error rate exceeded 5% in {{bucket.name}}'
                  },
                  'order': 1
              }
          ],
          'isActive': True
      }
  )

  workflow = response.json()
  print(workflow)
  ```
</RequestExample>

<ResponseExample>
  ```json Response theme={null}
  {
    "sid": "wfl_abc123def456ghi789jkl012",
    "accountSid": "acc_abc123def456ghi789jkl012",
    "environmentSid": "env123",
    "bucketSid": "bkt_xyz789uvw012rst345abc",
    "name": "Error Alert Workflow",
    "description": "Send Slack notification when error rate exceeds 5%",
    "trigger": {
      "type": "threshold",
      "conditions": [
        {
          "metric": "error_rate",
          "operator": "greater_than",
          "value": 5,
          "timeWindow": "5m"
        }
      ]
    },
    "actions": [
      {
        "type": "slack",
        "config": {
          "webhook_url": "https://hooks.slack.com/services/...",
          "channel": "#alerts",
          "message": "🚨 Error rate exceeded 5% in {{bucket.name}}"
        },
        "order": 1
      }
    ],
    "isActive": true,
    "createdAt": "2023-12-01T15:45:00.000Z"
  }
  ```
</ResponseExample>

***

## Workflow Trigger Types

### Request Trigger

Triggers when specific requests are made to your API.

```json theme={null}
{
  "type": "request",
  "conditions": [
    {
      "path": "/api/users",
      "method": "POST",
      "statusCode": 201
    }
  ]
}
```

### Error Trigger

Triggers when errors occur in your API.

```json theme={null}
{
  "type": "error",
  "conditions": [
    {
      "statusCode": 500,
      "path": "/api/*"
    }
  ]
}
```

### Threshold Trigger

Triggers when metrics cross specified thresholds.

```json theme={null}
{
  "type": "threshold",
  "conditions": [
    {
      "metric": "response_time",
      "operator": "greater_than",
      "value": 1000,
      "timeWindow": "5m"
    }
  ]
}
```

### Schedule Trigger

Triggers on a scheduled basis using cron expressions.

```json theme={null}
{
  "type": "schedule",
  "schedule": "0 9 * * MON-FRI"
}
```

***

## Workflow Action Types

### Webhook Action

Send HTTP requests to external services.

```json theme={null}
{
  "type": "webhook",
  "config": {
    "url": "https://api.example.com/webhook",
    "method": "POST",
    "headers": {
      "Authorization": "Bearer token"
    },
    "body": {
      "message": "Alert from ApiTraffic",
      "data": "{{request.body}}"
    }
  }
}
```

### Email Action

Send email notifications.

```json theme={null}
{
  "type": "email",
  "config": {
    "to": ["admin@example.com"],
    "subject": "API Alert: {{trigger.type}}",
    "body": "An alert was triggered in bucket {{bucket.name}}"
  }
}
```

### Slack Action

Send messages to Slack channels.

```json theme={null}
{
  "type": "slack",
  "config": {
    "webhook_url": "https://hooks.slack.com/services/...",
    "channel": "#alerts",
    "message": "🚨 {{trigger.message}}",
    "username": "ApiTraffic Bot"
  }
}
```

### ActivePieces Action

Trigger ActivePieces workflows for complex automation.

```json theme={null}
{
  "type": "activepieces",
  "config": {
    "flow_id": "flow_abc123",
    "webhook_url": "https://flow.apitraffic.io/webhook/...",
    "data": {
      "request": "{{request}}",
      "response": "{{response}}"
    }
  }
}
```

***

## Template Variables

Workflows support template variables that are dynamically replaced with actual values:

### Request Variables

* `{{request.method}}` - HTTP method
* `{{request.path}}` - Request path
* `{{request.headers}}` - Request headers
* `{{request.body}}` - Request body
* `{{request.query}}` - Query parameters

### Response Variables

* `{{response.statusCode}}` - HTTP status code
* `{{response.headers}}` - Response headers
* `{{response.body}}` - Response body
* `{{response.size}}` - Response size in bytes

### Timing Variables

* `{{timings.duration}}` - Total request duration
* `{{timings.responseTime}}` - Response time

### Context Variables

* `{{bucket.name}}` - Bucket name
* `{{bucket.sid}}` - Bucket ID
* `{{account.name}}` - Account name
* `{{environment.name}}` - Environment name

### Metric Variables (for threshold triggers)

* `{{metric.value}}` - Current metric value
* `{{metric.threshold}}` - Configured threshold
* `{{metric.timeWindow}}` - Time window for the metric

***

## Common Workflow Examples

### High Error Rate Alert

```json theme={null}
{
  "name": "High Error Rate Alert",
  "trigger": {
    "type": "threshold",
    "conditions": [
      {
        "metric": "error_rate",
        "operator": "greater_than",
        "value": 10,
        "timeWindow": "5m"
      }
    ]
  },
  "actions": [
    {
      "type": "slack",
      "config": {
        "message": "🚨 Error rate is {{metric.value}}% in {{bucket.name}}"
      }
    }
  ]
}
```

### Slow Response Alert

```json theme={null}
{
  "name": "Slow Response Alert",
  "trigger": {
    "type": "threshold",
    "conditions": [
      {
        "metric": "avg_response_time",
        "operator": "greater_than",
        "value": 2000,
        "timeWindow": "10m"
      }
    ]
  },
  "actions": [
    {
      "type": "email",
      "config": {
        "subject": "Slow API Performance Alert",
        "body": "Average response time is {{metric.value}}ms"
      }
    }
  ]
}
```

### New User Registration

```json theme={null}
{
  "name": "New User Registration",
  "trigger": {
    "type": "request",
    "conditions": [
      {
        "path": "/api/users",
        "method": "POST",
        "statusCode": 201
      }
    ]
  },
  "actions": [
    {
      "type": "webhook",
      "config": {
        "url": "https://crm.example.com/webhook",
        "body": {
          "event": "user_registered",
          "user_data": "{{request.body}}"
        }
      }
    }
  ]
}
```

### Daily Summary Report

```json theme={null}
{
  "name": "Daily Summary Report",
  "trigger": {
    "type": "schedule",
    "schedule": "0 9 * * *"
  },
  "actions": [
    {
      "type": "email",
      "config": {
        "subject": "Daily API Summary for {{bucket.name}}",
        "body": "Your daily API traffic summary is ready."
      }
    }
  ]
}
```
