Developer guide

How to send SMS from Python with the JMSURF SMS API

Whether you run Django, Flask, FastAPI or a cron script, sending SMS is one HTTPS request. These examples use the requests library and the standard library only.

Before you start: get an API key

  1. Create a free JMSURF SMS workspace at jmsurfsms.co.ke and confirm your email.
  2. 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.
  3. 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.
  4. 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

send_sms.py
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

bulk_from_csv.py
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_kes

Check status and balance

status.py
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

webhook.py
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 "", 200

Errors to handle

HTTPerror.codeWhat to do
400invalid_request / invalid_recipientFix the body or phone number; do not retry unchanged
401unauthorized / invalid_keyCheck the key and the Bearer header
402insufficient_creditTop up the wallet
403insufficient_scope / ip_not_allowedAdd the scope or allow your server's IP on the key
409reference_conflictThe reference was used for a different message; generate a new one
422recipient_blocked / sender_not_approvedThe message cannot be sent as requested
429rate_limitedWait 60 seconds (Retry-After header) and retry with the same reference
503provider_credit / sending_pausedHold 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].

Make every message count.

Start with a free workspace. Add your audience, top up with M-Pesa and keep your customers in the conversation.

Create your workspace