Kapso provides powerful programmatic interfaces to integrate your agents with external systems, enabling automated workflows and real-time communication.

API Overview

The Kapso API enables you to:

  • Trigger agent executions programmatically
  • Retrieve execution status and results
  • Manage agent configurations
  • Access conversation history

Authentication

All API requests require authentication using your Project API Key:

X-API-Key: your-project-api-key

Find your API keys in your Project settings under “API Keys”. Keep these keys secure and never expose them in client-side code.

For complete endpoint documentation, see the API Reference.

Agent Webhooks

Webhooks allow two-way communication: your systems can trigger Kapso agents, and Kapso agents can notify your systems.

Incoming Webhooks (Triggering Agents)

Use incoming webhooks to start an agent’s execution flow from your application (e.g., backend, CRM).

  • Endpoint: Each agent has a unique webhook URL.

    POST https://app.kapso.ai/api/v1/agents/{AGENT_ID}/executions
    
  • Authentication: Include your Project API Key in the X-API-Key request header.

    X-API-Key: your-project-api-key
    
  • Request Body (Optional): Send initial data in the JSON payload.

    {
      "message": "Optional initial message for the agent",
      "phone_number": "1234567890" // Optional identifier
    }
    
  • Example (Node.js):

    const agentWebhookUrl = 'https://app.kapso.ai/api/v1/agents/YOUR_AGENT_ID/executions';
    const apiKey = 'YOUR_PROJECT_API_KEY';
    
    const payload = JSON.stringify({
      message: 'Hello agent!',
      phone_number: '1987654321'
    });
    
    fetch(agentWebhookUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-API-Key': apiKey
      },
      body: payload
    })
    .then(response => response.json())
    .then(data => console.log('Agent execution started:', data))
    .catch(error => console.error('Error triggering agent:', error));
    

Outbound Webhooks (Agent Notifications)

Configure your agents to send real-time notifications to your systems when important events occur during execution.

Configuration

  1. Navigate to your agent’s “API & Webhooks” settings
  2. Add webhook endpoints for the events you want to monitor
  3. Configure a Secret Key for request verification
  4. Select which events to subscribe to

Supported Events

Execution Started

agent_execution_started

Fired when an agent begins processing

Execution Ended

agent_execution_ended

Fired when an agent completes successfully

Execution Failed

agent_execution_failed

Fired when an agent encounters an error

Handoff Required

agent_execution_handoff

Fired when human intervention is needed

Security & Verification

Every webhook request includes an X-Webhook-Signature header containing an HMAC SHA-256 signature of the request body. Verify this signature using your configured Secret Key to ensure authenticity.

const crypto = require('crypto');

function verifyWebhookSignature(body, signature, secret) {
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(body, 'utf8')
    .digest('hex');
  
  return signature === expectedSignature;
}

Webhook Payloads

All webhook payloads include base execution data plus event-specific information:

Base Payload Structure
{
  "event": "event_type",
  "agent_execution": {
    "id": "exec_123abc",
    "started_at": "2024-01-01T12:00:00Z",
    "ended_at": "2024-01-01T12:05:00Z", // null if still running
    "status": "completed", // started, completed, failed, handoff
    "agent_id": "agent_456def"
  },
  "agent": {
    "id": "agent_456def",
    "name": "Customer Support Agent"
  }
}
Event-Specific Data

Handoff Event includes handoff details:

{
  "event": "agent_execution_handoff",
  // ... base payload ...
  "handoff": {
    "node_name": "Escalate to Human",
    "handoff_datetime": "2024-01-01T12:04:30Z",
    "handoff_reason": "Customer requested to speak with a human"
  }
}

Failed Event includes error information:

{
  "event": "agent_execution_failed",
  // ... base payload ...
  "failure": {
    "error": {
      "message": "Failed to connect to external API",
      "type": "ConnectionError"
    },
    "failed_at": "2024-01-01T12:03:15Z"
  }
}

Webhook Best Practices

Important considerations:

  • Respond quickly (within 5 seconds) with a 2xx status code
  • Process webhook data asynchronously if needed
  • Store the webhook secret securely
  • Always verify webhook signatures
  • Implement idempotency handling using the provided idempotency key

WhatsApp Webhooks

Kapso provides real-time webhooks for WhatsApp messaging events, enabling you to build powerful integrations and automate workflows based on WhatsApp conversations.

Configuring WhatsApp Webhooks

  1. Navigate to your WhatsApp configuration settings
  2. Go to the “Webhooks” tab
  3. Click “Add Webhook” to create a new webhook endpoint
  4. Configure the following:
    • URL: Your endpoint that will receive webhook notifications
    • Events: Select which events you want to subscribe to
    • Secret Key: Auto-generated or provide your own (used for HMAC signature verification)
    • Custom Headers: Optional additional headers for authentication

WhatsApp Webhook Events

Message Received

whatsapp.message.received

Fired when a new WhatsApp message is received from a customer

Message Sent

whatsapp.message.sent

Fired when your system sends a message to a customer

Message Delivered

whatsapp.message.delivered

Fired when a message is successfully delivered to the recipient’s device

Message Read

whatsapp.message.read

Fired when the recipient reads your message

Message Failed

whatsapp.message.failed

Fired when a message fails to deliver

Conversation Created

whatsapp.conversation.created

Fired when a new WhatsApp conversation is initiated

WhatsApp Webhook Headers

Every WhatsApp webhook request includes these headers:

X-Webhook-Event: whatsapp.message.received
X-Webhook-Signature: sha256=<hmac-signature>
X-Idempotency-Key: <unique-key-per-event>
Content-Type: application/json

WhatsApp Webhook Payloads

Message Event Payload

For message-related events (received, sent, delivered, read, failed):

{
  "message": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "message_type": "text",
    "content": "Hello, I need help with my order",
    "direction": "inbound",
    "status": "received",
    "whatsapp_message_id": "wamid.HBgNNTU0MTIzNDU2Nzg5MA",
    "created_at": "2024-01-15T14:30:00Z",
    "metadata": {
      "custom_field": "value"
    },
    "has_media": false,
    "media_data": null
  },
  "conversation": {
    "id": "660e8400-e29b-41d4-a716-446655440001",
    "phone_number": "+1234567890",
    "status": "active",
    "last_active_at": "2024-01-15T14:30:00Z",
    "metadata": {
      "customer_id": "cust_123"
    }
  },
  "is_new_conversation": false
}

Conversation Created Payload

For the whatsapp.conversation.created event:

{
  "conversation": {
    "id": "660e8400-e29b-41d4-a716-446655440001",
    "phone_number": "+1234567890",
    "status": "active",
    "last_active_at": "2024-01-15T14:30:00Z",
    "metadata": {}
  }
}

Message Types

The message_type field can be one of:

  • text - Plain text message
  • image - Image attachment
  • video - Video attachment
  • audio - Audio/voice message
  • document - Document attachment
  • location - Location sharing
  • sticker - WhatsApp sticker

Verifying WhatsApp Webhooks

Always verify the webhook signature to ensure the request is authentic:

const crypto = require('crypto');

app.post('/webhook/whatsapp', (req, res) => {
  const signature = req.headers['x-webhook-signature'];
  const body = JSON.stringify(req.body);
  
  // Your webhook's secret key
  const secret = process.env.WHATSAPP_WEBHOOK_SECRET;
  
  // Calculate expected signature
  const expectedSignature = 'sha256=' + crypto
    .createHmac('sha256', secret)
    .update(body, 'utf8')
    .digest('hex');
  
  if (signature !== expectedSignature) {
    return res.status(401).send('Invalid signature');
  }
  
  // Process the webhook
  const event = req.headers['x-webhook-event'];
  const idempotencyKey = req.headers['x-idempotency-key'];
  
  // Handle the event...
  
  res.status(200).send('OK');
});

Testing WhatsApp Webhooks

You can test your webhook endpoints directly from the Kapso interface:

  1. Go to your WhatsApp webhook configuration
  2. Click the “Test Webhook” button
  3. Select an event type to test
  4. Review the sample payload that will be sent
  5. Click “Send Test” to trigger a test webhook

The test will use realistic sample data that matches the exact structure of production webhooks.

Webhook Reliability

Kapso implements several features to ensure reliable webhook delivery:

  • Retries: Failed webhooks are retried up to 3 times with exponential backoff (1 minute, 4 minutes, 9 minutes)
  • Timeout: Webhook requests timeout after 30 seconds
  • Idempotency: Each event has a unique idempotency key to prevent duplicate processing
  • Delivery Tracking: All webhook deliveries are logged with full request/response details

Best Practices for WhatsApp Webhooks

  1. Handle Events Asynchronously: Process webhook data in background jobs to respond quickly
  2. Implement Idempotency: Use the X-Idempotency-Key header to prevent processing duplicates
  3. Monitor Failures: Set up alerts for webhook delivery failures
  4. Secure Your Endpoint: Always verify signatures and use HTTPS
  5. Handle All Event Types: Even if you only need certain events now, handle all types gracefully