Testing & Debugging
Comprehensive testing and debugging guide for Amanah AI API. Learn how to test your integrations, debug issues, and optimize performance.
Sandbox Environment Setup
🧪 Test Environment
Use our sandbox environment to test your integrations safely without sending real messages or incurring charges.
Base URL: https://sandbox-api.amanahagent.cloud/v1
Getting Sandbox Credentials
Access your sandbox API keys from your dashboard's testing section:
Step 1: Access Sandbox Settings
Navigate to Settings → Developer → Sandbox in your Amanah AI dashboard.
Step 2: Generate Test API Key
Create a sandbox-specific API key that won't affect your production environment.
Step 3: Configure Test Environment
Update your application to use sandbox endpoints for testing.
Sandbox Features
[Done] Available Features
- Full API functionality
- Webhook testing
- Message simulation
- Error condition testing
- Rate limit testing
- Template validation
⚠️ Limitations
- No real messages sent
- Simulated delivery statuses
- Limited to test phone numbers
- No billing or usage charges
- Data cleared every 30 days
Test Phone Numbers and Scenarios
📱 Testing Scenarios
Use special test phone numbers to simulate different delivery scenarios and test your error handling logic.
Test Phone Numbers
| Phone Number | Scenario | Result | Use Case |
|---|---|---|---|
| +1555000001 | Successful delivery | delivered | Test happy path |
| +1555000002 | Message read | read | Test read receipts |
| +1555000003 | Delivery failure | failed | Test error handling |
| +1555000004 | Slow delivery | delayed | Test timeouts |
| +1555000005 | Invalid number | invalid | Test validation |
| +1555000006 | Rate limit trigger | rate_limited | Test rate limits |
Testing Different Scenarios
// Test successful message delivery
const testSuccess = async () => {
const response = await client.messages.send({
to: '+1555000001',
type: 'text',
message: 'Test message for successful delivery'
});
console.log('Message sent:', response.message_id);
// Check status after delay
setTimeout(async () => {
const status = await client.messages.getStatus(response.message_id);
console.log('Delivery status:', status.delivery_status); // 'delivered'
}, 2000);
};
// Test error handling
const testFailure = async () => {
try {
const response = await client.messages.send({
to: '+1555000003', // This number simulates delivery failure
type: 'text',
message: 'Test message for failure scenario'
});
// Monitor for failure webhook
console.log('Message queued:', response.message_id);
} catch (error) {
console.error('Message failed:', error.message);
// Handle the error appropriately
}
};
// Test rate limiting
const testRateLimit = async () => {
const promises = [];
// Send multiple messages quickly to +1555000006
for (let i = 0; i < 20; i++) {
promises.push(
client.messages.send({
to: '+1555000006',
type: 'text',
message: `Rate limit test message ${i + 1}`
}).catch(err => ({ error: err.message, index: i }))
);
}
const results = await Promise.all(promises);
console.log('Rate limit results:', results);
};Webhook Testing
Test your webhook endpoints using our webhook testing tool:
// Set up test webhook endpoint
app.post('/test-webhook', (req, res) => {
const { event, data } = req.body;
console.log('Webhook received:', { event, data });
// Test different event types
switch (event) {
case 'message.sent':
console.log('Message sent successfully');
break;
case 'message.delivered':
console.log('Message delivered to:', data.to);
break;
case 'message.failed':
console.log('Message failed:', data.error_reason);
break;
case 'message.received':
console.log('Incoming message from:', data.from);
break;
}
res.status(200).send('OK');
});
// Configure webhook for testing
const webhookConfig = {
url: 'https://your-test-app.com/test-webhook',
events: ['message.sent', 'message.delivered', 'message.failed'],
secret: 'test-webhook-secret'
};
await client.webhooks.create(webhookConfig);Pro Tip: Use tools like ngrok or localtunnel to expose your local development server for webhook testing.
API Testing Tools and Methods
🛠️ Testing Toolkit
Use these tools and methods to thoroughly test your Amanah AI API integration across different scenarios and environments.
Postman Collection
Download our official Postman collection with pre-configured requests for all API endpoints:
Amanah AI API Collection
Complete collection with environment variables and test scripts
Included Requests
- • Send Text Message
- • Send Media Message
- • Get Message Status
- • Manage Contacts
- • Template Operations
- • Webhook Configuration
Environment Setup
"api_key": "{{API_KEY}}",
"base_url": "https://api.amanahagent.cloud/v1",
"sandbox_url": "https://sandbox-api.amanahagent.cloud/v1"
}
cURL Testing Commands
Quick cURL commands for testing API endpoints:
Send Test Message
curl -X POST https://sandbox-api.amanahagent.cloud/v1/messages -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d '{
"to": "+1555000001",
"type": "text",
"message": "Hello from cURL test!"
}'Check Message Status
curl -X GET https://sandbox-api.amanahagent.cloud/v1/messages/MSG_ID -H "Authorization: Bearer YOUR_API_KEY"
Upload Test Media
curl -X POST https://sandbox-api.amanahagent.cloud/v1/media -H "Authorization: Bearer YOUR_API_KEY" -F "file=@test-image.jpg" -F "filename=test-upload.jpg"
Automated Testing Scripts
Example test scripts for different programming languages:
Node.js Test Suite
// test/amanahagent.test.js
const { expect } = require('chai');
const Amanah AI = require('@amanahagent/sdk');
const client = new Amanah AI({
apiKey: process.env.AMANAHAGENT_TEST_API_KEY,
baseURL: 'https://sandbox-api.amanahagent.cloud/v1'
});
describe('Amanah AI API Tests', () => {
it('should send a text message successfully', async () => {
const response = await client.messages.send({
to: '+1555000001',
type: 'text',
message: 'Test message from automated test'
});
expect(response).to.have.property('message_id');
expect(response.status).to.equal('sent');
});
it('should handle delivery failures gracefully', async () => {
try {
await client.messages.send({
to: '+1555000003', // Simulates failure
type: 'text',
message: 'This message will fail'
});
} catch (error) {
expect(error.message).to.include('delivery failed');
}
});
it('should respect rate limits', async () => {
const promises = [];
for (let i = 0; i < 25; i++) {
promises.push(
client.messages.send({
to: '+1555000006',
type: 'text',
message: `Rate limit test ${i}`
}).catch(err => err)
);
}
const results = await Promise.all(promises);
const rateLimitErrors = results.filter(r =>
r.message && r.message.includes('rate limit')
);
expect(rateLimitErrors.length).to.be.greaterThan(0);
});
});Python Test Example
# test_amanahagent.py
import pytest
import os
from amanahagent import Amanah AI
client = Amanah AI(
api_key=os.getenv('AMANAHAGENT_TEST_API_KEY'),
base_url='https://sandbox-api.amanahagent.cloud/v1'
)
def test_send_message_success():
response = client.messages.send(
to="+1555000001",
type="text",
message="Test from Python"
)
assert 'message_id' in response
assert response['status'] == 'sent'
def test_message_delivery_failure():
with pytest.raises(Exception) as exc_info:
client.messages.send(
to="+1555000003",
type="text",
message="This will fail"
)
assert "delivery failed" in str(exc_info.value)
def test_webhook_signature_verification():
import hmac
import hashlib
payload = '{"event":"message.sent","data":{"message_id":"test123"}}'
secret = 'test-webhook-secret'
signature = hmac.new(
secret.encode(),
payload.encode(),
hashlib.sha256
).hexdigest()
# Your webhook handler should verify this signature
assert len(signature) == 64 # SHA256 hex lengthPerformance Testing Guidelines
⚡ Performance Metrics
Monitor and optimize the performance of your WhatsApp messaging integration with these testing strategies and benchmarks.
Load Testing
Test your application's ability to handle high message volumes:
// Load testing with concurrent requests
const loadTest = async (concurrentRequests = 10, totalMessages = 1000) => {
const results = {
successful: 0,
failed: 0,
totalTime: 0
};
const startTime = Date.now();
const batchSize = Math.ceil(totalMessages / concurrentRequests);
const batches = [];
for (let i = 0; i < concurrentRequests; i++) {
const batch = [];
for (let j = 0; j < batchSize && (i * batchSize + j) < totalMessages; j++) {
batch.push(
client.messages.send({
to: '+1555000001',
type: 'text',
message: `Load test message ${i * batchSize + j + 1}`
})
.then(() => ({ success: true }))
.catch(error => ({ success: false, error: error.message }))
);
}
batches.push(Promise.all(batch));
}
const allResults = await Promise.all(batches);
// Process results
allResults.flat().forEach(result => {
if (result.success) {
results.successful++;
} else {
results.failed++;
}
});
results.totalTime = Date.now() - startTime;
results.messagesPerSecond = totalMessages / (results.totalTime / 1000);
console.log('Load Test Results:', results);
return results;
};
// Run load test
loadTest(20, 500).then(results => {
console.log(`
Performance Metrics:`);
console.log(`Success Rate: ${(results.successful / (results.successful + results.failed) * 100).toFixed(2)}%`);
console.log(`Messages/Second: ${results.messagesPerSecond.toFixed(2)}`);
console.log(`Total Time: ${results.totalTime}ms`);
});Target Metrics
- • >95% success rate
- • <2s response time
- • >10 msg/sec throughput
Warning Signs
- • >5% failure rate
- • >5s response time
- • Rate limit errors
Critical Issues
- • >10% failure rate
- • >10s response time
- • Service unavailable
Monitoring and Alerting
Set up monitoring to track API performance in production:
// Performance monitoring wrapper
class Amanah AIMonitor {
constructor(client) {
this.client = client;
this.metrics = {
requests: 0,
successes: 0,
failures: 0,
totalLatency: 0
};
}
async sendMessage(messageData) {
const startTime = Date.now();
this.metrics.requests++;
try {
const result = await this.client.messages.send(messageData);
this.metrics.successes++;
const latency = Date.now() - startTime;
this.metrics.totalLatency += latency;
// Log success metrics
if (latency > 5000) {
console.warn(\`Slow API response: \${latency}ms\`);
// Send alert
this.sendAlert('HIGH_LATENCY', { latency, messageId: result.message_id });
}
return result;
} catch (error) {
this.metrics.failures++;
// Log error metrics
console.error('API request failed:', error.message);
this.sendAlert('API_FAILURE', { error: error.message, messageData });
throw error;
}
}
getStats() {
const avgLatency = this.metrics.totalLatency / this.metrics.successes;
const successRate = (this.metrics.successes / this.metrics.requests) * 100;
return {
requests: this.metrics.requests,
successRate: successRate.toFixed(2) + '%',
averageLatency: avgLatency.toFixed(0) + 'ms',
failures: this.metrics.failures
};
}
sendAlert(type, data) {
// Integrate with your monitoring service
// e.g., Datadog, New Relic, or custom webhook
console.log(\`ALERT [\${type}]:\`, data);
}
// Reset metrics (call periodically)
resetMetrics() {
this.metrics = {
requests: 0,
successes: 0,
failures: 0,
totalLatency: 0
};
}
}
// Usage
const monitoredClient = new Amanah AIMonitor(client);
// Send messages through monitored client
await monitoredClient.sendMessage({
to: '+1234567890',
type: 'text',
message: 'Monitored message'
});
// Get performance stats
console.log('Performance Stats:', monitoredClient.getStats());Integration Tip: Use tools like Datadog, New Relic, or Prometheus to collect and visualize these metrics over time.