Before you start: get an API key
- Create a free JMSURF SMS workspace at jmsurfsms.co.ke and confirm your email.
- Open Developers, then API keys, and create a test key (starts with jms_test_). Test keys behave like live keys but never deliver or charge; messages are recorded with the status sandbox.
- When your code works, create a live key (jms_live_) with only the scopes you need, for example sms:send and sms:read, and top up your wallet with M-Pesa.
- Store the key in an environment variable such as JMSURF_API_KEY. Never put it in front-end code or a public repository.
The request in brief
- POST https://jmsurfsms.co.ke/api/v1/sms/send with header Authorization: Bearer <your key> and a JSON body.
- to: the phone number, local (07XXXXXXXX or 01XXXXXXXX) or international (+2547XXXXXXXX).
- message: the text, up to 1,600 characters. 160 plain characters = 1 SMS.
- reference: a UUID you generate. Sending again with the same reference never sends twice, so retries are safe.
- sender_id (optional): your approved sender ID; omit it to use your default sender.
- type (optional): "transactional" for OTPs, receipts and alerts that must reach people who opted out of marketing; "marketing" otherwise.
A successful request returns 202 Accepted with the message id, status queued, number of SMS parts, encoding and cost_kes. A message the network refuses immediately returns 422 with status failed and is refunded. Errors return { "error": { "code": "...", "message": "..." } }.
Send one SMS
import os
import uuid
import requests
API = "https://jmsurfsms.co.ke/api/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['JMSURF_API_KEY']}"}
def send_sms(to: str, message: str, reference: str | None = None) -> dict:
payload = {
"to": to,
"message": message,
"reference": reference or str(uuid.uuid4()), # keep it to retry safely
"type": "transactional",
}
r = requests.post(f"{API}/sms/send", json=payload, headers=HEADERS, timeout=30)
data = r.json()
if r.status_code not in (202, 422):
raise RuntimeError(f"{r.status_code} {data['error']['code']}: {data['error']['message']}")
return data
sms = send_sms("07XXXXXXXX", "Your appointment is tomorrow at 10:00.")
print(sms["id"], sms["status"], sms["cost_kes"])Bulk SMS from a CSV file
import csv
import os
import requests
with open("customers.csv", newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f)) # columns: phone, name, balance
payload = {
"name": "Monthly statements",
"message": "Hi {first_name|there}, your balance is KES {balance}.",
"recipients": [
{"phone": r["phone"], "name": r["name"], "fields": {"balance": r["balance"]}} for r in rows
],
}
r = requests.post(
"https://jmsurfsms.co.ke/api/v1/sms/bulk",
json=payload,
headers={"Authorization": f"Bearer {os.environ['JMSURF_API_KEY']}"},
timeout=60,
)
print(r.status_code, r.json()) # 202 with campaign_id, recipients, skipped, estimated_cost_kesCheck status and balance
msg = requests.get(f"{API}/sms/{sms['id']}", headers=HEADERS, timeout=30).json()
print(msg["status"], msg.get("network"), msg.get("delivered_at"))
bal = requests.get(f"{API}/balance", headers=HEADERS, timeout=30).json()
print(bal["balance_kes"], bal["sms_remaining"])Reading a message needs the sms:read scope; the balance needs balance:read.
Flask webhook
import hashlib
import hmac
import os
from flask import Flask, abort, request
app = Flask(__name__)
@app.post("/jmsurf/webhook")
def jmsurf_webhook():
raw = request.get_data()
expected = "sha256=" + hmac.new(
os.environ["JMSURF_WEBHOOK_SECRET"].encode(), raw, hashlib.sha256
).hexdigest()
if not hmac.compare_digest(expected, request.headers.get("x-jmsurf-signature", "")):
abort(401)
event = request.get_json()
if event["event"] == "sms.failed":
print("failed", event["data"]["reference"])
return "", 200Errors to handle
| HTTP | error.code | What to do |
|---|---|---|
| 400 | invalid_request / invalid_recipient | Fix the body or phone number; do not retry unchanged |
| 401 | unauthorized / invalid_key | Check the key and the Bearer header |
| 402 | insufficient_credit | Top up the wallet |
| 403 | insufficient_scope / ip_not_allowed | Add the scope or allow your server's IP on the key |
| 409 | reference_conflict | The reference was used for a different message; generate a new one |
| 422 | recipient_blocked / sender_not_approved | The message cannot be sent as requested |
| 429 | rate_limited | Wait 60 seconds (Retry-After header) and retry with the same reference |
| 503 | provider_credit / sending_paused | Hold the message and retry later with the same reference |
Start sending today
Create a free workspace, top up with M-Pesa and send your first message at KES 0.40 per SMS. Questions first? Call or WhatsApp +254 712 504 593 or email [email protected].
Related pages
- API referenceEvery endpoint, request and response of the REST API.
- SMS API in Node.jsSend SMS from Node.js with fetch and the JMSURF SMS API: single and bulk sends, idempotent retries and an Express webhook with HMAC signature check.
- SMS webhooksReceive SMS delivery reports (DLR), inbound replies and payment events as signed webhooks from JMSURF SMS. Event list, payloads, signature check and retries.
- Developer hubTest keys, scopes, webhooks and the OpenAPI spec.