Part of the guide SMS API Documentation: Android SMS Gateway, OTP and Webhooks
On this page
- Key takeaways
- How does the SMS8 API work?
- How do I send an SMS with curl?
- How do I send SMS from Node.js?
- How do I send SMS from Python?
- How do I send SMS from PHP?
- How do I receive SMS with webhooks?
- What errors can the SMS API return?
- How do I retry without sending the same SMS twice?
- How fast can I send, and how should I pace bulk sends?
- What does it cost?
- Where to go next
- Why developers choose SMS8
Key takeaways
- One endpoint sends everything:
POST https://app.sms8.io/api/v1/messageswithnumberandmessage, and your key in theX-Api-Keyheader. - The body is a normal form post. Every answer is JSON with a
successflag, and you must read it, because some errors come back inside a 200 response. - Receive messages with signed webhooks. Verify
X-Signature(HMAC-SHA256 of the raw body) with a constant-time compare. - Retry on network errors, not on refusals. SMS8 ignores an identical payload repeated within five minutes, and you can pass an
idempotencyKey. - The API has no artificial rate limit. Your SIMs set the pace: about one message every 10 to 30 seconds per SIM for bulk sends.
An SMS API lets your code send a text with one HTTP request and get replies back as events. With SMS8 the request goes to app.sms8.io, and the message leaves from an Android phone you paired, using its own SIM. That means no number to rent, no per-message fee and no A2P 10DLC filing, and it also means a few things behave differently from a cloud provider: throughput depends on your phones, and a phone that goes offline holds messages until it is back. This guide shows the same send and receive in Node, Python, PHP and curl, then covers webhooks, errors, retries and pacing.
This is a hands-on companion to the SMS8 API documentation, which lists every endpoint. The full field reference with a live request builder is in your dashboard under API.
How does the SMS8 API work?
- Your code POSTs a message to
/api/v1/messages. - SMS8 checks the key and credits, stores the message as queued and wakes your paired phone.
- The phone sends it from its SIM and reports back: sent, then delivered or failed.
- Replies that arrive on the phone are pushed to your webhook as they come in.
Authentication is the same everywhere: your API key in the X-Api-Key header. A bearer token in Authorization or a form field called key also work, for tools that cannot set custom headers. Keep the key on your server. If it ends up in a browser bundle or a public repo, rotate it from the dashboard.
How do I send an SMS with curl?
Start here to confirm the account, the phone and the key all work before writing code.
curl -X POST https://app.sms8.io/api/v1/messages \
-H "X-Api-Key: $SMS8_API_KEY" \
--data-urlencode "number=+14155550100" \
--data-urlencode "message=Hello from the SMS8 API"
A success looks like this, trimmed:
{
"success": true,
"data": { "messages": [ { "ID": 128476, "number": "+14155550100", "status": "Pending", ... } ] },
"error": null
}
A failure keeps the same shape, with success false and an error object holding a code and a message.
How do I send SMS from Node.js?
The sms8-sdk package gives you typed methods and works in Node 18 and newer, Bun, Deno and edge runtimes.
npm install sms8-sdk
import { Sms8 } from 'sms8-sdk';
const sms8 = new Sms8({ apiKey: process.env.SMS8_API_KEY });
const res = await sms8.sendSMS({
phone: '+14155550100',
message: 'Your order #4412 has shipped',
});
if (!res.success) {
console.error('send refused:', res.error);
} else {
console.log('queued as', res.messageId);
}
Routing options go in the same object: deviceId and simSlot to pick the sender, option (0 for the listed device, 1 to rotate across phones, 2 to rotate across SIMs), randomDevice, attachments for MMS and prioritize to jump the queue. The SDK also has listDevices(), getBalance(), getMessages(), sendOTP() and verifyOTP().
Reading recent replies from Node is one call:
const { messages } = await sms8.getMessages({ direction: 'received', limit: 20 });
for (const m of messages) console.log(m.number, m.message);
Use this for scripts and dashboards. For a live app, use webhooks, covered below.
How do I send SMS from Python?
No SDK needed. requests and a form body are enough.
import os, requests
API = "https://app.sms8.io/api/v1"
HEADERS = {"X-Api-Key": os.environ["SMS8_API_KEY"]}
def send_sms(number: str, text: str) -> int:
r = requests.post(f"{API}/messages", headers=HEADERS,
data={"number": number, "message": text}, timeout=30)
r.raise_for_status()
body = r.json()
if not body.get("success"):
raise RuntimeError(f"SMS8 refused: {body['error']}")
return body["data"]["messages"][0]["ID"]
msg_id = send_sms("+14155550100", "Your appointment is tomorrow at 10:00")
To pull messages received in the last hour, call the read endpoint with a status filter and a start time:
import time
r = requests.post(f"{API}/messages/read", headers=HEADERS, data={
"status": "Received",
"startTimestamp": int(time.time()) - 3600,
"limit": 100,
}, timeout=30)
body = r.json()
inbox = body["data"]["messages"] if body.get("success") else []
Note that an empty result comes back as success: false with error code 404, "no messages found". Treat that code as an empty list, not as a failure.
How do I send SMS from PHP?
The dashboard offers a ready PHP class with a method per endpoint, for PHP 7.4 and newer. If you prefer no dependency, plain curl works:
<?php
function sms8_send(string $number, string $text): array {
$ch = curl_init('https://app.sms8.io/api/v1/messages');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => ['X-Api-Key: ' . getenv('SMS8_API_KEY')],
CURLOPT_POSTFIELDS => http_build_query(['number' => $number, 'message' => $text]),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
]);
$raw = curl_exec($ch);
if ($raw === false) throw new RuntimeException(curl_error($ch));
$body = json_decode($raw, true);
if (empty($body['success'])) {
throw new RuntimeException($body['error']['message'] ?? 'unknown error');
}
return $body['data']['messages'][0];
}
$msg = sms8_send('+14155550100', 'Your password was changed. Not you? Reply HELP.');
WordPress and WooCommerce users can skip the code entirely with the official plugin.

How do I receive SMS with webhooks?
Register an HTTPS URL on the Webhooks page of the dashboard, pick the events (received, sent, delivered, failed and more), and SMS8 POSTs JSON to it as things happen. Each webhook has its own signing secret, separate from your API key. A received message looks like this:
POST /sms8/webhook
Content-Type: application/json
X-Signature: sha256=4f3a...
{
"event": "messages",
"timestamp": "2026-11-16T14:22:31+00:00",
"userID": 42,
"data": [
{ "ID": 128476, "number": "+14155550100", "message": "Yes, confirmed", "deviceID": 42, "simSlot": 0 }
]
}
Verify the signature
X-Signature is sha256= followed by the hex HMAC-SHA256 of the raw request body, keyed with the webhook secret. Compute it over the raw bytes, before any JSON parsing, and compare in constant time.
Node with Express:
import crypto from 'node:crypto';
import express from 'express';
const app = express();
app.post('/sms8/webhook', express.raw({ type: 'application/json' }), (req, res) => {
const expected = 'sha256=' + crypto
.createHmac('sha256', process.env.SMS8_WEBHOOK_SECRET)
.update(req.body)
.digest('hex');
const received = req.get('X-Signature') || '';
const ok = received.length === expected.length &&
crypto.timingSafeEqual(Buffer.from(received), Buffer.from(expected));
if (!ok) return res.sendStatus(401);
res.sendStatus(200); // answer fast
const event = JSON.parse(req.body.toString('utf8'));
queue.push(event); // do slow work later
});
Python with Flask:
import hmac, hashlib, os
from flask import Flask, request, abort
app = Flask(__name__)
SECRET = os.environ["SMS8_WEBHOOK_SECRET"].encode()
@app.post("/sms8/webhook")
def sms8_webhook():
raw = request.get_data()
expected = "sha256=" + hmac.new(SECRET, raw, hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, request.headers.get("X-Signature", "")):
abort(401)
enqueue(request.get_json())
return "", 200
PHP:
$raw = file_get_contents('php://input');
$expected = 'sha256=' . hash_hmac('sha256', $raw, getenv('SMS8_WEBHOOK_SECRET'));
if (!hash_equals($expected, $_SERVER['HTTP_X_SIGNATURE'] ?? '')) {
http_response_code(401); exit;
}
http_response_code(200);
$event = json_decode($raw, true);
Webhook rules that prevent most bugs
- Answer within 10 seconds with a 2xx status. Do CRM lookups, AI classification and database writes after responding.
- Expect retries. If your server is down or slow, SMS8 tries again on a growing schedule for up to 30 days, and every attempt shows in the deliveries log.
- Deduplicate by message ID. A retried event carries the same
ID. Store it with a unique index and skip anything you have seen. - HTTPS only. Plain HTTP receivers are not accepted.
Should you poll instead? Rarely. The full trade-off, with a clean polling loop for the cases that need one, is in webhook vs polling for incoming SMS.
What errors can the SMS API return?
| Situation | What you see | What to do |
|---|---|---|
| Missing or wrong key | Error code 401 | Fix the key. Do not retry |
| Missing or malformed fields | Error code 400 | Fix the request. Do not retry |
| Refused inside a normal answer, for example no credits left | success: false with an error message | Log and alert. Retrying will not help |
| No messages match a read | Error code 404 | Treat as an empty list |
| Server error | Error code 500 or an HTTP 5xx | Retry with backoff |
| Timeout or connection reset | No answer | Retry with backoff. The duplicate guard below protects you |
Message status failed, result code 4 | Webhook or lookup | The phone had no signal. Resend once it is back |
The key habit: check the success flag on every response, not just the HTTP status.
How do I retry without sending the same SMS twice?
The classic bug is a client that times out while the server is still accepting the message, retries, and sends two texts. SMS8 guards against this on the send endpoint: an identical request from the same account within a five-minute window gets the first response back instead of a second send. You can make it explicit by passing an idempotencyKey field, for example your order ID plus the message type.
class Permanent extends Error {}
async function sendWithRetry(number, message, key, attempts = 4) {
for (let i = 0; i < attempts; i++) {
try {
const r = await fetch('https://app.sms8.io/api/v1/messages', {
method: 'POST',
headers: { 'X-Api-Key': process.env.SMS8_API_KEY },
body: new URLSearchParams({ number, message, idempotencyKey: key }),
signal: AbortSignal.timeout(30_000),
});
const body = await r.json();
if (body.success) return body.data.messages[0];
const code = body.error?.code;
if (r.status < 500 && code !== 500) throw new Permanent(body.error?.message);
} catch (e) {
if (e instanceof Permanent || i === attempts - 1) throw e; // 400, 401, no credits: stop
}
await new Promise((res) => setTimeout(res, 2 ** i * 1000)); // 1s, 2s, 4s
}
throw new Error('SMS8 send failed after retries');
}
For a message that the phone later reports as failed, do not resend a new copy from your code. Put the original back in the queue with POST /api/v1/messages/resend and its ID, so your records keep one message per intent.
How fast can I send, and how should I pace bulk sends?
The API itself has no artificial rate limit, so you will not get throttled for sending a burst of requests. The physical limit is the SIM. For bulk sends, plan on one message every 10 to 30 seconds per SIM. That pace keeps the phone's queue healthy and keeps your sending pattern close to a person texting, which protects the SIM from carrier filtering.
- Queue on your side and drain it at the pace above, or submit and let the phone queue work through it.
- Add phones to scale. Set
option=1to rotate across every paired phone, oroption=2to use every SIM including both slots of dual-SIM phones. - Use
prioritize=1for codes and alerts so they jump ahead of a running batch. - Schedule with the
schedulefield (a Unix timestamp) instead of keeping a timer in your app. - Watch the phones.
GET /api/v1/devicesreturns battery, signal and last seen time. Check it before a large send.
What does it cost?
SMS8 charges a flat monthly fee per connected phone, not per message: USD 29 a month for 1 phone, USD 89 for 5 and USD 229 for 20, unlimited SMS and MMS, and yearly billing at half price. The trial gives you 3 days and 30 messages with no card. Your mobile plan on the SIM applies, so use one with unlimited texting. Details on the pricing page.
Where to go next
- Sending pictures: how to send MMS through an API.
- Shell scripts, cron and CI: send SMS from the terminal with the sms8 CLI.
- Letting an assistant write and run this for you: Claude Code SMS with MCP.
- Phone verification flows: the SMS OTP verification API.
Why developers choose SMS8
SMS8 is the SMS API without a number to rent or a meter to watch.
- A developer-friendly API.
POST https://app.sms8.io/api/v1/messageswith anX-Api-Keyheader, signed webhooks retried for up to 30 days, andnpm install sms8-sdkfor the SDK and thesms8CLI. - Your own number. Texts leave from the SIM in your own Android phone, so customers see a number they know and can reply to.
- A flat price with unlimited messages. USD 29 a month for one phone or Mac, USD 89 for five and USD 229 for twenty, with unlimited SMS and MMS and no per-message fee. Yearly billing is half the price.
- No A2P 10DLC filing. Texts go person-to-person from your SIM, so there is no brand, campaign or monthly campaign fee to manage.
- Made for AI agents. Connect Claude Code with
claude mcp add --transport http sms8 https://mcp.sms8.io, or any MCP client through the hosted server ornpx -y sms8-sdk mcp. - OTP built in. Send and verify a code in two calls, from your own number, with no fee per code.
Start the 3-day trial with 30 messages and no card, or compare plans on the SMS8 pricing page.