To use the WhatsApp API in Python, send a POST request to Meta's Cloud API with the requests library. The address is https://graph.facebook.com/v27.0/<PHONE_NUMBER_ID>/messages, with a system user token in the header. Start a chat with an approved template. Free text only works within 24 hours of the customer's last message.
Every request body below follows the syntax on Meta's own pages, which we read on 13 November 2026. Graph API v27.0 came out on 4 November 2026, per Meta's Graph API changelog. Many older tutorials still call v18.0, which Meta lists as available only until 26 January 2026.
See your AI answer your customers
Three ways to send WhatsApp messages from Python#
| Path | You build | Best for |
|---|---|---|
| Meta Cloud API, direct | Sending, the webhook, storage and any inbox | Teams that want full control |
| A messaging provider's API | Your app logic on top of their API | Teams already using that provider |
| Instant Reply REST API | Only your own logic. The inbox and AI replies exist already. | Teams that want a team inbox too |
This guide uses the first path. Meta's Cloud API is plain HTTPS and JSON, so requests is all you need to send.
What you need before the first call#
These steps are from Meta's Cloud API get started guide.
- Create a Meta app with the WhatsApp use case
In the App Dashboard, pick "Connect with customers through WhatsApp" and choose a business portfolio.
- Open API Setup and note two IDs
Save the test phone number ID and the Messaging account ID. Every send uses the phone number ID.
- Add a To number and send the test message
Generate a temporary token and send Meta's sample template to your own phone. Meta says this token "expires quickly".
- Make a system user token
In Business Settings, open System users and add one. Give it your app and your WhatsApp account. Then generate a token with business_management, whatsapp_business_messaging and whatsapp_business_management.
- Store the token as a secret
Put it in an environment variable. Never commit it to git.
Meta's access token guide says system user tokens are long-lived and meant for automated services.
Send a WhatsApp message with Python#
This helper sends any message type and returns the message ID. Meta calls that ID a wamid. Set WA_PHONE_NUMBER_ID and WA_TOKEN first.
# send.py
import os
import requests
GRAPH = "https://graph.facebook.com/v27.0"
PHONE_NUMBER_ID = os.environ["WA_PHONE_NUMBER_ID"]
TOKEN = os.environ["WA_TOKEN"] # system user access token
def send(message: dict) -> str:
"""Send one message and return its WhatsApp message ID (wamid)."""
body = {"messaging_product": "whatsapp", "recipient_type": "individual", **message}
r = requests.post(
f"{GRAPH}/{PHONE_NUMBER_ID}/messages",
headers={"Authorization": f"Bearer {TOKEN}"},
json=body,
timeout=10,
)
data = r.json()
if r.status_code != 200:
error = data.get("error", {})
raise RuntimeError(f"WhatsApp error {error.get('code')}: {error.get('message')}")
return data["messages"][0]["id"]Start a chat with a template#
Outside the 24-hour window you can only send a template, and it must be approved. Meta reviews each template when you create or edit it, per its template overview. Use your template's name and language code.
from send import send
# Starts a chat. Works at any time, but only with an APPROVED template.
send({
"to": "+16505551234",
"type": "template",
"template": {"name": "order_update", "language": {"code": "en_US"}},
})Reply with free text inside the 24-hour window#
A customer's message opens a 24-hour window, and each new message resets it. Inside it you can send text, images and buttons, per Meta's send messages page.
# Free text. Works only while the customer's 24-hour window is open.
send({
"to": "+16505551234",
"type": "text",
"text": {"body": "Thanks! Your order ships today."},
})Send reply buttons#
You can add up to 3 buttons. Each label can be 20 characters at most, and the body text up to 1,024, per Meta's reply buttons page. A tap comes back to your webhook as a button_reply with the button's ID.
send({
"to": "+16505551234",
"type": "interactive",
"interactive": {
"type": "button",
"body": {"text": "Your table is booked for 7 pm. Need to change it?"},
"action": {
"buttons": [
{"type": "reply", "reply": {"id": "keep", "title": "Keep it"}},
{"type": "reply", "reply": {"id": "change", "title": "Change time"}},
]
},
},
})Send an image#
JPEG, PNG and static WebP images up to 5 MB work, per Meta's image messages page. Meta recommends an uploaded media ID for better performance, but a public link is the quickest start.
send({
"to": "+16505551234",
"type": "image",
"image": {"link": "https://example.com/menu.png", "caption": "Today's menu"},
})Receive WhatsApp messages with a Python webhook#
Meta sends each new message to your server as a POST request. Meta's webhook endpoint page sets three rules:
- Verify the endpoint. Meta sends a GET request with
hub.mode,hub.verify_tokenandhub.challenge. If the token matches yours, answer 200 with the challenge. - Check the signature. Each POST carries an
X-Hub-Signature-256header. Hash the raw body with your app secret using HMAC-SHA256 and compare. - Expect repeats. Failed deliveries are retried for up to 7 days, so your server should skip messages it has already seen.
# webhook.py (pip install flask requests)
import hashlib
import hmac
import os
from flask import Flask, abort, request
from send import send
app = Flask(__name__)
VERIFY_TOKEN = os.environ["WA_VERIFY_TOKEN"]
APP_SECRET = os.environ["WA_APP_SECRET"].encode()
seen_ids = set() # use a database table in production
@app.get("/webhook")
def verify():
# Meta calls this when you save the Callback URL and Verify token.
if (request.args.get("hub.mode") == "subscribe"
and request.args.get("hub.verify_token") == VERIFY_TOKEN):
return request.args.get("hub.challenge", ""), 200
abort(403)
@app.post("/webhook")
def receive():
raw = request.get_data() # the exact bytes Meta signed
expected = "sha256=" + hmac.new(APP_SECRET, raw, hashlib.sha256).hexdigest()
given = request.headers.get("X-Hub-Signature-256", "")
if not hmac.compare_digest(expected.encode(), given.encode()):
abort(401)
payload = request.get_json()
for entry in payload.get("entry", []):
for change in entry.get("changes", []):
for msg in change.get("value", {}).get("messages", []):
if msg["id"] in seen_ids: # Meta retries, so skip repeats
continue
seen_ids.add(msg["id"])
handle(msg)
return "", 200
def handle(msg: dict) -> None:
if msg.get("type") != "text":
return
# "from" is missing when the user hides their number behind a username.
who = {"to": msg["from"]} if "from" in msg else {"recipient": msg["from_user_id"]}
send({**who, "type": "text", "text": {"body": "Got it: " + msg["text"]["body"]}})Run it with flask --app webhook run behind HTTPS. Meta needs a valid TLS certificate, and self-signed ones are not accepted. In the App Dashboard, open Use cases, then Customize, then Configuration. Older apps without the WhatsApp use case have it under WhatsApp, then Configuration. Paste your Callback URL and Verify token, then subscribe to the messages field, per Meta's webhooks overview.
Tip: Keep the handler fast. For real traffic, save the message, return 200, and reply from a background worker. In FastAPI, read the raw body with await request.body() before you parse it, so the signature check uses the exact bytes.
The same POST also carries status updates (sent, delivered, read) under statuses instead of messages. A user who chose a username may arrive without a from number. Meta's text message webhook reference adds from_user_id instead, and you reply by setting recipient to it. Our guide to WhatsApp usernames and BSUIDs explains the change.
WhatsApp API error codes you will hit first#
Errors come back in the API response, in the webhook, or both, per Meta's error codes page. Meta says to build your handling on the code value, not the title.
| Code | What it means | Fix |
|---|---|---|
| 131047 | More than 24 hours since the customer last wrote | Send an approved template |
| 132001 | Template missing in that language, or not approved | Check the name, language code and status |
| 131026 | Message could not be delivered | Check the number is on WhatsApp |
| 130429 | Throughput limit reached | Retry later or send more slowly |
| 131056 | Too many messages to one person too fast | Wait, then retry |
| 190 | Access token expired | Make a new token |
What Meta charges per message#
Meta charges per delivered message, by category and country, per its pricing page. Messages from customers to you are free.
- Service messages. Each business number gets 1,000 free service messages a month. Since 1 October 2026, Meta charges from the 1,001st.
- Utility templates inside the window. These are charged since 1 October 2026.
- Click to WhatsApp ads. If a customer writes from one of these ads and you answer in time, a free window opens for up to 7 days.
To estimate a month of your own traffic, use our WhatsApp API pricing calculator. Our guide to Meta's WhatsApp pricing covers each category.
When to use Instant Reply's API instead#
The code above sends and receives messages. A real support line also needs a shared inbox, a way for teammates to take over, and replies that know your prices. Instant Reply is a WhatsApp, Instagram and Messenger inbox with AI replies that has its own REST API.
- The calls are plain HTTPS too.
GET https://api.instantreply.co/v1/conversationslists chats, andPOST /v1/conversations/{id}/messagessends a reply with anIdempotency-Keyheader. - Its webhooks are signed with an
X-InstantReply-Signatureheader. - An MCP server lets Claude, Cursor and other agents use the inbox:
npx -y @instantreply.co/mcp. - The same 24-hour rule applies. Outside the window, you send an approved template.
The developer docs list every endpoint, and developer pricing lists the API limits by plan.
What we could not confirm#
- The language code of Meta's sample hello_world template. The get started page names the template but does not show its code.
- How long the temporary token lasts. Meta only says it "expires quickly".
- An official Meta Python package. We found none in Meta's docs, so this guide uses plain HTTP.


