How to Send WhatsApp Notifications from a Python Flask App
Send WhatsApp notifications from a Python Flask app with Celery: retry without duplicate sends, verify signed webhooks and test free in the sandbox.

To send WhatsApp notifications from a Flask app, make an HTTPS POST to https://developers-api.chatmaid.net/v1/messages/send with your Chatmaid API key as a Bearer token and a JSON body holding the sender number (fromPhoneId), the recipient (to) and the text (content). In production, run that call in a Celery task so your routes answer right away, protect retries with an idempotency key, and receive replies and delivery updates on a signed webhook route. Messages go out from your own WhatsApp number, linked by scanning a QR code, with no Meta Business verification.
This tutorial builds that setup one file at a time. Every snippet runs against the free sandbox, so you can finish it before paying for anything.
What you need before you start
- Python 3.10 or newer. The code uses
str | Nonetype hints. - A Redis server for Celery. A local one is enough:
docker run --rm -p 6379:6379 redis:7. - A Chatmaid Developers account. Create one for free from the Chatmaid Developers page.
- A sandbox API key. Keep the dashboard switch on Test Mode, open API Keys and create a key. Sandbox keys start with
sk_test_, and new keys come with themessages:sendandmessages:readscopes this tutorial needs. - A sender number. Still in Test Mode, add a number under Phone Numbers. Sandbox numbers connect automatically; a live number connects when you scan the QR code with WhatsApp on that phone.
Install the packages:
pip install flask requests "celery[redis]" python-dotenvThe finished project has five Python files, a test script and a .env:
flask-whatsapp/
├── .env
├── config.py
├── chatmaid_client.py
├── tasks.py
├── webhook.py
├── app.py
└── send_test_event.pyPut your settings in .env. You will get the webhook secret later in this tutorial, so leave the placeholder for now.
CHATMAID_API_KEY=sk_test_xxxxxxxxxxxxxxxxxxxxxxxx
CHATMAID_SENDER=+15551234567
CHATMAID_WEBHOOK_SECRET=whsec_xxxxxxxxxxxxxxxxxxxxxxxx
REDIS_URL=redis://localhost:6379/0config.py loads them once, so the Flask process and the Celery worker read the same values:
import os
from dotenv import load_dotenv
load_dotenv()
CHATMAID_API_KEY = os.environ["CHATMAID_API_KEY"]
CHATMAID_SENDER = os.environ["CHATMAID_SENDER"]
CHATMAID_WEBHOOK_SECRET = os.environ.get("CHATMAID_WEBHOOK_SECRET", "")
REDIS_URL = os.environ.get("REDIS_URL", "redis://localhost:6379/0")How do you send a WhatsApp message from Python?
One request does it. fromPhoneId is your sender, given as its E.164 number (or its dashboard ID). to is the recipient in E.164 format, with the plus sign and country code.
import os
import requests
response = requests.post(
"https://developers-api.chatmaid.net/v1/messages/send",
headers={"Authorization": f"Bearer {os.environ['CHATMAID_API_KEY']}"},
json={
"fromPhoneId": "+15551234567",
"to": "+15557654321",
"content": "Your order #1042 has shipped.",
},
timeout=30,
)
print(response.status_code, response.json())A successful send answers HTTP 201 with the message wrapped in a success envelope:
{
"success": true,
"data": {
"id": "msg_abc123def456",
"from": "+15551234567",
"to": "+15557654321",
"isGroup": false,
"groupId": null,
"content": "Your order #1042 has shipped.",
"mediaUrls": [],
"status": "sent",
"errorCode": null,
"errorMessage": null,
"createdAt": "2026-10-22T14:18:33.000Z",
"sentAt": "2026-10-22T14:18:33.120Z",
"deliveredAt": null,
"readAt": null,
"failedAt": null
}
}Keep data.id. It is the ID you use to look the message up later and to match webhook events to it.
A failed send answers with a non-2xx status. For a send that failed after it was recorded, error holds one of the stable codes, such as RECIPIENT_NOT_REACHABLE; for a request the API rejected, it is a generic label such as Bad Request. message is a list of readable explanations, and when the API had already recorded the message, messageId and status are included too:
{
"success": false,
"error": "RECIPIENT_NOT_REACHABLE",
"message": [
"The message could not be delivered to this recipient. They may need to message you first, or may not be reachable on WhatsApp."
],
"statusCode": 422,
"timestamp": "2026-10-22T14:18:34.000Z",
"path": "/v1/messages/send",
"messageId": "msg_abc123def457",
"status": "failed"
}Build a reusable Chatmaid client
Wrap the API in a small class so the rest of your app never builds requests by hand. Save this as chatmaid_client.py:
from dataclasses import dataclass
import requests
API_BASE = "https://developers-api.chatmaid.net/v1"
@dataclass
class SendResult:
ok: bool
http_status: int | None = None # None means the request never got an answer
message_id: str | None = None
status: str | None = None
error: str | None = None
detail: str | None = None
retry_after: int | None = None
class ChatmaidClient:
def __init__(self, api_key: str, sender: str, timeout: float = 30):
self.sender = sender
self.timeout = timeout
self.session = requests.Session()
self.session.headers["Authorization"] = f"Bearer {api_key}"
def send(
self,
to: str,
content: str | None = None,
media_urls: list[str] | None = None,
idempotency_key: str | None = None,
) -> SendResult:
body = {"fromPhoneId": self.sender, "to": to}
if content:
body["content"] = content
if media_urls:
body["mediaUrls"] = media_urls
if idempotency_key:
body["idempotencyKey"] = idempotency_key
try:
response = self.session.post(
f"{API_BASE}/messages/send", json=body, timeout=self.timeout
)
except requests.RequestException as exc:
return SendResult(ok=False, error="NETWORK_ERROR", detail=str(exc))
try:
payload = response.json()
except ValueError:
payload = {}
if response.ok and payload.get("success"):
data = payload.get("data") or {}
return SendResult(
ok=True,
http_status=response.status_code,
message_id=data.get("id"),
status=data.get("status"),
)
messages = payload.get("message") or []
if isinstance(messages, str):
messages = [messages]
return SendResult(
ok=False,
http_status=response.status_code,
message_id=payload.get("messageId"),
status=payload.get("status"),
error=payload.get("error") or f"HTTP_{response.status_code}",
detail="; ".join(messages),
retry_after=payload.get("retryAfter"),
)
def get_message(self, message_id: str) -> dict:
response = self.session.get(
f"{API_BASE}/messages/{message_id}", timeout=self.timeout
)
response.raise_for_status()
return response.json()["data"]A few choices here matter later:
- It returns a result instead of raising. Your caller decides what a failure means, which is what the retry logic below needs.
- It separates "no answer" from "an error answer". When the network fails,
http_statusstaysNone, because you cannot know whether the request reached the API. - The timeout is generous. A live send waits for WhatsApp to accept the message before the API answers, so give it 30 seconds rather than 5.
- Media is one argument away. Pass public HTTPS links in
media_urlsto attach images or documents; plainhttp://links are rejected. With one link,contentbecomes its caption; with several,contentis sent first as its own message.
Send a notification from a Flask route
The simplest integration calls the client inside the route. Save this first version as app.py:
import re
from flask import Flask, jsonify, request
import config
from chatmaid_client import ChatmaidClient
E164 = re.compile(r"^\+[1-9]\d{1,14}$")
app = Flask(__name__)
chatmaid = ChatmaidClient(config.CHATMAID_API_KEY, config.CHATMAID_SENDER)
@app.post("/notify")
def notify():
body = request.get_json(silent=True) or {}
to, text = body.get("to", ""), body.get("text", "")
if not E164.match(to) or not text:
return jsonify(error="to (E.164 format) and text are required"), 400
result = chatmaid.send(to, text)
if result.ok:
return jsonify(sent=True, message_id=result.message_id, status=result.status), 201
return jsonify(sent=False, error=result.error, detail=result.detail), 502Run it on port 8000 (on a Mac, port 5000 is often taken by AirPlay Receiver) and call it from a second terminal:
# Terminal 1
flask --app app run --port 8000# Terminal 2
curl -X POST http://localhost:8000/notify \
-H "Content-Type: application/json" \
-d '{"to": "+15557654321", "text": "Hello from Flask"}'With a sandbox key, nothing reaches WhatsApp: the API simulates the send and answers "status": "sent". That makes it safe to run as often as you like.
Move sends to a Celery worker
The first version works, but the user who clicked "Ship order" now waits for a WhatsApp round trip, and a slow or failed send turns into a failed page. Move the send to a background worker. Save this as tasks.py:
import hashlib
import logging
import redis
from celery import Celery
import config
from chatmaid_client import ChatmaidClient, SendResult
celery = Celery("tasks", broker=config.REDIS_URL)
chatmaid = ChatmaidClient(config.CHATMAID_API_KEY, config.CHATMAID_SENDER)
store = redis.Redis.from_url(config.REDIS_URL, decode_responses=True)
log = logging.getLogger(__name__)
OPTED_OUT = "whatsapp:opted_out"
# Test and live keys share idempotency keys, so mix the environment into each one.
ENV = "live" if config.CHATMAID_API_KEY.startswith("sk_live_") else "test"
def make_key(*parts: str) -> str:
"""Stable idempotency key (48 chars) built from your own identifiers."""
return hashlib.sha256(":".join((ENV, *parts)).encode()).hexdigest()[:48]
def retry_plan(result: SendResult) -> str | None:
if not result.message_id:
# No message was recorded: the request failed on the way, hit the
# API rate limit, or the server had a problem before sending.
if result.http_status is None or result.http_status == 429 or result.http_status >= 500:
return "same-key"
return None
if result.error in ("RATE_LIMITED", "SERVICE_UNAVAILABLE"):
# Recorded as failed. The old key would replay that failure.
return "new-key"
return None
@celery.task(bind=True, max_retries=5)
def send_whatsapp(self, to: str, text: str, key: str, generation: int = 0):
if store.sismember(OPTED_OUT, to):
log.info("skipping %s: opted out", to)
return {"skipped": "opted_out"}
# generation counts deliberate new-key attempts only: key, key-r1, key-r2...
attempt_key = key if generation == 0 else f"{key}-r{generation}"
result = chatmaid.send(to, text, idempotency_key=attempt_key)
if result.ok:
log.info("sent %s to %s (%s)", result.message_id, to, result.status)
return {"message_id": result.message_id, "status": result.status}
plan = retry_plan(result)
reason = RuntimeError(f"{result.error}: {result.detail}") # shown if retries run out
if plan == "same-key":
raise self.retry(exc=reason, countdown=result.retry_after or 30)
if plan == "new-key":
kwargs = {**(self.request.kwargs or {}), "generation": generation + 1}
raise self.retry(exc=reason, kwargs=kwargs, countdown=120)
log.error("WhatsApp send to %s failed: %s %s", to, result.error, result.detail)
return {"error": result.error, "message_id": result.message_id}Now replace app.py with a version that queues the send and returns at once. This example notifies a customer when an order ships:
import re
from flask import Flask, jsonify, request
from tasks import make_key, send_whatsapp
E164 = re.compile(r"^\+[1-9]\d{1,14}$")
app = Flask(__name__)
@app.post("/orders/<order_id>/shipped")
def order_shipped(order_id):
body = request.get_json(silent=True) or {}
phone, tracking = body.get("phone", ""), body.get("tracking", "")
if not E164.match(phone) or not tracking:
return jsonify(error="phone (E.164) and tracking are required"), 400
text = f"Good news: order {order_id} has shipped. Tracking number: {tracking}."
send_whatsapp.delay(phone, text, make_key("order-shipped", order_id))
return jsonify(queued=True), 202Start the worker and the web app in two terminals:
# Terminal 1
celery -A tasks worker --loglevel=info# Terminal 2
flask --app app run --port 8000Why every send gets an idempotency key
idempotencyKey (up to 64 characters, scoped to your account and shared by your test and live keys) tells Chatmaid that two requests are the same notification. If a request arrives with a key that was already used, the API returns the original message instead of sending a second one. make_key("order-shipped", order_id) builds the key from your own data, so a re-run job or a retried task will not send the same shipping notice twice. Two requests that arrive at the same instant are not guaranteed to be merged, so also block double clicks in your app, for example with a Redis SET NX on the key before you call send_whatsapp.delay.
Because test and live keys share the same idempotency keys, a key you used in the sandbox would replay that simulated message after you go live, and nothing would be sent. make_key adds the environment to every key to prevent this.
There is one more rule to remember: the same key always gets the same answer, failures included. If a send failed, retrying with its old key just replays the failure. That is why the task appends -r1, -r2 and so on when it deliberately tries again, counting only those deliberate attempts so a re-run of the same job lands on the same keys.
Which errors should you retry?
retry_plan sorts failures into three groups. The table shows how each error is handled and why.
| Error | What it means | What the task does |
|---|---|---|
| No response (timeout or connection error) | You cannot tell whether the request arrived | Retries with the same key, so a send that did arrive is not repeated |
| HTTP 429 without a messageId | You hit the API's request limit (100 requests a minute by default) | Retries with the same key after the retryAfter seconds |
| HTTP 5xx without a messageId | The API failed before recording a message | Retries with the same key |
| RATE_LIMITED | WhatsApp is temporarily throttling sends | Retries with a new key after 2 minutes |
| SERVICE_UNAVAILABLE | WhatsApp or the send service is briefly unavailable | Retries with a new key after 2 minutes |
| TIMEOUT | WhatsApp did not answer in time; the message may have gone out | Does not retry; check it before sending again |
| HTTP 500 with a messageId (error is InternalServerError) | Something failed after the message was recorded; it may have gone out | Does not retry; check the message before resending |
| MEDIA_ERROR | A media link could not be fetched or is not a supported type | Does not retry; fix the link |
| NOT_CONNECTED or NOT_AUTHORIZED | The sender number needs reconnecting in the dashboard | Does not retry |
| INVALID_RECIPIENT, RECIPIENT_NOT_REACHABLE or NOT_GROUP_MEMBER | The recipient is wrong, refused, or you cannot post to that group | Does not retry |
| HTTP 400, 401, 403 or 404 | Bad request body, bad key, missing scope, no active subscription for a live key, or unknown sender | Does not retry; fix the request or the setup |
Log the failures you do not retry and look at them. A sender the dashboard already shows as disconnected is refused with HTTP 400 before any message is recorded, and NOT_CONNECTED means the connection dropped during the send. Either way, every later notification fails too until someone reconnects the number. The full list of codes is in the error code reference.
Track delivery status
A message moves from pending to sent (WhatsApp accepted it), then delivered and read as receipts arrive, or ends at failed. read may never arrive, because recipients can turn read receipts off, and a message can jump from sent straight to read.
You can poll a message by its ID with the client you already have:
from tasks import chatmaid
message = chatmaid.get_message("msg_abc123def456")
print(message["status"], message["deliveredAt"], message["errorCode"])Polling is fine for a support tool or a one-off check. For anything automatic, let Chatmaid push status changes to you instead.
Receive replies and delivery updates with a webhook
Open Webhooks in the dashboard, enter an HTTPS URL that points at your app, and pick the events you want. For this tutorial, choose Message Sent (via API), Message Delivered, Message Read, Message Failed, Message Received and Phone Disconnected (the events message.sent, message.delivered, message.read, message.failed, message.received and phone.disconnected). The dashboard shows the webhook secret once: copy it into CHATMAID_WEBHOOK_SECRET in .env. During development, a tunnel such as ngrok or Cloudflare Tunnel gives your local port a public HTTPS address.
Every delivery carries an X-Chatmaid-Event header with the event name and an X-Chatmaid-Signature header shaped like t=1792419600,v1=<hex>. The v1 value is an HMAC-SHA256 of the timestamp, a dot and the raw request body, keyed with your secret. Verify it against the raw bytes, not against JSON you parsed and serialized again. Don't reject events because t is old: retries resend the original signature, so a retry minutes later carries the first attempt's timestamp. Save this as webhook.py:
import hashlib
import hmac
from flask import Blueprint, jsonify, request
import config
from tasks import handle_webhook_event
webhook_bp = Blueprint("chatmaid_webhook", __name__)
def verify_signature(raw_body: bytes, header: str, secret: str) -> bool:
# Header format: t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<raw body>">
if not secret or not header:
return False
try:
parts = dict(item.split("=", 1) for item in header.split(","))
signed = parts["t"].encode() + b"." + raw_body
except (KeyError, ValueError):
return False
expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
return hmac.compare_digest(parts.get("v1", "").encode(), expected.encode())
@webhook_bp.post("/webhooks/chatmaid")
def chatmaid_webhook():
raw = request.get_data()
signature = request.headers.get("X-Chatmaid-Signature", "")
if not verify_signature(raw, signature, config.CHATMAID_WEBHOOK_SECRET):
return jsonify(error="invalid signature"), 401
handle_webhook_event.delay(request.get_json(silent=True) or {})
return jsonify(received=True), 200The route only checks the signature and queues the event. Answer fast: Chatmaid treats an error status, or no answer within 30 seconds, as a failed delivery and tries again, up to 3 attempts in total, so the same event can reach you more than once. Add the handler to the end of tasks.py:
@celery.task
def handle_webhook_event(event: dict):
kind = event.get("event")
data = event.get("data") or {}
if kind in ("message.sent", "message.delivered", "message.read", "message.failed"):
# Update your own notification record here, keyed by data["messageId"].
log.info("%s %s is now %s", kind, data.get("messageId"), data.get("status"))
if kind == "message.failed":
log.warning("%s failed: %s", data.get("messageId"), data.get("errorCode"))
elif kind == "phone.disconnected":
log.error("Sender %s disconnected; reconnect it in the dashboard", data.get("phoneNumber"))
elif kind == "message.received" and not data.get("isGroup"):
sender = data.get("from")
text = (data.get("content") or "").strip().upper()
if sender and text == "STOP":
store.sadd(OPTED_OUT, sender)
chatmaid.send(
sender,
"You will not get any more notifications from us on WhatsApp.",
idempotency_key=make_key("stop-ack", data["messageId"]),
)Status events (message.sent, message.delivered, message.read, message.failed) carry the messageId from your send, the new status, and on failure an errorCode and errorMessage. A message.received event carries the inbound message: from is the person who wrote, to is your number, and content is the text or a media caption. A phone.disconnected event names the number in phoneNumber, so you hear about a dropped connection before your notifications start failing.
The handler turns a "STOP" reply into an opt-out that send_whatsapp checks before every send. Redis keeps this example short; in production, store the opt-out on the customer record in your database and check it there, so it survives restarts. The confirmation uses a key built from the inbound message ID, so a repeated webhook delivery cannot send the confirmation twice. For routing replies by keyword, storing them and handing conversations to a person, see how to receive and reply to WhatsApp messages via webhook.
Now register the blueprint. This is the finished app.py:
import re
from flask import Flask, jsonify, request
from tasks import make_key, send_whatsapp
from webhook import webhook_bp
E164 = re.compile(r"^\+[1-9]\d{1,14}$")
app = Flask(__name__)
app.register_blueprint(webhook_bp)
@app.post("/orders/<order_id>/shipped")
def order_shipped(order_id):
body = request.get_json(silent=True) or {}
phone, tracking = body.get("phone", ""), body.get("tracking", "")
if not E164.match(phone) or not tracking:
return jsonify(error="phone (E.164) and tracking are required"), 400
text = f"Good news: order {order_id} has shipped. Tracking number: {tracking}."
send_whatsapp.delay(phone, text, make_key("order-shipped", order_id))
return jsonify(queued=True), 202Restart the worker so it picks up the new task, then restart Flask.
Inbound messages only exist for live numbers. In the sandbox you can still test the webhook route: every sandbox send fires message.sent, and the Test Webhook button on the Webhooks page sends a signed sample event. To test the STOP branch without a tunnel or a live number, sign a sample reply yourself and post it to your local server. Save this as send_test_event.py and run it while the worker and Flask are running:
import hashlib
import hmac
import json
import time
import requests
import config
event = {
"event": "message.received",
"timestamp": "2026-10-22T14:20:00.000Z",
"data": {
"messageId": "inmsg_test123",
"from": "+15557654321",
"to": "+15551234567",
"content": "STOP",
"type": "text",
"isGroup": False,
"groupId": None,
"receivedAt": "2026-10-22T14:20:00.000Z",
},
}
body = json.dumps(event)
t = str(int(time.time()))
digest = hmac.new(
config.CHATMAID_WEBHOOK_SECRET.encode(), f"{t}.{body}".encode(), hashlib.sha256
).hexdigest()
response = requests.post(
"http://localhost:8000/webhooks/chatmaid",
data=body,
headers={"Content-Type": "application/json", "X-Chatmaid-Signature": f"t={t},v1={digest}"},
timeout=10,
)
print(response.status_code, response.text)A 200 with "received": true means the signature check passed and the event is in the queue. A 401 means the secret in .env does not match the one the event was signed with. Then run redis-cli SISMEMBER whatsapp:opted_out +15557654321: it returns 1 once the worker has processed the opt-out, and the sandbox key simulates the confirmation send.
Test in the sandbox, then go live
The sandbox is free, and everything here except real inbound replies runs in it. Sends are simulated, numbers connect without a QR code, and webhooks fire with the same payload shape as live traffic. When it all works:
- Subscribe to the live plan. As of October 2026 it costs $7.99 a month, flat, for one number; the pricing page has the current details.
- Flip the dashboard switch to Live, add your real WhatsApp number and scan the QR code with WhatsApp on that phone.
- Create a live key (it starts with
sk_live_) and put it in.envin place of the test key. SetCHATMAID_SENDERto the live number. The base URL stays the same; the key decides the environment, andmake_keyswitches to fresh live idempotency keys on its own. Restart the worker and Flask. - Point your webhook at your production URL and keep its secret out of your code.
Keep the sending honest. With normal use, a ban is very unlikely; WhatsApp restricts accounts that behave like spam, such as unsolicited bulk messages to people who do not have you saved. Send notifications only to people who asked for them, and honor STOP. For more patterns built on the same API, read the WhatsApp API quickstart for SaaS developers, a WhatsApp order tracking bot and how the API works without Meta Business verification.
Frequently asked questions
Do I need Meta Business verification or approved templates?
No. Chatmaid sends from your own WhatsApp number, which you link by scanning a QR code, so there is no Meta Business verification and no template review. You write each notification as plain text.
Is there a Python SDK?
Not as of October 2026. Chatmaid publishes an official JavaScript SDK (@chatmaid/sdk) and an MCP server. From Python, call the REST API with requests, as this tutorial does; the client class above covers sending and status lookups.
Can I send a notification to a WhatsApp group?
Yes. Pass the group's ID (it ends in @g.us) as to. You get group IDs from GET /v1/groups?fromPhoneId=%2B15551234567 (your sender, with the plus URL-encoded), or from the groupId of an inbound group message. The sender number must be a member of the group and allowed to post in it. The Flask routes above accept phone numbers only, so widen their validation if you want groups.
Does this work with Django or FastAPI?
Yes. chatmaid_client.py and tasks.py do not import Flask; only the routes in app.py and webhook.py change. Read the raw request body for signature checks (request.body in Django, await request.body() in FastAPI).
How much does it cost?
As of October 2026, the sandbox is free and the live plan is $7.99 a month, flat, for one number. See the Chatmaid Developers page for what each includes.
How do I avoid sending the same notification twice?
Give every send an idempotencyKey built from your own IDs, such as an order number plus the event name, as make_key does. A repeated request with the same key returns the original message instead of sending again.


