Send WhatsApp Messages from Django with the TextMeFlow API
Django apps already talk to third-party APIs through requests, so sending WhatsApp messages needs no extra SDK — just a small client class, a Celery task that respects rate-limit backoff, and a webhook view that verifies signatures before touching the request body. This guide covers all three, written to drop into an existing Django project rather than a toy script.
Before you start
- Create a free TextMeFlow account — 50 messages a month, forever, no credit card and no Meta Business verification.
- Scan the QR code from the portal with the phone holding the WhatsApp number you want to send from.
- Copy your API key from the dashboard and your webhook secret from
/admin/webhook.
The full endpoint reference lives at /docs/api; everything below targets POST /v1/messages on https://api.textmeflow.eu.
A client in its own app
Keep the HTTP details out of views and models — a whatsapp app with a single client class is enough:
# whatsapp/client.py
import requests
from django.conf import settings
BASE_URL = "https://api.textmeflow.eu"
class TextMeFlowError(Exception):
pass
class RateLimited(TextMeFlowError):
def __init__(self, reason, retry_after_seconds):
self.reason = reason
self.retry_after_seconds = retry_after_seconds
super().__init__(f"rate limited: {reason}")
def send_message(to, text=None, media_url=None):
payload = {"to": to, "text": text, "media_url": media_url}
payload = {k: v for k, v in payload.items() if v is not None}
response = requests.post(
f"{BASE_URL}/v1/messages",
json=payload,
headers={"Authorization": f"Bearer {settings.TEXTMEFLOW_API_KEY}"},
timeout=10,
)
if response.status_code == 202:
return response.json()
if response.status_code == 429:
body = response.json()
raise RateLimited(body.get("reason"), body.get("retry_after_seconds"))
raise TextMeFlowError(f"unexpected status {response.status_code}: {response.text}")
Keep to in E.164 format (+32472932208) — a number without the leading + and country code is rejected with a 422, and it's the single most common integration bug in any language. media_url is optional and accepts any publicly reachable file up to 100 MB; leave it out for a plain text message. A 202 means the message is queued, not delivered — the message_id in the response is what you use to check real status afterwards, not the HTTP call returning successfully.
Add the key to settings from the environment, not hardcoded:
# settings.py
TEXTMEFLOW_API_KEY = os.environ["TEXTMEFLOW_API_KEY"]
TEXTMEFLOW_WEBHOOK_SECRET = os.environ["TEXTMEFLOW_WEBHOOK_SECRET"]
Retrying on 429 with Celery
Since most Django projects already run Celery for anything that hits an external API, let the task's own retry policy handle the wait instead of a blocking time.sleep in a request-response cycle:
# whatsapp/tasks.py
from celery import shared_task
from .client import send_message, RateLimited, TextMeFlowError
@shared_task(bind=True, max_retries=5)
def send_whatsapp_message(self, to, text):
try:
send_message(to=to, text=text)
except RateLimited as exc:
raise self.retry(exc=exc, countdown=exc.retry_after_seconds or 2 ** self.request.retries * 5)
except TextMeFlowError:
raise
A 429 body always includes reason (burst_exceeded or hourly_exceeded) and retry_after_seconds, documented on the rate limits page — countdown reads that value directly instead of guessing a backoff interval. For the broader question of polling GET /v1/messages/{id} versus trusting webhooks for delivery status, see handling rate limits and message status.
Verifying inbound webhooks in a view
Customer replies are POSTed to whatever endpoint you configure in /admin/webhook, signed with HMAC-SHA256 over the raw request body in an X-TextMeFlow-Signature: sha256=<hex> header. Django's CSRF middleware and request.POST both expect form data, so this has to be a plain @csrf_exempt view that reads request.body before anything parses it:
# whatsapp/views.py
import hmac
import hashlib
import json
from django.conf import settings
from django.http import HttpResponse, HttpResponseForbidden
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from .models import ProcessedWebhookEvent
from .tasks import handle_incoming_message
@csrf_exempt
@require_POST
def textmeflow_webhook(request):
raw = request.body
expected = "sha256=" + hmac.new(
settings.TEXTMEFLOW_WEBHOOK_SECRET.encode(), raw, hashlib.sha256
).hexdigest()
received = request.headers.get("X-TextMeFlow-Signature", "")
if not hmac.compare_digest(expected, received):
return HttpResponseForbidden()
event_id = request.headers.get("X-TextMeFlow-Event-Id")
if ProcessedWebhookEvent.objects.filter(event_id=event_id).exists():
return HttpResponse(status=200)
ProcessedWebhookEvent.objects.create(event_id=event_id)
handle_incoming_message.delay(json.loads(raw))
return HttpResponse(status=200)
hmac.compare_digest runs in constant time — use it instead of ==, which short-circuits on the first mismatched byte and leaks timing information. X-TextMeFlow-Event-Id stays stable across retries, so a unique constraint on that column in ProcessedWebhookEvent is enough to avoid handling the same inbound message twice: TextMeFlow retries undelivered webhooks up to 5 times with increasing backoff, and anything but a 2xx within 10 seconds counts as a failed attempt. Returning 200 immediately and handing the real work to a Celery task via .delay() matters here — a slow view looks identical to a timeout from TextMeFlow's side and triggers a needless retry. The full header list and payload shape are in the webhook docs; the signature mechanics are covered in more depth, with PHP/Python/Node side by side, in verifying WhatsApp webhook signatures.
Wire the URL as usual:
# urls.py
from whatsapp.views import textmeflow_webhook
urlpatterns = [
path("webhooks/textmeflow/", textmeflow_webhook, name="textmeflow-webhook"),
# ...
]
Wrapping up
A Django integration needs three pieces: a requests-based client that reads the API key from settings, a Celery task whose retry countdown respects retry_after_seconds instead of a fixed sleep, and a CSRF-exempt view that checks the HMAC signature with hmac.compare_digest before it does anything else with the payload — no extra dependency beyond what a typical Django stack already has. Start free and you can have a send task and a webhook view both running before your next deploy.
Want to send WhatsApp messages via API yourself?
Free forever up to 50 messages/month. Scan a QR and send your first message within 5 minutes.
Free forever