SMS APIs in Kenya: Sending Your First Message With Africa's Talking
Africa's Talking is the most developer-friendly SMS gateway in Kenya. You create an account, get API credentials, install their SDK (or make direct HTTP calls), and send an SMS with a single function call. The sandbox lets you test for free. Production messages cost a per-SMS fee and require a registered sender ID.
Why SMS still works in Kenya
SMS reaches every phone with a SIM card. No smartphone, no data plan, no app install required. In Kenya, SMS is still the backbone for:
- OTP verification: banks, M-Pesa, and most apps send login codes via SMS
- Transaction alerts: M-Pesa confirmations, bank notifications, utility receipts
- Appointment reminders: clinics, salons, service providers
- Marketing campaigns: promotional offers, sale announcements (with opt-in)
- Agricultural alerts: market prices, weather warnings for farmers
WhatsApp is growing, but SMS has one advantage nothing else matches: it works on every phone, on every network, even when data is off. If your users include anyone outside major cities or anyone on a basic phone, SMS is not optional.
Setting up Africa's Talking
- Create an account at
africastalking.com - Switch to the Sandbox environment using the toggle in the dashboard header
- Go to Settings and copy your API Key
- Your sandbox username is always
sandbox
Store credentials in your environment:
# .env
AT_USERNAME=sandbox
AT_API_KEY=your_sandbox_api_key_hereInstall the SDK:
# Node.js
npm install africastalking
# Python
pip install africastalkingThe sandbox does not send real SMS messages. Instead, it returns a success response and logs the message in the sandbox simulator on the dashboard. This lets you test your integration without spending money or needing a real phone.
Sending your first SMS
Node.js:
import AfricasTalking from 'africastalking';
const at = AfricasTalking({
apiKey: process.env.AT_API_KEY!,
username: process.env.AT_USERNAME!,
});
const sms = at.SMS;
async function sendSMS(to: string, message: string) {
try {
const result = await sms.send({
to: [to],
message: message,
// from: 'YOUR_SENDER_ID', // production only
});
console.log('SMS sent:', result);
return result;
} catch (error) {
console.error('SMS failed:', error);
throw error;
}
}
// Usage
sendSMS(
'+254712345678',
'Hello from McTaba Labs! Your enrollment is confirmed.'
);Python:
import africastalking
import os
africastalking.initialize(
username=os.environ["AT_USERNAME"],
api_key=os.environ["AT_API_KEY"],
)
sms = africastalking.SMS
def send_sms(to: str, message: str) -> dict:
try:
result = sms.send(
message=message,
recipients=[to],
# sender_id="YOUR_SENDER_ID", # production only
)
print(f"SMS sent: {result}")
return result
except Exception as e:
print(f"SMS failed: {e}")
raise
# Usage
send_sms(
"+254712345678",
"Hello from McTaba Labs! Your enrollment is confirmed.",
)The to parameter accepts Kenyan numbers in international format: +254712345678. The SDK accepts an array, so you can send to multiple recipients in one call.
A successful sandbox response looks like:
{
"SMSMessageData": {
"Message": "Sent to 1/1 Total Cost: KES 0.0000",
"Recipients": [
{
"number": "+254712345678",
"status": "Success",
"statusCode": 101,
"cost": "KES 0.0000",
"messageId": "ATXid_abc123"
}
]
}
}Bulk messaging and delivery reports
Sending to multiple recipients:
// Send to multiple numbers
const result = await sms.send({
to: [
'+254712345678',
'+254723456789',
'+254734567890',
],
message: 'Class starts Monday at 9am EAT. See you there!',
});
// Each recipient gets an individual status
result.SMSMessageData.Recipients.forEach((r: any) => {
console.log(`${r.number}: ${r.status}`);
});For large batches (hundreds or thousands of messages), send in chunks of 100 to 200 recipients per API call. This keeps individual requests fast and makes error handling manageable.
Delivery reports:
Africa's Talking can notify you when a message is delivered (or fails) via a callback URL. Set up a delivery report callback in your dashboard under SMS > Callback URL.
// Delivery report webhook handler
app.post('/sms/delivery', (req, res) => {
const {
id, // message ID
status, // "Delivered", "Failed", etc.
phoneNumber,
failureReason,
} = req.body;
console.log(
`Delivery report: ${id} to ${phoneNumber} = ${status}`
);
if (status === 'Failed') {
console.log(`Failure reason: ${failureReason}`);
// TODO: retry or notify admin
}
res.sendStatus(200);
});Common delivery statuses:
- Sent: the message left the gateway
- Submitted: the mobile network accepted it
- Delivered: confirmed delivered to the handset
- Failed: could not be delivered (wrong number, phone off, network issue)
- Rejected: the network rejected the message (invalid sender ID, content filter)
Receiving incoming SMS
If you have a shortcode or a dedicated long number, you can receive SMS messages from users. Africa's Talking forwards incoming messages to your callback URL.
Set up an incoming message callback in the dashboard under SMS > Callback URL > Incoming Messages.
Node.js handler:
app.post('/sms/incoming', (req, res) => {
const {
from, // sender phone number
to, // your shortcode or number
text, // message content
date, // when it was sent
id, // message ID
} = req.body;
console.log(`Incoming SMS from ${from}: ${text}`);
// Auto-reply based on keyword
const keyword = text.trim().toLowerCase();
if (keyword === 'courses') {
sendSMS(
from,
'McTaba Courses:\n' +
'1. Full-Stack AI Engineering\n' +
'2. M-Pesa Integration\n' +
'3. Tech Foundations\n' +
'Reply with course number for details.'
);
} else if (['1', '2', '3'].includes(keyword)) {
const info: Record<string, string> = {
'1': 'Full-Stack AI Engineering: 26-week marathon. Visit mctaba.com',
'2': 'M-Pesa Integration: Learn Daraja API. Visit academy.mctaba.com',
'3': 'Tech Foundations: Start your coding journey. Visit academy.mctaba.com',
};
sendSMS(from, info[keyword]);
} else {
sendSMS(
from,
'Welcome to McTaba Labs. Reply COURSES for info.'
);
}
res.sendStatus(200);
});This pattern (receive keyword, send response) is the foundation of SMS-based services. Agricultural information systems, health hotlines, and voting platforms in Kenya all work this way.
Going to production: sender IDs and costs
In production, your SMS messages need a sender ID. This is the name or number that appears as the "from" field on the recipient's phone. Instead of seeing a random number, they see your business name (e.g., "McTaba").
To get a sender ID:
- Apply through the Africa's Talking dashboard
- Provide your business registration documents
- Africa's Talking submits the sender ID to the mobile networks for approval
- Approval takes 3 to 14 business days depending on the network
Once approved, include the sender ID in your API calls:
const result = await sms.send({
to: ['+254712345678'],
message: 'Your class starts in 1 hour.',
from: 'McTaba', // your approved sender ID
});Costs: SMS pricing in Kenya depends on the network. Safaricom, Airtel, and Telkom have different per-message rates. [TODO: verify on provider website] for current pricing. Generally, rates range from a few cents to about KES 1 per SMS depending on volume commitments.
Opt-in compliance: Kenya's Communications Authority requires that recipients opt in before receiving marketing SMS. Transactional messages (order confirmations, OTPs) do not need opt-in, but promotional messages do. Always provide an opt-out mechanism (e.g., "Reply STOP to unsubscribe").
Frequently Asked Questions
- What is the character limit for an SMS?
- A single SMS can contain 160 characters using standard GSM encoding. If you exceed 160 characters, the message is split into multiple parts (each 153 characters due to concatenation headers) and reassembled on the recipient's phone. You are charged for each part. A 320-character message costs the same as 3 individual SMS messages.
- Can I send SMS to numbers outside Kenya with Africa's Talking?
- Yes. Africa's Talking supports SMS to multiple African countries including Uganda, Tanzania, Rwanda, Nigeria, and others. The pricing and sender ID requirements vary by country. Check their coverage page for the full list of supported countries.
- How fast are SMS messages delivered?
- Most SMS messages are delivered within 5 to 30 seconds. However, delivery is not guaranteed to be instant. Network congestion, phone being off, or being out of coverage area can delay delivery. Messages to phones that are off are queued by the network for up to 48 hours.
Ready to build real-world apps?
Join the McTaba Labs full-stack marathon. Ship 8 production apps with M-Pesa, USSD, and WhatsApp integrations, and get career support until placement.
See Programs