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

# Initiate Workflow (Flexible)

> Start a new workflow task instance with flexible key-value pairs and automatic type detection

## Endpoint

```
POST /workflows/{workflow_id}/{version}/initiate-flexible
```

## Authentication

This endpoint requires authentication via API key. Include your API key in the `X-API-Key` header:

```bash theme={null}
X-API-Key: ca_your_api_key_here
```

## Path Parameters

| Parameter     | Type   | Required | Description                                                        |
| ------------- | ------ | -------- | ------------------------------------------------------------------ |
| `workflow_id` | string | Yes      | Unique identifier for the workflow                                 |
| `version`     | string | Yes      | Version number (e.g., "1") or "latest" for the most recent version |

## Request Body

The request body must be a JSON object with the following fields:

### Required Fields

| Field        | Type  | Description                                                       |
| ------------ | ----- | ----------------------------------------------------------------- |
| `attributes` | array | List of simple key-value pairs for workflow variables (see below) |

### Optional Fields

| Field      | Type   | Description                                                                                                     |
| ---------- | ------ | --------------------------------------------------------------------------------------------------------------- |
| `files`    | array  | List of files with base64 content (see File Format below)                                                       |
| `user`     | string | Email address of the user initiating the workflow. If not provided, workflow is attributed to the API key owner |
| `metadata` | object | Optional key-value pairs (accepted but currently ignored)                                                       |

### Attribute Format

Each attribute is a simple object with `key` and `value` fields:

```json theme={null}
{
  "key": "vendor_name",
  "value": "Acme Corporation"
}
```

The system will match attributes to workflow variables using flexible matching:

1. Exact match by variable ID
2. Case-insensitive match by variable title
3. Normalized match (lowercase, spaces/underscores/hyphens ignored)

<Info>
  All values are provided as strings. The system will automatically convert them to the appropriate type based on the workflow schema.
</Info>

### File Format

Files are provided separately from attributes:

```json theme={null}
{
  "filename": "contract.pdf",
  "base64_content": "JVBERi0xLjQKJeLjz9MK..."
}
```

<Warning>
  Files are matched to file-type workflow fields by order. Ensure files in the array correspond to the order of file fields in your workflow.
</Warning>

## When to Use This Endpoint

This endpoint is designed for scenarios where the integrating system or user **cannot maintain variable-specific mapping and control**. Use this endpoint when:

* **Generic integration systems** that handle multiple workflows without custom configuration for each
* **Low-code/no-code platforms** where users configure integrations through UI without coding
* **Form builders** that generate dynamic field mappings based on workflow schemas
* **Third-party tools** that need to integrate with workflows but can't be customized for each workflow's schema
* **Rapid prototyping** where you want to test workflows without setting up precise type mappings
* **Simple scripts** where maintaining detailed variable schemas adds unnecessary complexity

The flexible matching (by ID, title, or normalized name) means integrating systems can use human-readable labels without knowing the exact internal variable IDs.

<Info>
  If your integration requires precise control over variable types, file references, or needs to distinguish between fields with similar names, use the standard [Initiate Workflow](/api-reference/endpoint/workflows/initiate) endpoint instead.
</Info>

## Request Example

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://platform.chamelio.ai/workflows/vendor_contract_review/latest/initiate-flexible" \
    -H "X-API-Key: ca_your_api_key_here" \
    -H "Content-Type: application/json" \
    -d '{
      "attributes": [
        {
          "key": "vendor_name",
          "value": "Acme Corporation"
        },
        {
          "key": "contract_value",
          "value": "150000.00"
        },
        {
          "key": "reviewer_email",
          "value": "legal@example.com"
        },
        {
          "key": "urgent",
          "value": "true"
        }
      ],
      "files": [
        {
          "filename": "acme_contract.pdf",
          "base64_content": "JVBERi0xLjQKJeLjz9MK..."
        }
      ],
      "user": "john.doe@example.com"
    }'
  ```

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

  workflow_id = "vendor_contract_review"
  version = "latest"

  # Read and encode file
  with open("acme_contract.pdf", "rb") as f:
      file_content = base64.b64encode(f.read()).decode('utf-8')

  url = f"https://platform.chamelio.ai/workflows/{workflow_id}/{version}/initiate-flexible"
  headers = {
      "X-API-Key": "ca_your_api_key_here",
      "Content-Type": "application/json"
  }

  payload = {
      "attributes": [
          {
              "key": "vendor_name",
              "value": "Acme Corporation"
          },
          {
              "key": "contract_value",
              "value": "150000.00"
          },
          {
              "key": "reviewer_email",
              "value": "legal@example.com"
          }
      ],
      "files": [
          {
              "filename": "acme_contract.pdf",
              "base64_content": file_content
          }
      ],
      "user": "john.doe@example.com"
  }

  response = requests.post(url, json=payload, headers=headers)
  print(response.json())
  ```

  ```javascript JavaScript theme={null}
  const workflowId = 'vendor_contract_review';
  const version = 'latest';

  // Convert file to base64
  const fileToBase64 = (file) => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result.split(',')[1]);
      reader.onerror = error => reject(error);
    });
  };

  // Assuming you have a File object
  const base64Content = await fileToBase64(fileObject);

  const response = await fetch(
    `https://platform.chamelio.ai/workflows/${workflowId}/${version}/initiate-flexible`,
    {
      method: 'POST',
      headers: {
        'X-API-Key': 'ca_your_api_key_here',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        attributes: [
          {
            key: 'vendor_name',
            value: 'Acme Corporation'
          },
          {
            key: 'contract_value',
            value: '150000.00'
          },
          {
            key: 'reviewer_email',
            value: 'legal@example.com'
          }
        ],
        files: [
          {
            filename: 'acme_contract.pdf',
            base64_content: base64Content
          }
        ],
        user: 'john.doe@example.com'
      })
    }
  );

  const data = await response.json();
  console.log(data);
  ```
</CodeGroup>

## Response

### Success Response

**Status Code:** `200 OK`

```json theme={null}
{
  "task_id": 12345,
  "workflow_state_id": "wfs_abc123xyz",
  "workflow_id": "vendor_contract_review",
  "version": 1,
  "status": "in_progress",
  "message": "Workflow initiated successfully"
}
```

### Response Fields

| Field               | Type    | Description                                                           |
| ------------------- | ------- | --------------------------------------------------------------------- |
| `task_id`           | integer | Unique identifier for the created task. Use this to track task status |
| `workflow_state_id` | string  | Internal workflow state identifier                                    |
| `workflow_id`       | string  | Workflow identifier that was initiated                                |
| `version`           | integer | Workflow version number that was used                                 |
| `status`            | string  | Initial task status (typically `"in_progress"` or `"pending"`)        |
| `message`           | string  | Success confirmation message                                          |

## Error Responses

### 400 Bad Request

Returned when the version format is invalid, request structure is malformed, or attribute matching fails.

```json theme={null}
{
  "detail": "Could not match attribute 'invalid_key' to any workflow variable"
}
```

### 401 Unauthorized

Returned when authentication fails. See the [authentication errors](/api-reference/introduction#authentication-errors) section for details.

```json theme={null}
{
  "detail": "Invalid API key"
}
```

### 404 Not Found

Returned when the workflow or version doesn't exist.

```json theme={null}
{
  "detail": "Workflow not found"
}
```

### 422 Validation Error

Returned when the request body is invalid or required variables are missing.

```json theme={null}
{
  "detail": [
    {
      "loc": ["body", "attributes"],
      "msg": "field required",
      "type": "value_error.missing"
    }
  ]
}
```

### 500 Internal Server Error

Returned when workflow initiation fails due to a server error.

```json theme={null}
{
  "detail": "Failed to initiate workflow"
}
```

## Comparison with `/initiate`

| Aspect             | `/initiate`                        | `/initiate-flexible`                      |
| ------------------ | ---------------------------------- | ----------------------------------------- |
| Input format       | Typed `InputValue` objects         | Simple `{key, value}` pairs               |
| Variable matching  | Exact `variable_id` only           | Flexible: ID → title → normalized         |
| File handling      | Requires `file_id` or typed object | Base64 content, matched by order          |
| Type specification | Explicit `type` field required     | Auto-detected from schema                 |
| Use case           | Precise control, file references   | Systems without variable-specific mapping |

## Notes

<Info>
  Save the `task_id` from the response to track the workflow's progress using the [Get Task](/api-reference/endpoint/tasks/get) endpoint.
</Info>

<Tip>
  Use flexible attribute keys: "Vendor Name", "vendor\_name", and "vendor-name" will all match the same variable.
</Tip>

<Warning>
  Files in the `files` array are matched to workflow file fields by position. The first file in the array is assigned to the first file field in the workflow, and so on.
</Warning>

## Use Cases

This flexible endpoint is ideal for:

* **Generic integration platforms** - iPaaS solutions (Zapier, Make, Workato) that connect to multiple workflows without per-workflow configuration
* **Form builders** - Dynamic forms that adapt to workflow schemas without hardcoded field mappings
* **No-code tools** - Platforms where users configure integrations visually without access to variable IDs
* **Multi-tenant systems** - Applications serving multiple organizations with different workflow schemas
* **API aggregators** - Services that normalize data from various sources before initiating workflows
* **Rapid prototyping** - Quick testing without setting up precise variable mappings
* **Simple scripts** - Automation where maintaining detailed schemas is unnecessary overhead

**Key advantage**: Integrating systems don't need to maintain a mapping table between their field names and Chamelio's internal variable IDs. They can use human-readable labels directly.

For precise control over variable types, file references, or when you need to distinguish between similarly-named fields, use the standard [Initiate Workflow](/api-reference/endpoint/workflows/initiate) endpoint.
