Workflows API
Workflows are automated multi-step processes that execute a series of connected tools and functions. This guide covers how to list and execute workflows via the API.
Overview
A workflow consists of:
- Nodes: Individual steps (tools/functions) in the workflow
- Edges: Connections that pass data between nodes
- Config: Execution settings like timeouts and retries
List Workflows
Returns a list of all workflows accessible to the authenticated user.
Endpoint
GET /api/agent/workflows
Parameters
| Parameter | Type | Description |
|---|---|---|
| search | string | Filter by name or description |
| limit | integer | Max results (default: 50) |
| offset | integer | Pagination offset |
Example
bash
curl -X GET "http://kaman.ai/api/agent/workflows?search=sales&limit=10" \
-H "Authorization: Bearer kam_your_api_key"
Response
json
[
{
"id": 123,
"name": "Sales Report Generator",
"description": "Generates monthly sales reports",
"created_at": "2024-01-15T10:30:00Z"
},
{
"id": 124,
"name": "Customer Data Sync",
"description": "Syncs customer data from CRM",
"created_at": "2024-01-10T08:00:00Z"
}
]
Execute a Workflow
Triggers execution of the specified workflow with the provided inputs. The workflow will execute all nodes in the defined order, passing data between nodes according to the edge mappings.
Endpoint
POST /api/agent/workflows/{id}/execute
Path Parameters
| Parameter | Type | Description |
|---|---|---|
| id | integer | Workflow ID to execute |
Request Body
The request body should contain the input values required by the workflow's starting nodes.
bash
curl -X POST "http://kaman.ai/api/agent/workflows/123/execute" \
-H "Authorization: Bearer kam_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"inputs": {
"startDate": "2024-01-01",
"endDate": "2024-12-31",
"region": "APAC"
}
}'
Response (Success)
json
{
"runId": "wf_123:550e8400-e29b-41d4-a716-446655440000",
"status": "completed",
"result": {
"report": {
"totalSales": 1250000,
"growth": 15.3
}
},
"executedNodes": ["fetch_data", "process", "generate_report"],
"duration": 3450
}
Response (Human Input Needed)
Some workflows may pause to request human input:
json
{
"error": "Human input needed",
"fieldsNeeded": ["approvalDecision", "comments"],
"instanceId": "wf_123:abc123"
}
Resuming an Interrupted Workflow
To continue a workflow that requested human input, include the instanceId:
bash
curl -X POST "http://kaman.ai/api/agent/workflows/123/execute" \
-H "Authorization: Bearer kam_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"instanceId": "wf_123:abc123",
"inputs": {
"approvalDecision": "approved",
"comments": "Looks good"
}
}'
Code Examples
TypeScript
typescript
const API_KEY = process.env.KAMAN_API_KEY;
const BASE_URL = 'http://kaman.ai';
// List workflows
async function listWorkflows(search?: string) {
const params = search ? `?search=${encodeURIComponent(search)}` : '';
const response = await fetch(`${BASE_URL}/api/agent/workflows${params}`, {
headers: {
'Authorization': `Bearer ${API_KEY}`
}
});
return response.json();
}
// Execute a workflow
async function executeWorkflow(
workflowId: number,
inputs: Record<string, any>,
instanceId?: string
) {
const response = await fetch(
`${BASE_URL}/api/agent/workflows/${workflowId}/execute`,
{
method: 'POST',
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ inputs, instanceId })
}
);
const result = await response.json();
if (result.error === 'Human input needed') {
console.log('Workflow needs human input:', result.fieldsNeeded);
return { needsInput: true, ...result };
}
return result;
}
// Example usage
const workflows = await listWorkflows('sales');
const result = await executeWorkflow(123, {
startDate: '2024-01-01',
endDate: '2024-12-31'
});
Python
python
import requests
import os
from typing import Optional, Dict, Any, List
class KamanWorkflows:
def __init__(self, base_url: str):
self.base_url = f'{base_url}/api/agent'
self.headers = {
'Authorization': f'Bearer {os.getenv("KAMAN_API_KEY")}',
'Content-Type': 'application/json'
}
def list_workflows(self, search: Optional[str] = None, limit: int = 50) -> List[Dict]:
params = {'limit': limit}
if search:
params['search'] = search
response = requests.get(
f'{self.base_url}/workflows',
params=params,
headers=self.headers
)
return response.json()
def execute_workflow(
self,
workflow_id: int,
inputs: Dict[str, Any],
instance_id: Optional[str] = None
) -> Dict[str, Any]:
payload = {'inputs': inputs}
if instance_id:
payload['instanceId'] = instance_id
response = requests.post(
f'{self.base_url}/workflows/{workflow_id}/execute',
json=payload,
headers=self.headers
)
result = response.json()
if result.get('error') == 'Human input needed':
print(f'Workflow needs input: {result["fieldsNeeded"]}')
return {'needs_input': True, **result}
return result
# Example usage
client = KamanWorkflows('http://kaman.ai')
# List workflows
workflows = client.list_workflows(search='sales')
# Execute a workflow
result = client.execute_workflow(123, {
'startDate': '2024-01-01',
'endDate': '2024-12-31'
})
Error Handling
Common Errors
| Status | Error | Description |
|---|---|---|
| 400 | Human input needed | Workflow requires additional inputs (see fieldsNeeded) |
| 400 | Invalid inputs | Missing required input fields |
| 401 | Unauthorized | Invalid or missing authentication |
| 404 | Workflow not found | Invalid workflow ID |
| 500 | Execution failed | Error during workflow execution |
Error Response
json
{
"error": "Workflow execution failed",
"details": "Node 'fetch_data' failed: Connection timeout",
"runId": "wf_123:abc123"
}
Best Practices
- Handle Interrupts: Implement handlers for human-in-the-loop workflows
- Store Instance IDs: Save the
instanceIdwhen a workflow needs input so you can resume later - Set Timeouts: Configure appropriate timeouts on your HTTP client for long-running workflows
- Retry Failed Runs: Implement retry logic for transient failures
Next Steps
- Authentication - Learn about API authentication
- KDL API - Query data from your data lake
- Getting Started - Quick start guide