Skip to content
Meta Business PartnerDeveloper how-to

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.

requests (or httpx); Flask or FastAPI
Libraries
3.10 or later
Python
POST https://api.infiq.in/v1/messages
Endpoint
X-INFIQ-API-KEY from an environment variable
Key
429 (after X-RateLimit-Reset) and 5xx
Retry on
request.get_data() / await request.body()
Webhook body

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 flask
export INFIQ_API_KEY=isk_test_… # sandbox key; isk_live_… sends for real
export 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 os
import time
import uuid
import requests
API = "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 send
to = "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, request
from verify import verify_infiq_signature
app = 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).

Get your InfiQ API key

Frequently asked questions

Is there an official WhatsApp API library for Python?+
Meta doesn't maintain one: its only official Cloud API SDK was for Node.js, and it was archived in 2023. Plain HTTP with requests is the simplest reliable option, and with InfiQ there's no Meta token to manage, only your API key.
Can I send WhatsApp messages from Python for free?+
Not through the official API. Meta charges per delivered message by category (₹0.19 for a utility template in India), on top of your InfiQ plan. Free scripts that automate WhatsApp Web aren't an official channel, and the number risks a ban.
How do I send a PDF on WhatsApp with Python?+
Send a document message with a public HTTPS link and a filename, as in the example. Inside the 24-hour window it can be free-form; outside it, use a template with a document header.
Should I use async Python for bulk sends?+
It helps at volume. httpx.AsyncClient with a small concurrency limit works well, as long as each recipient keeps its own Idempotency-Key and you back off on 429.