WhatsApp· 5 min read

Send a WhatsApp message with Python and the Cloud API


Send a WhatsApp message from Python with one requests.post to https://graph.facebook.com/v26.0/<PHONE_NUMBER_ID>/messages, a Bearer token in the Authorization header and a JSON body. Inside a customer service window the body can be plain text. Outside it, Meta accepts only an approved template. A successful call returns an ID in messages[0].id. That ID means Meta accepted the message. Delivery is reported later, by webhook.

What you need before the first call

You need three values: an access token, the business phone number ID and a Graph API version. The test number in the App Dashboard gives you a phone number ID. Meta’s get-started page tells you to “retain both your test phone number ID and Messaging account ID for later use” (Meta get started, accessed 2026-11-03). The walkthrough is in the Cloud API test number guide.

The temporary token from that page “expires quickly”, and Meta gives no duration. For anything you leave running, use a system user token, covered in Cloud API access tokens.

For the version, Meta’s send samples use v26.0 (Meta text messages, accessed 2026-11-03). The Graph API changelog lists v26.0 as released on 2026-07-29 with no end date set yet (Graph API changelog, accessed 2026-11-03). The get-started page still shows v23.0, which stays available until 2027-10-08. Keep the version in an environment variable so an upgrade is a config change.

pip install requests
export WHATSAPP_TOKEN="ACCESS_TOKEN"
export PHONE_NUMBER_ID="PHONE_NUMBER_ID"
export GRAPH_VERSION="v26.0"

The script

This file sends a text or a template, retries the two rate-limit codes and prints the message ID. It needs nothing beyond requests.

# send_whatsapp.py
import os
import sys
import time

import requests

TOKEN = os.environ["WHATSAPP_TOKEN"]
PHONE_NUMBER_ID = os.environ["PHONE_NUMBER_ID"]
GRAPH_VERSION = os.environ.get("GRAPH_VERSION", "v26.0")
URL = f"https://graph.facebook.com/{GRAPH_VERSION}/{PHONE_NUMBER_ID}/messages"

RETRY_CODES = {130429, 131056}  # throughput and pair rate: wait, then retry


class WhatsAppError(Exception):
    def __init__(self, status, error):
        self.status = status
        self.error = error or {}
        self.code = self.error.get("code")
        details = self.error.get("error_data", {}).get("details", "")
        super().__init__(
            f"HTTP {status}, code {self.code}: {self.error.get('message')} {details}"
        )


def post_message(payload):
    r = requests.post(
        URL,
        json=payload,
        headers={"Authorization": f"Bearer {TOKEN}"},
        timeout=10,
    )
    try:
        data = r.json()
    except requests.exceptions.JSONDecodeError:
        r.raise_for_status()  # a non-JSON error page raises HTTPError here
        raise
    if not r.ok or "error" in data:
        raise WhatsAppError(r.status_code, data.get("error"))
    return data


def send(payload, attempts=4):
    for attempt in range(attempts):
        try:
            return post_message(payload)
        except WhatsAppError as e:
            if e.code not in RETRY_CODES or attempt == attempts - 1:
                raise
            time.sleep(2 ** attempt)


def text_payload(to, body):
    return {
        "messaging_product": "whatsapp",
        "recipient_type": "individual",
        "to": to,
        "type": "text",
        "text": {"preview_url": False, "body": body},
    }


def template_payload(to, name, language, params):
    template = {"name": name, "language": {"code": language}}
    if params:  # name=value becomes a named parameter, a bare value a positional one
        parameters = []
        for p in params:
            key, sep, value = p.partition("=")
            if sep:
                parameters.append({"type": "text", "parameter_name": key, "text": value})
            else:
                parameters.append({"type": "text", "text": p})
        template["components"] = [{"type": "body", "parameters": parameters}]
    return {
        "messaging_product": "whatsapp",
        "recipient_type": "individual",
        "to": to,
        "type": "template",
        "template": template,
    }


if __name__ == "__main__":
    if len(sys.argv) < 4 or (sys.argv[1] == "template" and len(sys.argv) < 5):
        sys.exit("usage: send_whatsapp.py text TO BODY | template TO NAME LANGUAGE [PARAMS...]")
    kind, to = sys.argv[1], sys.argv[2]
    if kind == "text":
        payload = text_payload(to, sys.argv[3])
    else:
        payload = template_payload(to, sys.argv[3], sys.argv[4], sys.argv[5:])
    try:
        data = send(payload)
    except WhatsAppError as e:
        print(e, file=sys.stderr)
        if e.code == 131047:
            print("Window closed: send an approved template instead.", file=sys.stderr)
        elif e.code == 190:
            print("Token expired: create a new access token.", file=sys.stderr)
        sys.exit(1)
    message = data["messages"][0]
    print("accepted:", message["id"], message.get("message_status", ""))
    print("wa_id:", data["contacts"][0]["wa_id"])

json=payload encodes the dict and sets the header for you. The Requests docs say passing a string through data=json.dumps(...) “will NOT add the Content-Type header” (Requests quickstart).

The 10-second timeout is this script’s choice. Meta documents no client timeout, and Requests warns that “if no timeout is specified explicitly, requests do not time out.” Requests also notes that an Authorization header set through headers= “will be overridden if credentials are specified in .netrc”. If authentication fails on one machine only, check that file.

Send a text message inside the window

The text payload follows Meta’s text message reference. body takes up to 4096 characters. With preview_url set to true, the WhatsApp client tries to render a preview of the first URL, which must start with http:// or https://.

python send_whatsapp.py text +16505551234 "Your order shipped"

Free-form text only goes through inside the 24-hour window that opens when the user writes to you. Meta’s get-started page puts it this way: “This 24-hour window allows you to send non-template messages to users on WhatsApp.” Format the to number in E.164 with country code; the E.164 normalization guide covers the edge cases.

A successful call prints the ID and the wa_id. Meta’s documented response looks like this:

{
  "messaging_product": "whatsapp",
  "contacts": [
    {
      "input": "+16505551234",
      "wa_id": "16505551234"
    }
  ],
  "messages": [
    {
      "id": "wamid.HBgLMTY0NjcwNDM1OTUVAgARGBI1RjQyNUE3NEYxMzAzMzQ5MkEA"
    }
  ]
}

Send a template outside the window

Outside the window you need a template. Meta’s template overview says “Template messages are the only type of message that can be sent to WhatsApp users outside of a customer service window” (Meta template fundamentals, accessed 2026-11-03). The template must be APPROVED, and you send it with the language code it was created in.

Meta’s example uses a template called order_confirmation with two named body variables. Replace the name and parameters with one of your own approved templates:

python send_whatsapp.py template +16505551234 order_confirmation en_US first_name=Jessica order_number=SKBUP2-4CPIG9

The script builds the same body Meta shows, with parameter_name on each entry. Pass bare values instead (Jessica SKBUP2-4CPIG9) for a template with positional {{1}} variables, and the script leaves parameter_name out. A positional value that contains = is read as named, so change the parser if your values can contain one. Template variables: positional and named parameters covers header and button parameters.

Read the response

Store messages[0].id. Every status webhook for that message carries the same ID, which is how you match sent, delivered, read and failed back to your record (status webhooks).

Meta’s messages reference also lists a message_status field on messages[] (Meta Messages API reference, accessed 2026-11-03). The text message sample doesn’t show it, so the script reads it with .get().

message_status Meta’s description
accepted “The message has been accepted by WhatsApp and is being processed”
held_for_quality_assessment “The message is being held for quality assessment before delivery”
paused “The message delivery has been paused”

contacts[0].input echoes the number you sent and wa_id is the WhatsApp ID. Meta notes that “a WhatsApp user’s ID and phone number may not always match” (Meta text message webhook, accessed 2026-11-03). Key your contacts on what you need, and store both.

If you send several messages in a row, Meta says “the order in which messages are delivered is not guaranteed” (Meta send messages, accessed 2026-11-03). For a sequence, wait for the delivered webhook of one message before you send the next. Out-of-order webhooks shows a pattern.

Handle error responses

Errors come back as an error object. This is Meta’s example for the throughput limit (Meta error codes, accessed 2026-11-03):

{
  "error": {
    "message": "(#130429) Rate limit hit",
    "type": "OAuthException",
    "code": 130429,
    "error_data": {
      "messaging_product": "whatsapp",
      "details": "Cloud API message throughput has been reached."
    },
    "error_subcode": 2494055,
    "fbtrace_id": "Az8or2yhqkZfEZ-_4Qn_Bam"
  }
}

Branch on error.code. Meta’s guidance reads “Build your app’s error handling around error codes instead of subcodes or HTTP response status codes.” error_subcode is deprecated and no longer returned from v16.0 on. Log fbtrace_id, because Meta’s Direct Support asks for it.

Code Meta’s details What the script or you do
131047 “More than 24 hours have passed since the recipient last replied to the sender number.” Send a template (error 131047)
190 “Your access token has expired.” Create a new token
130429 “Cloud API message throughput has been reached.” Wait and retry
131056 “Too many messages sent from the sender phone number to the same recipient phone number in a short period of time.” Wait and retry that recipient
132000 “The number of variable parameter values included in the request did not match…” Fix the parameters
132001 “The template does not exist in the specified language or the template has not been approved.” Check name, language and status
131026 “Unable to deliver message.” Don’t retry (error 131026)

The 1, 2 and 4 second waits in send() are short placeholders. Meta’s pacing for 131056 is in Cloud API rate limits.

Not every error arrives in the HTTP response. Meta says errors are returned “either synchronously as a Graph API response,” or “asynchronously via Webhook, or sometimes through both methods”, and recommends watching both. A 131047 that only shows up in a failed status webhook never reaches the script’s except branch. Handle the same codes in your webhook consumer, and look up the rest in the Cloud API error codes reference.

Z-API Omni team