WhatsApp API in Python: send a WhatsApp message from Python, a complete example
Sending a WhatsApp message with Python through the official API: one function with the requests library, sending an approved template and reading its status, a script that sends payment reminders from a CSV file, and the common mistakes.
On this page 7
The short answer
To send a WhatsApp message from Python use the requests library and one call to POST https://app.arabybot.com/api/v1/messages/template with your key in the Authorization header, the body holding the recipient's number with its country code, the approved template's name and its variables. This is the official route through the WhatsApp Business Platform; libraries that drive WhatsApp Web are unofficial and put the number at risk of a ban.
Also asked as: «whatsapp api python» · «ارسال رسالة واتساب بايثون» · «سكربت بايثون يرسل واتساب» · «ارسال واتساب من ملف اكسل بايثون» · «python send whatsapp message» · «whatsapp business api python» · «send whatsapp messages from csv python»
The official route, not automating WhatsApp Web
The first thing someone searching for sending WhatsApp from Python finds is libraries that open WhatsApp Web in a browser and type the message as if human. They work in a trial, then cost you the number: WhatsApp restricts accounts whose activity looks automated or bulk, then bans them. The code here sends through the official WhatsApp Business Platform from your number connected to ArabyBot, with templates approved by Meta.
How long a WhatsApp ban lasts, and its kinds · Bulk sender software: which will not get your number banned?
What you need
- A WhatsApp number connected to ArabyBot with at least one approved template.
- A plan that includes «Developer tools»: WhatsApp Pro, WhatsApp Premium, Complete Plan or Ultimate Plan.
- A key from the «Developer tools» page; it starts with
abk_and is shown once. Put it in theARABYBOT_API_KEYenvironment variable.
One function with the requests library
# pip install requests
import os
import requests
BASE = "https://app.arabybot.com/api/v1"
HEADERS = {"Authorization": "Bearer " + os.environ["ARABYBOT_API_KEY"]}
def arabybot(method, path, body=None):
"""One helper for every call. Returns the API's JSON answer as a dict."""
try:
res = requests.request(method, f"{BASE}/{path}", headers=HEADERS, json=body, timeout=20)
return res.json()
except (requests.RequestException, ValueError):
return {"success": False, "error_code": "NETWORK"}
me = arabybot("GET", "me") # does the key work, and which numbers does it send from?
templates = arabybot("GET", "templates") # each template comes with a ready body in "example" The json= argument turns the dict into JSON and sets the content header, so you do not need json.dumps. The timeout is essential: without it the script waits forever if the connection drops.
Sending a template and reading its status
sent = arabybot("POST", "messages/template", {
"to": "201012345678", # with the country code
"template": "order_shipped",
"language": "ar",
"variables": ["Ahmed", "1042"], # the template's {{1}}, {{2}} in order
"reference": "order-1042-shipped", # the same reference is never sent twice
})
if sent.get("success"):
message_id = sent["id"] # "accepted", or "queued": it goes out by itself
elif sent.get("error_code") in ("TRY_AGAIN", "NETWORK"):
retry_later(order_id) # same request, same reference
elif sent.get("error_code") == "UNCERTAIN":
check_later(sent.get("id")) # ask GET messages/{id} before sending again
else:
print(sent.get("error_code"), sent.get("message_en"))
status = arabybot("GET", "messages/512") # queued · accepted · sent · delivered · read · failed A successful answer carries status with one of two values: accepted, meaning WhatsApp took it, or queued, meaning it waits its turn and goes out by itself. Either way keep id to ask about delivery later.
Every field, refusal code and limit, in the send API reference
A practical example: payment reminders from a CSV file
What Python is asked for most is a script that reads a list and sends each row its message. The reference built from the invoice number makes running the script twice safe: whoever got the message does not get it again.
import csv
import time
with open("customers.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f): # columns: phone, name, invoice
sent = arabybot("POST", "messages/template", {
"to": row["phone"],
"template": "payment_reminder",
"language": "ar",
"variables": [row["name"], row["invoice"]],
"reference": "reminder-" + row["invoice"],
})
if not sent.get("success"):
print(row["phone"], sent.get("error_code"), sent.get("message_en"))
time.sleep(0.2) # five a second is plenty; the queue paces the rest The API takes 600 requests a minute per key, and whatever exceeds your number's pace at WhatsApp waits in the queue and is not lost. Someone who turned off marketing messages in WhatsApp comes back as OPTED_OUT when the template is a marketing one, so remove them from your list.
Common Python mistakes
| The mistake | What happens | The fix |
|---|---|---|
| The key inside the script | It leaks the first time the file is shared | os.environ |
data= instead of json= | Lists inside variables do not arrive as you wrote them | json=body |
| Reading the file in a non-UTF-8 encoding | Arabic names arrive garbled | encoding="utf-8" |
| Numbers with a leading zero and no country code | BAD_PHONE | Store them in international form |
| Retrying every refusal | Useless requests | Retry TRY_AGAIN only |
The same walkthrough in PHP · And from Node.js · The OTP API
Frequently asked questions
Should I use libraries that drive WhatsApp Web from Python?
We do not recommend them for a business number. These libraries open WhatsApp Web and type into it automatically, and WhatsApp treats automated and bulk sending from the app as a violation that ends in a restricted or banned account. The official route is the WhatsApp Business Platform with approved templates, which is what the code on this page does.
Which Python version do I need?
Python 3.6 or newer, and the requests library. The code uses nothing else.
How do I send from Django or Flask?
With the same function, but from a background task rather than the view. If you send from the view, the user waits for the API's answer, and a page reload repeats the request. A task retries by itself on TRY_AGAIN, and the reference field makes retrying it safe.
Can I send an image or a PDF with the message?
Yes, if the approved template has an image or document header: put the file's link in the header field. The file must be at a public link WhatsApp can download.
Read next
Try the agent before you pay anything
The agent that will answer your customers is the one answering you now: ask it from the chat button here or on WhatsApp. Your account is free with no credit card, and the free trial on your own number or page is activated after you contact our team on customer-service WhatsApp.