WhatsApp API with Python: send messages and receive webhooks
You don't need a special library to use the WhatsApp API from Python. It is JSON over HTTPS, so requests (or httpx) and two small helpers cover sending, retries and webhooks. This guide builds those helpers against InfiQ's API, which takes the same message bodies as Meta's WhatsApp Cloud API.
In short
Install requests, keep your InfiQ API key in an environment variable, and wrap one POST to https://api.infiq.in/v1/messages in a send() function that adds an Idempotency-Key and retries on 429 and server errors. Use it for text, templates and documents. Receive replies and delivery updates with a Flask or FastAPI route that verifies X-InfiQ-Signature against the raw body.Set up
You need Python 3.10 or later, requests for sending and Flask (or FastAPI) for the webhook. Put the API key from Settings → Developers in an environment variable:
pip install requests flaskexport INFIQ_API_KEY=isk_test_… # sandbox key; isk_live_… sends for realexport INFIQ_WEBHOOK_KEY=… # your webhook endpoint's signing key
A send() helper with safe retries
One function handles what every send needs: the key header, an idempotency key so that a retry can never send twice, a wait on 429 until X-RateLimit-Reset, and backoff on server errors. Other 4xx errors are raised, because sending the same body again won't fix them.
import osimport timeimport uuidimport requestsAPI = "https://api.infiq.in/v1/messages"session = requests.Session()session.headers["X-INFIQ-API-KEY"] = os.environ["INFIQ_API_KEY"]def send(body: dict, idempotency_key: str | None = None, attempts: int = 5) -> str:"""Send one message and return its wamid. Retries reuse the same key."""key = idempotency_key or str(uuid.uuid4())for attempt in range(1, attempts + 1):res = session.post(API, json=body, timeout=30, headers={"Idempotency-Key": key})data = res.json()if res.ok:return data["messages"][0]["id"]if res.status_code == 429:reset = int(res.headers.get("X-RateLimit-Reset", time.time() + 1))time.sleep(max(reset - time.time(), 1))elif res.status_code >= 500:time.sleep(2 ** attempt * 0.5)else:err = data.get("error", {})raise RuntimeError(f"{err.get('code')}: {err.get('message')} ({data.get('InfiQ_traceid')})")raise RuntimeError(f"gave up after {attempts} attempts")
Send a text, a template and a PDF
With the helper in place, each message type is just its body, in the format Meta's Cloud API defines. The text needs an open 24-hour window; the template works at any time; the document needs a public HTTPS link and a filename.
from infiq import sendto = "919820000001"send({"messaging_product": "whatsapp","to": to,"type": "text","text": {"body": "Your order INF-3091 has shipped."},})send({"messaging_product": "whatsapp","to": to,"type": "template","template": {"name": "order_confirmation","language": {"code": "en"},"components": [{"type": "body","parameters": [{"type": "text", "text": "Ananya"},{"type": "text", "text": "INF-3091"},],}],},}, idempotency_key="INF-3091-confirmation")send({"messaging_product": "whatsapp","to": to,"type": "document","document": {"link": "https://www.infiq.in/media/INF-3091.pdf","filename": "Invoice-INF-3091.pdf","caption": "Invoice for your order",},})
Receive webhooks in Flask or FastAPI
Read the raw bytes before anything parses them, verify the signature, then act on the event. Both routes use the verify_infiq_signature() function shown in the third tab.
from flask import Flask, abort, requestfrom verify import verify_infiq_signatureapp = Flask(__name__)@app.post("/webhooks/infiq")def infiq_webhook():raw = request.get_data()if not verify_infiq_signature(request.headers.get("X-InfiQ-Signature", ""), raw):abort(401)event = request.get_json()if event["type"] == "message.received":msg = event["data"]["message"]print(msg["from"], msg["content"].get("text"))return "", 200
Avoid unofficial WhatsApp libraries
Searches for Python WhatsApp libraries turn up tools such as pywhatkit and WhatsApp Web automation that drive the consumer app through a browser. They aren't the WhatsApp Business API: WhatsApp doesn't allow automated or bulk business messaging through the consumer app, and numbers used that way get banned. For business messaging use the official API, here through InfiQ, which needs nothing beyond requests.
* Per-message rates for India, ex-GST: marketing, utility and authentication effective 1 July 2026; service messages ₹0.145 since 1 October 2026 after the first 1,000 a month on each WhatsApp number, which are free (all were ₹0 until 30 September 2026). Volume commitments earn discounts — final rate is confirmed on your account; applicable GST extra. Rates for other countries differ (see the international rate table on /pricing).