Development Guide
This guide provides advanced tips, best practices, and examples for developers working with the Klen AI API. Use this information to build robust, scalable integrations with our platform.
API Architecture
The Klen AI API is a RESTful API that uses standard HTTP methods and returns JSON responses. The base URL for all API requests is:
https://api.klen.ai/api/v1
Our API follows these conventions:
GET
requests for retrieving resources
POST
requests for creating resources
PUT
/PATCH
requests for updating resources
DELETE
requests for deleting resources (when applicable)
Error Handling
The API returns appropriate HTTP status codes and error messages to help you troubleshoot issues:
{
"error": "error_code",
"message": "Human-readable error message"
}
Common error codes include:
Status Code | Error Code | Description |
---|
400 | validation_error | Invalid input parameters |
401 | authentication_required | No API key provided |
401 | invalid_key | Invalid or inactive API key |
403 | permission_denied | API key lacks required permission |
404 | not_found | Requested resource not found |
429 | rate_limit_exceeded | Rate limit exceeded |
500 | server_error | Internal server error |
For robust error handling, implement retry logic with exponential backoff for 5xx errors and 429 rate limit errors.
List endpoints support pagination through the page
and limit
query parameters:
GET /api/v1/calls?page=2&limit=25
Pagination responses include metadata to help you navigate the results:
{
"count": 157, // Total number of items
"page": 2, // Current page
"limit": 25, // Items per page
"pages": 7, // Total number of pages
"calls": [...] // Results for this page
}
For large datasets, we recommend implementing cursor-based pagination by storing the ID of the last item received and using it to fetch the next page.
Rate Limiting
Our API implements rate limiting to ensure the stability of the service. Rate limits are enforced on a per-API-key basis.
When you exceed the rate limit, you’ll receive a 429 Too Many Requests
status code with a Retry-After
header indicating when you can make your next request.
HTTP/1.1 429 Too Many Requests
Content-Type: application/json
Retry-After: 30
{
"error": "rate_limit_exceeded",
"message": "Rate limit exceeded. Please try again after 30 seconds."
}
Implement proper handling of rate limit responses by respecting the Retry-After
header and implementing exponential backoff strategies.
Best Practices
Security
- Store API Keys Securely: Never hardcode API keys in your source code or expose them in client-side JavaScript.
- Use Environment Variables: Store your API keys in environment variables or a secure key management system.
- Implement IP Allowlisting: Use the Klen AI dashboard to restrict access to your API keys from specific IP addresses.
- Create Scoped Keys: Create API keys with the minimum required permissions for each use case.
- Optimize Batch Operations: Use batch endpoints where available instead of making many individual requests.
- Implement Caching: Cache responses for resources that don’t change frequently.
- Use Compression: Enable gzip compression for API requests and responses to reduce bandwidth usage.
- Filter Results: Use query parameters to filter results on the server side rather than retrieving all data and filtering client-side.
Webhooks
- Verify Webhook Signatures: Always verify the signature of incoming webhook requests using the secret provided when creating the webhook.
- Implement Idempotency: Handle webhook events idempotently to avoid duplicate processing.
- Acknowledge Quickly: Respond to webhook requests with a 2xx status code as quickly as possible, then process the event asynchronously.
Working with Agents
When creating or updating AI agents, you can customize various aspects of their behavior:
Agent Persona
Provide detailed instructions to shape your agent’s personality, tone, and behavior:
{
"name": "Customer Support Agent",
"model_instructions": "You are a friendly and helpful customer support agent for a software company. Your goal is to help customers troubleshoot technical issues and answer questions about our products. Be patient, empathetic, and technically accurate. If you don't know the answer to a specific question, politely acknowledge this and offer to connect the customer with a human agent."
}
Context Variables
Use context variables to provide dynamic information to your agents during calls:
{
"variables": {
"customer_name": "John Doe",
"last_purchase": "Premium Plan (3 months ago)",
"open_tickets": [
{
"id": "T-12345",
"subject": "Integration issue with API",
"status": "In Progress"
}
],
"subscription_status": "Active",
"renewal_date": "2025-07-15"
}
}
Variables can be referenced in the agent’s instructions using {{variable_name}}
syntax.
Testing
We provide a sandbox environment for testing your integration without making real phone calls:
https://api-sandbox.klen.ai/api/v1
In the sandbox environment:
- No real calls are made
- No charges are incurred
- Test data is automatically generated
- API responses mimic production behavior
To use the sandbox, simply replace the base URL in your API requests.
Implementing Webhooks
Receiving Webhooks
Here’s an example of how to receive and verify webhook events using Node.js and Express:
const express = require('express');
const crypto = require('crypto');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
const WEBHOOK_SECRET = process.env.KLEN_WEBHOOK_SECRET;
app.post('/webhooks/klen', (req, res) => {
const signature = req.headers['x-klen-signature'];
const body = JSON.stringify(req.body);
// Verify signature
const expectedSignature = crypto
.createHmac('sha256', WEBHOOK_SECRET)
.update(body)
.digest('hex');
if (signature !== expectedSignature) {
return res.status(401).send('Invalid signature');
}
// Process the webhook event
const event = req.body;
console.log(`Received ${event.event_type} event`);
// Process based on event type
switch (event.event_type) {
case 'call.started':
// Handle call started
break;
case 'call.ended':
// Handle call ended
break;
case 'call.transcript':
// Handle call transcript
break;
// Handle other event types...
}
// Acknowledge receipt
res.status(200).send('Webhook received');
});
app.listen(3000, () => {
console.log('Webhook server running on port 3000');
});
Webhook Event Types
Refer to our Webhook Events documentation for a complete list of available webhook events and their payloads.
Need Help?
If you need assistance with your integration, you can:
We’re committed to helping you build successful integrations with Klen AI!
Responses are generated using AI and may contain mistakes.