How to Send SMS with Python: A Step-by-Step Guide
By Nimana · Last updated December 4, 2026 · 5 min read
Send SMS from Python with one HTTP request. Covers phone number format, sender IDs, segments, delivery status and error handling, with code.
Order confirmations, appointment reminders, delivery updates: some messages need to reach a phone right now, and SMS works on every phone, with or without internet.
This guide shows how to send SMS from Python with SendAPI. By the end you'll have a reusable send_sms() function, a way to check delivery, and error handling you can ship.
Why This Matters
SMS reaches almost any mobile phone, with no app and no data connection needed. That makes it the first choice for short, urgent messages and the backup for every other channel. It's also the channel you pay for per message, so sending it well, with correct numbers, short text and no duplicates, directly lowers your bill.
What you need
- Python 3.10 or newer
- A SendAPI account on a plan that includes SMS (the Free plan is email-only)
- Your API key from the dashboard. It starts with
sk_live_
Step 1: Install requests and store your key
pip install requests
export SENDAPI_KEY="sk_live_your_key_here"
Keep the key in an environment variable, never in your code. Every request uses it as a Bearer token.
Step 2: Send your first SMS
import os
import requests
response = requests.post(
"https://sendapi.co/v1/sms/send",
headers={"Authorization": f"Bearer {os.environ['SENDAPI_KEY']}"},
json={
"to": "+27821234567",
"content": "Your order #1042 has shipped. Track it at https://example.com/t/1042",
},
timeout=10,
)
print(response.json())
The two required fields are to and content. A successful response looks like this (trimmed):
{
"success": true,
"data": {
"id": 32,
"to": "+447700900000",
"segments": 1,
"cost": "$0.0250",
"region": "United Kingdom",
"status": "queued",
"sms_credit_balance": "$1.4000"
}
}
Save the id. You'll use it to check delivery. The cost and sms_credit_balance fields show what the message cost and what credit you have left.
Step 3: Format numbers in E.164
The to number must be in E.164 format: a plus sign, the country code, then the number with no spaces or leading zero.
| Local format | E.164 |
| --- | --- |
| 082 123 4567 (South Africa) | +27821234567 |
| 07700 900000 (UK) | +447700900000 |
| (415) 555-2671 (US) | +14155552671 |
Not sure a number is valid? Check it first. See How to Validate Phone Numbers Before You Send.
Step 4: Show your brand name with a sender ID
Add sender_id to send from a name instead of a number:
json={
"to": "+27821234567",
"content": "Your order #1042 has shipped.",
"sender_id": "AcmeShop",
}
A sender ID can be up to 11 letters and numbers. Some countries require you to register it first. If yours is still pending, SendAPI sends from the default sender and says so in the response. More in How to Choose an SMS Sender ID That Customers Trust.
Step 5: Watch your message length
One SMS segment holds 160 characters. Longer messages are split into 153-character parts, and each part is billed. content can be up to 1,600 characters, but a 200-character message costs twice as much as a 160-character one. The segments field in the response tells you how many you used. See SMS Segments Explained.
Step 6: Wrap it in a reusable function
import os
import uuid
import requests
BASE_URL = "https://sendapi.co/v1"
class SMSError(Exception):
pass
def _headers(idempotency_key: str | None = None) -> dict:
headers = {"Authorization": f"Bearer {os.environ['SENDAPI_KEY']}"}
if idempotency_key:
headers["Idempotency-Key"] = idempotency_key
return headers
def send_sms(to: str, content: str, sender_id: str | None = None,
idempotency_key: str | None = None) -> dict:
"""Send one SMS. Returns the message data, including its id."""
payload = {"to": to, "content": content}
if sender_id:
payload["sender_id"] = sender_id
try:
response = requests.post(
f"{BASE_URL}/sms/send",
# Reuse the same key when retrying, so the SMS is sent only once
headers=_headers(idempotency_key or str(uuid.uuid4())),
json=payload,
timeout=10,
)
except requests.RequestException as exc:
raise SMSError(f"Network error: {exc}") from exc
body = response.json()
if not response.ok or not body.get("success"):
raise SMSError(f"SendAPI returned {response.status_code}: {response.text}")
return body["data"]
Step 7: Check delivery status
def get_sms_status(message_id: int) -> str:
response = requests.get(
f"{BASE_URL}/sms/status/{message_id}",
headers=_headers(),
timeout=10,
)
response.raise_for_status()
return response.json()["data"]["status"]
The status moves through these values:
| Status | Meaning |
| --- | --- |
| queued | Accepted by SendAPI, not sent yet |
| sent | Handed to the carrier |
| delivered | The carrier confirmed delivery |
| failed | Permanent delivery failure |
| rejected | The carrier refused it, e.g. an invalid number or an opt-out |
Some carriers never send delivery receipts, so a message can stay sent even after it arrives. In production, use webhooks instead of polling. See How to Track Message Delivery Status with Webhook Events.
Step 8: Handle errors
| Error | What it means | What to do |
| --- | --- | --- |
| 401 | Key missing, invalid or revoked | Check SENDAPI_KEY |
| 403 channel_not_in_plan | Your plan doesn't include SMS | Upgrade from the Free plan |
| 403 (trial) | You've hit a trial limit | Trials allow 2 SMS in total, to your paired WhatsApp number |
| 422 | Sender ID rejected | Use a registered sender ID or leave it out |
| 429 | Too many requests | Wait for the seconds in Retry-After, then retry |
For timeouts and 5xx errors, retry with the same Idempotency-Key so the customer never gets the message twice. See How to Retry Failed API Requests Without Sending Duplicate Messages.