API Documentation

Integrate reliable SMS messaging into your application in minutes. RESTful endpoints, multi-language SDKs, and comprehensive error handling.

Overview

The MacraSMS API allows you to programmatically send SMS messages to single or multiple recipients. Our API uses simple GET requests with query parameters, making it easy to integrate from any programming language or platform.

All API calls return JSON responses with detailed status information, message IDs, and per-recipient delivery results.

Authentication

Every API request requires two authentication parameters passed as query string arguments:

ParameterDescription
sender_idYour registered sender ID (e.g., "MYCOMPANY")
api_keyYour unique API key generated from the dashboard

Important: Never expose your API key in client-side code. Use server-side requests only. If you suspect your key has been compromised, regenerate it immediately from your dashboard.

Base URL

GET https://sms.macrasms.com/api/v1/

Send SMS

Send a text message to one or more recipients. Supports comma-separated phone numbers for bulk sending.

GET https://sms.macrasms.com/api/v1/?sender_id=X&api_key=X&message_text=X&recipients=X

Request Parameters

ParameterTypeRequiredDescription
sender_idStringYESRegistered sender ID. Must be approved before use.
api_keyStringYESAPI authentication key from dashboard.
message_textStringYESMessage content. Max 160 chars per segment. Unicode supported.
recipientsStringYESPhone number(s). Single: 254700000000. Multiple: 254700000000,254711111111

Phone Number Format

All phone numbers must be in international format without the + sign. Supported formats are automatically normalized:

  • 254708138498 ✅ Preferred format
  • 0708138498 ✅ Auto-converted to 254708138498
  • 708138498 ✅ Auto-converted to 254708138498
  • +254708138498 ❌ Remove the + sign

Response Format

All responses are returned as JSON. A successful request returns HTTP 200 regardless of individual message delivery status.

Success Response (HTTP 200)

{
  "success": true,
  "message_id": 12345,
  "sender_id": "MACRA",
  "total": 3,
  "successful": 3,
  "failed": 0,
  "status": "sent",
  "cost": 3.00,
  "balance_used": 3,
  "results": [
    {
      "mobile": "254708138498",
      "status": "success",
      "messageid": "MSG-ABC123",
      "networkid": "SAFARICOM"
    }
  ]
}

Partial Success Response (HTTP 200)

{
  "success": false,
  "message_id": 12346,
  "sender_id": "MACRA",
  "total": 3,
  "successful": 2,
  "failed": 1,
  "status": "partial",
  "cost": 2.00,
  "balance_used": 2,
  "results": [
    {"mobile": "254708138498", "status": "success", "messageid": "MSG-ABC124"},
    {"mobile": "254711111111", "status": "failed", "error_code": 404, "error_desc": "Invalid number"}
  ]
}

Error Codes

400 Bad Request

Missing required parameters or invalid recipient format. Check the details array in response.

401 Unauthorized

Invalid API key or sender ID. Verify credentials in your dashboard.

402 Payment Required

Insufficient SMS balance. Top up credits at macrasms.com/pricing.

500 Server Error

Internal server error. Retry after 30 seconds. Contact support if persistent.

Code Examples

cURL
curl -G "https://sms.macrasms.com/api/v1/" \
  --data-urlencode "sender_id=MACRA" \
  --data-urlencode "api_key=your_api_key_here" \
  --data-urlencode "message_text=Hello from MacraSMS!" \
  --data-urlencode "recipients=254708138498,254711111111"
Python
import requests
from urllib.parse import quote

BASE_URL = "https://sms.macrasms.com/api/v1/"

def send_sms(sender_id, api_key, message, recipients):
    """
    Send SMS via MacraSMS API
    
    Args:
        sender_id: Registered sender ID
        api_key: API authentication key
        message: Message text
        recipients: Single number or comma-separated list
    
    Returns:
        dict: API response
    """
    params = {
        'sender_id': sender_id,
        'api_key': api_key,
        'message_text': message,
        'recipients': recipients
    }
    
    response = requests.get(BASE_URL, params=params, timeout=30)
    return response.json()

# Usage
result = send_sms(
    sender_id="MACRA",
    api_key="your_api_key_here",
    message_text="Your OTP is 123456",
    recipients="254708138498"
)

print(f"Status: {result['status']}")
print(f"Successful: {result['successful']}/{result['total']}")
PHP
<?php
/**
 * Send SMS via MacraSMS API
 */
function sendSMS(string $senderId, string $apiKey, string $message, string $recipients): array {
    $baseUrl = 'https://sms.macrasms.com/api/v1/';
    
    $params = http_build_query([
        'sender_id'    => $senderId,
        'api_key'      => $apiKey,
        'message_text' => $message,
        'recipients'   => $recipients
    ]);
    
    $url = $baseUrl . '?' . $params;
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    curl_close($ch);
    
    if ($curlError) {
        return ['success' => false, 'error' => $curlError];
    }
    
    return json_decode($response, true);
}

// Usage
$result = sendSMS(
    'MACRA',
    'your_api_key_here',
    'Your order #1234 has been shipped!',
    '254708138498,254711111111'
);

if ($result['success']) {
    echo "Sent {$result['successful']} of {$result['total']} messages\n";
} else {
    echo "Error: " . ($result['error'] ?? 'Unknown') . "\n";
}
?>
JavaScript (Node.js / Fetch)
/**
 * Send SMS via MacraSMS API
 * @param {string} senderId - Registered sender ID
 * @param {string} apiKey - API authentication key
 * @param {string} message - Message text
 * @param {string} recipients - Comma-separated phone numbers
 * @returns {Promise<Object>} API response
 */
async function sendSMS(senderId, apiKey, message, recipients) {
    const baseUrl = 'https://sms.macrasms.com/api/v1/';
    
    const params = new URLSearchParams({
        sender_id: senderId,
        api_key: apiKey,
        message_text: message,
        recipients: recipients
    });
    
    const response = await fetch(`${baseUrl}?${params}`, {
        method: 'GET',
        headers: {
            'Accept': 'application/json'
        },
        signal: AbortSignal.timeout(30000)
    });
    
    if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }
    
    return await response.json();
}

// Usage
(async () => {
    try {
        const result = await sendSMS(
            'MACRA',
            'your_api_key_here',
            'Welcome to our service!',
            '254708138498'
        );
        
        console.log(`Status: ${result.status}`);
        console.log(`Cost: KES ${result.cost}`);
        result.results.forEach(r => {
            console.log(`${r.mobile}: ${r.status}`);
        });
    } catch (error) {
        console.error('SMS failed:', error.message);
    }
})();
Java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

public class MacraSmsClient {
    
    private static final String BASE_URL = "https://sms.macrasms.com/api/v1/";
    
    /**
     * Send SMS via MacraSMS API
     */
    public static String sendSMS(String senderId, String apiKey, 
                                  String message, String recipients) throws Exception {
        
        String url = String.format("%s?sender_id=%s&api_key=%s&message_text=%s&recipients=%s",
            BASE_URL,
            URLEncoder.encode(senderId, StandardCharsets.UTF_8),
            URLEncoder.encode(apiKey, StandardCharsets.UTF_8),
            URLEncoder.encode(message, StandardCharsets.UTF_8),
            URLEncoder.encode(recipients, StandardCharsets.UTF_8)
        );
        
        HttpClient client = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(30))
            .build();
            
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(url))
            .GET()
            .header("Accept", "application/json")
            .timeout(Duration.ofSeconds(30))
            .build();
            
        HttpResponse<String> response = client.send(request, 
            HttpResponse.BodyHandlers.ofString());
            
        return response.body();
    }
    
    // Usage
    public static void main(String[] args) throws Exception {
        String result = sendSMS(
            "MACRA",
            "your_api_key_here",
            "Your verification code is 7890",
            "254708138498"
        );
        System.out.println(result);
    }
}
Ruby
require 'net/http'
require 'uri'
require 'json'

module MacraSMS
  BASE_URL = 'https://sms.macrasms.com/api/v1/'
  
  def self.send_sms(sender_id:, api_key:, message:, recipients:)
    uri = URI(BASE_URL)
    uri.query = URI.encode_www_form({
      sender_id: sender_id,
      api_key: api_key,
      message_text: message,
      recipients: recipients
    })
    
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true
    http.open_timeout = 30
    http.read_timeout = 30
    
    response = http.get(uri.request_uri)
    
    case response.code.to_i
    when 200
      JSON.parse(response.body)
    else
      { success: false, error: "HTTP #{response.code}", body: response.body }
    end
  rescue => e
    { success: false, error: e.message }
  end
end

# Usage
result = MacraSMS.send_sms(
  sender_id: 'MACRA',
  api_key: 'your_api_key_here',
  message: 'Thank you for your purchase!',
  recipients: '254708138498,254711111111'
)

puts "Status: #{result['status']}"
puts "Sent: #{result['successful']}/#{result['total']}"

Best Practices

Rate Limits

To ensure fair usage and system stability, the following rate limits apply:

TierLimitWindow
Standard100 requestsPer minute
Bulk500 requestsPer minute
EnterpriseCustomContact sales

Exceeding rate limits returns HTTP 429. Implement exponential backoff in your retry logic.

Security Guidelines

  • Never hardcode API keys - Use environment variables or secure vaults
  • Use HTTPS only - All API calls must be over TLS 1.2+
  • Validate phone numbers server-side before sending to avoid wasted credits
  • Implement idempotency - Store message IDs to prevent duplicate sends
  • Rotate API keys every 90 days or immediately after suspected compromise
  • Log all API calls with timestamps for audit and debugging purposes

Ready to Integrate?

Get your API key and 100 free test credits when you create an account.

Get API Key