To send an SMS from a Flask app, add a route that calls POST /v1/messages with the requests library, an X-API-Key header, a hard timeout and an Idempotency-Key header. Keep the key in an environment variable, and create the idempotency key once per message so a retry never texts the customer twice.
That is the whole request. The rest of this post is the Flask-shaped parts: a session you build once, a route that does not hang a worker, a place to keep the key, and a sketch of the route a provider calls when a customer replies. We make Ready, so the examples use its API, but the structure carries to any provider that takes JSON over HTTPS.
What the request looks like
One call sends one text. The body takes to in E.164 format, the message body, and consent_attested, which is your statement that the recipient agreed to receive texts. Auth is the X-API-Key header and the base URL is https://api.tryready.com.
curl -X POST https://api.tryready.com/v1/messages \
-H "X-API-Key: $READY_API_KEY" \
-H "Idempotency-Key: 6f1c2a54-0d3e-4c5b-9a77-2b8f0e1d3c91" \
-H "Content-Type: application/json" \
-d '{"to": "+12125550199", "body": "Your order #1042 has shipped.", "consent_attested": true}' If you leave out from, Ready picks the number: the one this contact already texts with, otherwise your number closest to their area code. The full request reference is in the messages API docs.
A small client module
Flask apps usually grow a services or clients module. Put the HTTP code there so routes stay thin and tests can stub one function. A requests.Session reuses the connection, and a default timeout on every call means no request can wait forever.
# sms_client.py
import os
import requests
BASE_URL = "https://api.tryready.com"
TIMEOUT = (3.05, 10) # connect, read, in seconds
_session = requests.Session()
_session.headers.update({"Content-Type": "application/json"})
class SmsError(Exception):
def __init__(self, status, body):
super().__init__(f"sms send failed: {status}")
self.status = status
self.body = body
def send_sms(to, body, idempotency_key):
resp = _session.post(
f"{BASE_URL}/v1/messages",
headers={
"X-API-Key": os.environ["READY_API_KEY"],
"Idempotency-Key": idempotency_key,
},
json={"to": to, "body": body, "consent_attested": True},
timeout=TIMEOUT,
)
if resp.status_code >= 400:
raise SmsError(resp.status_code, resp.text)
return resp.json() Two details. requests has no default timeout, so the timeout argument is not optional in production code. And the key is read inside the function from the environment, so it is never in source control and a rotated key needs a restart, not a deploy.
The route
Here is a route that sends a shipping notice. The important line is where the idempotency key comes from.
# app.py
import uuid
from flask import Flask, jsonify, request
import requests
from sms_client import send_sms, SmsError
app = Flask(__name__)
@app.post("/orders/<int:order_id>/notify")
def notify_shipped(order_id):
order = load_order(order_id) # your own data access
key = order.shipped_sms_key or str(uuid.uuid4())
if not order.shipped_sms_key:
save_sms_key(order_id, key) # store it before the first attempt
try:
result = send_sms(
order.phone,
f"Your order #{order.id} has shipped.",
key,
)
except requests.Timeout:
return jsonify(status="unknown", retry=True), 202
except SmsError as err:
if err.status == 409:
return jsonify(status="held", detail=err.body), 202
return jsonify(status="failed", detail=err.body), 502
return jsonify(status="sent", result=result), 200 The key is generated once and saved on the order. A second click, a second worker or a retried request all reuse it. A fresh uuid4() per attempt would defeat the header, because the server would see every attempt as a new message. Our post on duplicate texts and idempotency keys walks through the failure in detail.
Which failures to retry
A timeout is the awkward case. Your request may have died before it arrived, or the text may have gone out and the answer got lost. With the same idempotency key, retrying is safe in both cases.
| Outcome | What to do |
|---|---|
| Network error or timeout | Retry later with the same key |
| 429 or a 5xx response | Retry with backoff and the same key; the error reference says which statuses are safe to repeat |
| 409 QUIET_HOURS_BLOCK | Not a failure. The text is not sent, so send it again once the window opens, or pass hold_until_allowed: true to let Ready hold it |
| Other 4xx | Do not retry. Record the reason and fix the data |
Quiet hours are the one that surprises people. An API text is held only if the window opens within <span data-figure="QUIET_HOLD_SINGLE_HRS">6</span> hours. Otherwise the API answers 409 QUIET_HOURS_BLOCK, and the sender sends it again once the window opens. With hold_until_allowed: true in the body, Ready holds it up to <span data-figure="QUIET_HOLD_CAMPAIGN_HRS">24</span> hours like a campaign text. Exact error bodies are in the error reference.
Do the retry outside the request
A Flask worker that sleeps through a backoff is a worker that cannot serve anyone else. For anything that is not a one-time code, write the send to a table or a queue and let a worker process do it. Celery and RQ both work, and our Django and Celery post shows the outbox pattern, which transfers directly to Flask. The route then returns 202 right away, and the job carries its idempotency key from creation to the last retry.
For a login code, latency matters more than queueing, so call send_sms in the request, keep the timeout short, and show the user a resend button.
An inbound webhook route sketch
When a customer replies, or when a delivery report arrives, the provider calls a URL on your app. We are not showing payload field names or a signature header here, because those come from the provider's docs and guessing them is how integrations break. The generic names below stand in for whatever your provider documents.
import hashlib
import hmac
import os
SIGNING_SECRET = os.environ["WEBHOOK_SIGNING_SECRET"]
def signature_ok(raw_body: bytes, received: str) -> bool:
# Replace the scheme with what your provider documents.
expected = hmac.new(SIGNING_SECRET.encode(), raw_body, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, received or "")
@app.post("/webhooks/sms")
def sms_webhook():
raw = request.get_data() # exact bytes, before any JSON parsing
if not signature_ok(raw, request.headers.get("X-Signature-Placeholder")):
return "", 401
event = request.get_json(silent=True) or {}
enqueue_inbound_event(event) # store first, process later
return "", 200 Read the raw bytes before parsing, verify the signature over them, store the event, and return 200 fast. Do the real work in a job. Names such as X-Signature-Placeholder are placeholders; take the real header, algorithm and payload fields from the API quickstart and the error reference. For the full pattern, see receiving inbound SMS webhooks.
Test it without texting anyone
Wrap send_sms behind a function you can patch. With pytest, monkeypatch.setattr("app.send_sms", fake) is enough to test the route's three branches: sent, held and unknown. For the live path, use a test key if your account has one, or send to your own phone first. Our sandbox and test numbers post covers the options.
Cost and setup
A text on Ready's Standard rate is <span data-figure="STANDARD_RATE">$0.0075</span> per segment plus a <span data-figure="CARRIER_FEE">$0.0045</span> carrier fee, which is <span data-figure="STANDARD_ALL_IN">$0.012</span> all-in per segment. That all-in figure does not include screening, the optional scrub and number validation, each <span data-figure="COMPLIANCE_SURCHARGE">$0.003</span> extra per segment when switched on. A card on file and a number of your own (<span data-figure="NUMBER_MONTHLY">$2</span> a month) are required to send. An account can send up to <span data-figure="UNREGISTERED_TEXT_CAP">500</span> texts a month before it registers for 10DLC, and most approvals take <span data-figure="REGISTRATION_APPROVAL">2 to 7 days</span>. Accounts opened before November 12, 2026 keep the prices they signed up with, shown under Billing.
Ready's all-in prices per segment include the carrier fee but not screening: Scrub lists and Number validation, the two switches in Settings under Compliance, each add $0.003 per segment when switched on, shown as screening on your bill, and both are off by default. Unless you turn the opt-out footer off, the first text to each contact, and one again from time to time, also gets "Reply STOP to opt out" and your business name if the message does not already have them, so a text close to the segment limit can bill one more segment.
The short version
In Flask, the pieces that matter are small: a session with a timeout, a key kept outside the code, an idempotency key stored with the thing you are notifying about, and a webhook route that verifies, stores and answers fast. Everything else is ordinary Flask. When you are ready to try it, create an account and follow the quickstart.