Skip to content
Connect Media Connect Media

How to Send SMS with Python

Send SMS from Python scripts, Django or Flask apps and data pipelines with a few lines of code using the Connect Media API.

Python

1. Install requests and set your key

Run pip install requests, then set CM_API_KEY in your environment. Get the key from Profile → API keys in the dashboard.

2. Send an SMS

import os
import requests

API_URL = "https://dashboard.connectmedia.co.ke/api.php"
HEADERS = {"Authorization": f"Bearer {os.environ['CM_API_KEY']}"}


def send_sms(to: str, message: str, sender: str | None = None) -> dict:
    payload = {"action": "send", "to": to, "message": message}
    if sender:
        payload["sender"] = sender
    resp = requests.post(API_URL, headers=HEADERS, json=payload, timeout=15)
    resp.raise_for_status()
    return resp.json()


result = send_sms("254712345678", "Your appointment is tomorrow at 10am.")
if result.get("code") != "201":
    print("Not accepted:", result.get("message"))

3. Send to many numbers

numbers = ["254712345678", "254733111222", "254110222333"]
result = send_sms(",".join(numbers), "Our offices are closed on Friday.")

4. Check balance and history

balance = requests.post(API_URL, headers=HEADERS, json={"action": "balance"}, timeout=15).json()
history = requests.post(API_URL, headers=HEADERS, json={"action": "history", "limit": 50}, timeout=15).json()

5. Normalise Kenyan numbers

import re

def normalise_ke(raw: str) -> str | None:
    d = re.sub(r"\D", "", raw)
    if d.startswith("0"):
        d = "254" + d[1:]
    if len(d) == 9:
        d = "254" + d
    return d if re.fullmatch(r"254[17]\d{8}", d) else None

Using it in Django or Flask

  • Send from a background worker (Celery, RQ) rather than inside the request.
  • Store the returned response with the order or user record for support.
  • Keep messages under 160 characters — see the cost calculator.

Other languages: PHP · Node.js. Full reference: API docs.

Get started

Create a Connect Media account — SMS from KES 1.0, no minimum top-up, credit that never expires, and one account for Safaricom, Airtel and Telkom. Call +254 707 339 945 or email info@connectmedia.co.ke.

Frequently asked questions

How do I send an SMS with Python?

Use the requests library to POST JSON with action send, the number and the message to the Connect Media API, with your API key as a Bearer token.

Can Python send bulk SMS?

Yes. Join the numbers with commas in the to field to send one message to many recipients.

Which Python version is required?

Any supported Python 3 version works. The example uses type hints available in Python 3.10 and later.