DevelopmentWorkflows
Workflow API Usage
Workflow API Usage
Base URL
All workflow API endpoints are available at:
/api/workflow/{workflowName}
```typescript
## Endpoints
### POST `/api/workflow/{workflowName}`
Triggers a workflow execution.
#### Request
**Path Parameters:**
- `workflowName` (string, required): Name of the workflow to execute
**Headers:**
```typescript
Content-Type: application/json
```typescript
**Body:**
JSON object with workflow-specific input parameters.
#### Response
**Success (202 Accepted):**
```json
{
"success": true,
"runId": "run-abc123",
"workflowName": "send-email-received-ein"
}
```typescript
**Error (404 Not Found):**
```json
{
"success": false,
"error": "Workflow \"invalid-name\" not found"
}
```typescript
**Error (500 Internal Server Error):**
```json
{
"success": false,
"error": "Error message here"
}
```typescript
#### Example: Trigger send-email-received-ein
```bash
curl -X POST http://localhost:3000/api/workflow/send-email-received-ein \
-H "Content-Type: application/json" \
-d '{
"userId": "user-123",
"companyId": "company-456",
"organizationId": "org-789",
"email_action": "sf_formations_we_received_your_ein",
"recipient_name": "John Doe",
"recipients": ["john@example.com"],
"resource_id_ref": "a03c8c04-d1af-4eff-bd9d-4cba26bead0b",
"ccs": []
}'
```typescript
#### Example: Trigger send-welcome-email
```bash
curl -X POST http://localhost:3000/api/workflow/send-welcome-email \
-H "Content-Type: application/json" \
-d '{
"userId": "user-123"
}'
```typescript
### GET `/api/workflow/{workflowName}`
Retrieves the status of a workflow execution.
#### Request
**Path Parameters:**
- `workflowName` (string, required): Name of the workflow
**Query Parameters:**
- `runId` (string, required): The workflow run ID returned from POST request
#### Response
**Success (200 OK):**
```json
{
"success": true,
"runId": "run-abc123",
"workflowName": "send-email-received-ein",
"status": "completed",
"result": {
"result": {
"message": "Email sent successfully"
}
},
"error": null,
"createdAt": "2024-01-15T10:30:00Z",
"updatedAt": "2024-01-15T10:30:05Z"
}
```typescript
**Error (400 Bad Request):**
```json
{
"success": false,
"error": "runId query parameter is required"
}
```typescript
**Error (404 Not Found):**
```json
{
"success": false,
"error": "Workflow run not found"
}
```typescript
#### Example: Get Workflow Status
```bash
curl "http://localhost:3000/api/workflow/send-email-received-ein?runId=run-abc123"
```typescript
## Workflow-Specific Parameters
### send-welcome-email
**Input:**
```typescript
{
userId: string; // Required: User ID to send welcome email to
}
```typescript
**Example:**
```json
{
"userId": "550e8400-e29b-41d4-a716-446655440000"
}
```typescript
### send-email-received-ein
**Input:**
```typescript
{
userId: string; // Required: User ID
companyId: string; // Required: Company ID
organizationId: string; // Required: Organization ID
emailAction: string; // Required: Email action type
recipientName?: string; // Optional: Recipient name
recipients: string[]; // Required: Array of recipient emails
resource_id_ref?: string; // Optional: Resource reference ID
ccs?: string[]; // Optional: CC recipients
}
```typescript
**Parameter Mapping:**
The API accepts both snake_case and camelCase parameters:
| API Parameter (snake_case) | Workflow Parameter (camelCase) |
|---------------------------|-------------------------------|
| `user_id` | `userId` |
| `company_id` | `companyId` |
| `organization_id` | `organizationId` |
| `email_action` | `emailAction` |
| `recipient_name` | `recipientName` |
| `recipients` | `recipients` |
| `resource_id_ref` | `resource_id_ref` |
| `ccs` | `ccs` |
**Example:**
```json
{
"userId": "user-123",
"companyId": "company-456",
"organizationId": "org-789",
"email_action": "sf_formations_we_received_your_ein",
"recipient_name": "John Doe",
"recipients": ["john@example.com"],
"resource_id_ref": "a03c8c04-d1af-4eff-bd9d-4cba26bead0b",
"ccs": []
}
```typescript
## Workflow Status Values
### Status Types
- `pending`: Workflow is queued and waiting for a worker
- `running`: Workflow is currently executing
- `completed`: Workflow finished successfully
- `failed`: Workflow failed after all retries
- `cancelled`: Workflow was manually cancelled
### Status Response Fields
- `status`: Current workflow status
- `result`: Workflow output (if completed)
- `error`: Error details (if failed)
- `createdAt`: When workflow was created
- `updatedAt`: When workflow was last updated
## Error Handling
### Common Errors
**Workflow Not Found (404)**
```json
{
"success": false,
"error": "Workflow \"invalid-name\" not found"
}
```typescript
**Missing Required Parameter (400)**
```json
{
"success": false,
"error": "runId query parameter is required"
}
```typescript
**Workflow Execution Error (500)**
```json
{
"success": false,
"error": "Failed to send email: Connection timeout"
}
```typescript
## Polling Pattern
For long-running workflows, poll the status endpoint:
```typescript
async function waitForWorkflowCompletion(
workflowName: string,
runId: string,
pollInterval = 1000
): Promise<any> {
while (true) {
const response = await fetch(
`/api/workflow/${workflowName}?runId=${runId}`
);
const data = await response.json();
if (data.status === "completed") {
return data.result;
}
if (data.status === "failed") {
throw new Error(data.error);
}
// Wait before next poll
await new Promise(resolve => setTimeout(resolve, pollInterval));
}
}
```typescript
## Rate Limiting
Currently, there are no rate limits on workflow triggers. However, consider:
- Worker concurrency limits (20 concurrent workflows)
- Database connection limits
- External API rate limits (e.g., email service)
## Authentication
The API routes should be protected with authentication middleware. Ensure:
- User authentication is verified
- User has permission to trigger workflows
- User context is available for workflow execution
## Best Practices
1. **Store runId**: Always save the `runId` returned from POST requests
2. **Poll Appropriately**: Don't poll too frequently (1-2 seconds is reasonable)
3. **Handle Errors**: Always check `success` field and handle errors
4. **Validate Input**: Validate all parameters before sending requests
5. **Use Timeouts**: Set appropriate timeouts for workflow execution
6. **Monitor Status**: Track workflow success/failure rates
## Integration Examples
### TypeScript/JavaScript
```typescript
async function triggerEmailWorkflow(params: {
userId: string;
companyId: string;
organizationId: string;
emailAction: string;
recipients: string[];
}) {
const response = await fetch("/api/workflow/send-email-received-ein", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
userId: params.userId,
companyId: params.companyId,
organizationId: params.organizationId,
email_action: params.emailAction,
recipients: params.recipients,
}),
});
if (!response.ok) {
throw new Error(`Failed to trigger workflow: ${response.statusText}`);
}
const data = await response.json();
return data.runId;
}
```typescript
### Python
```python
import requests
def trigger_email_workflow(user_id, company_id, org_id, email_action, recipients):
response = requests.post(
"http://localhost:3000/api/workflow/send-email-received-ein",
json={
"userId": user_id,
"companyId": company_id,
"organizationId": org_id,
"email_action": email_action,
"recipients": recipients,
}
)
response.raise_for_status()
return response.json()["runId"]
```typescript