API Testing

This guide provides information on how to test our WhatsApp API service effectively, including available testing environments, tools, and best practices.

Testing Environments

We provide different environments to help you test your integration without affecting production data:

Environment Base URL Purpose Limitations
Sandbox https://sandbox-api.messaging.com/v1 Development and initial testing
  • Messages are not delivered to real recipients
  • Limited to 100 requests per day
  • Simulated responses
Staging https://staging-api.messaging.com/v1 Pre-production testing
  • Can send to whitelisted numbers only
  • Limited to 500 requests per day
  • Real message delivery to whitelisted numbers
Production https://api.messaging.com/v1 Live environment
  • Full functionality
  • Rate limits based on your plan
  • Real message delivery to any valid number

Test API Keys

Each environment requires a different API key:

  • Sandbox API Key: Generate from your dashboard under "Developer" → "Sandbox Keys"
  • Staging API Key: Request through support after completing sandbox testing
  • Production API Key: Generate from your dashboard under "Developer" → "Production Keys"
Important: Never use production API keys in development or testing environments. Each key is environment-specific and should only be used in its intended environment.

Testing Tools

Built-in Testing Console

Our API documentation includes an interactive testing console that allows you to make API requests directly from your browser. To use it:

  1. Navigate to the endpoint you want to test in the API documentation
  2. Click the "Try it out" button
  3. Enter your API key and request parameters
  4. Click "Execute" to send the request

Recommended External Tools

Tool Type Best For Link
Postman API Client Manual testing, creating collections of requests Website
Insomnia API Client Simple interface, GraphQL support Website
cURL Command-line tool Quick tests, automation scripts Website
Jest Testing framework Automated JavaScript testing Website
Pytest Testing framework Automated Python testing Website

Webhook Testing

For testing webhooks during development, we recommend:

  • Webhook.site - Provides a temporary URL to receive and inspect webhook payloads
  • ngrok - Creates a secure tunnel to your localhost for receiving webhooks
  • RequestBin - Collects, inspects and debugs HTTP requests and webhooks

Testing Best Practices

General Testing Tips

  • Start with the sandbox: Always begin testing in the sandbox environment
  • Test error scenarios: Deliberately trigger errors to test your error handling
  • Validate responses: Check that your code correctly handles all response fields
  • Test rate limiting: Ensure your application handles rate limit errors gracefully
  • Test with realistic data: Use data that resembles your production use case

Automated Testing

For reliable integration, we recommend implementing automated tests:

Test individual components of your integration:

// Example Jest test for sending a message
test('sends a text message successfully', async () => {
  const client = new WhatsAppClient({
    apiKey: 'test_api_key',
    baseUrl: 'https://sandbox-api.messaging.com/v1'
  });
  
  const mockResponse = {
    success: true,
    data: {
      messageId: 'msg_123456789'
    }
  };
  
  // Mock the API call
  client.api.post = jest.fn().mockResolvedValue({ data: mockResponse });
  
  const result = await client.messages.sendText({
    sessionId: 'test_session',
    to: '14155552671',
    text: 'Test message'
  });
  
  expect(result.success).toBe(true);
  expect(result.data.messageId).toBe('msg_123456789');
});

Test the interaction between your application and the API:

# Example Python pytest integration test
import pytest
from whatsapp_api import WhatsAppClient

@pytest.fixture
def client():
    return WhatsAppClient(
        api_key='sandbox_test_key',
        base_url='https://sandbox-api.messaging.com/v1'
    )

def test_session_workflow(client):
    # Create a session
    session_response = client.sessions.create({
        'phone_number': '14155552671'
    })
    assert session_response['success'] == True
    session_id = session_response['data']['sessionId']
    
    # Send a message using the session
    message_response = client.messages.send_text({
        'sessionId': session_id,
        'to': '14155552671',
        'text': 'Integration test message'
    })
    assert message_response['success'] == True
    
    # Delete the session
    delete_response = client.sessions.delete(session_id)
    assert delete_response['success'] == True

Test your webhook handling code:

// Example Express.js webhook handler test
const request = require('supertest');
const app = require('../app');
const crypto = require('crypto');

describe('Webhook Handler', () => {
  it('processes message received webhook correctly', async () => {
    // Sample webhook payload
    const payload = {
      event: 'message.received',
      data: {
        messageId: 'msg_123456789',
        sessionId: 'session_abcdef',
        from: '14155552671',
        timestamp: new Date().toISOString(),
        type: 'text',
        text: {
          body: 'Hello from webhook test'
        }
      }
    };
    
    // Create signature for webhook verification
    const webhookSecret = 'test_webhook_secret';
    const signature = crypto
      .createHmac('sha256', webhookSecret)
      .update(JSON.stringify(payload))
      .digest('hex');
    
    // Send webhook request
    const response = await request(app)
      .post('/api/webhooks/whatsapp')
      .set('X-Webhook-Signature', signature)
      .send(payload);
    
    expect(response.status).toBe(200);
    
    // Verify the webhook was processed correctly
    // This depends on your implementation
    // For example, check if a database record was created
  });
});

Testing Checklist

Before moving to production, ensure you've tested the following:

Category Test Case Description
Authentication Valid API key Requests with valid API key succeed
Invalid API key Requests with invalid API key fail with 401
Missing API key Requests without API key fail with 401
Sessions Create session Session is created successfully
Get session status Session status is retrieved correctly
Delete session Session is deleted successfully
List sessions All sessions are listed correctly
Messages Send text message Text message is sent successfully
Send media message Media message is sent successfully
Send location message Location message is sent successfully
Send button message Button message is sent successfully
Message status updates Webhooks for message status updates are received
Webhooks Webhook verification Webhook signatures are verified correctly
Message received webhook Incoming messages trigger webhooks
Webhook retry handling Application handles webhook retries correctly
Error Handling Rate limit handling Application handles rate limit errors gracefully
General error handling Application handles various error responses correctly

Moving to Production

Once you've completed testing in the sandbox and staging environments, follow these steps to move to production:

  1. Generate a production API key from your dashboard
  2. Update your application configuration to use the production base URL and API key
  3. Configure production webhooks with proper security measures
  4. Monitor your initial production traffic closely
  5. Set up alerts for any unusual error rates or response times
Need help? Our support team is available to assist with your production deployment. Contact us through the Support Portal for assistance.