Conecxt
Create account

Resources Insight

Send a WhatsApp message with Python: your first hour on Meta's Cloud API, with working code

A developer's first hour with the WhatsApp Business API in Python, from Meta's live docs: the test number, the token that doesn't expire by lunchtime, a 20-line send script, a webhook that verifies and prints, and the errors you'll meet before tea.

Conecxt team 11 min read

Share WhatsApp LinkedIn

The short version

  • Meta's Cloud API takes a POST to /<PHONE_NUMBER_ID>/messages with a bearer token and a JSON body. Python's requests library is enough; no WhatsApp-specific package is needed.
  • The App Dashboard's temporary token expires within hours. Use a system user token with business_management, whatsapp_business_management and whatsapp_business_messaging.
  • Your first message must be a template such as hello_world. Free text works only after the recipient replies, inside the 24-hour window, or it fails with error 131047.
  • The webhook must answer Meta's GET check with the hub.challenge value and should verify the X-Hub-Signature-256 header on every POST.
  • The test number sends templates without a payment method, but only to recipient numbers you have added. Others fail with 131030.

Rohan Kamble is a freelance developer in Nagpur, and his newest client runs two optician shops, in Sitabuldi and Dharampeth, with four people at the counters. The client wants a WhatsApp message to go out when a pair of spectacles is ready for pickup, triggered by the billing software Rohan already maintains. He works alone, writes Python, and wants to send a WhatsApp message from Python before he quotes a price. (Rohan and his client are invented for this guide.)

This is his first hour with the WhatsApp Business API from Python, built from Meta’s live documentation as read on 25 October 2026. If you want the request format in curl and the rules on templates and bulk sends, our guide to the send-message API covers those; this one is about getting Python to send, receive and recover from its first errors.

What do you need before the first line of Python?

A Meta developer account and a Meta app with the WhatsApp use case, which gives you the values the script needs. Meta’s Get Started page (Updated 16 Jun 2026) walks through creating the app with “Connect with customers through WhatsApp” and then opening API Setup.

On that panel you’ll find a test business phone number Meta created for you, its phone number ID, the Messaging account ID, and a button that generates a temporary token. Add your own WhatsApp number as a recipient there. Meta’s About the platform page says test numbers “have relaxed messaging limits and don’t require a payment method on file in order to send template messages”, so this hour costs nothing.

Keep these three values out of the code:

export WA_PHONE_NUMBER_ID="<PHONE_NUMBER_ID_FROM_API_SETUP>"
export WA_TOKEN="<SYSTEM_USER_TOKEN>"
export WA_TO="<YOUR_WHATSAPP_NUMBER_WITH_PLUS_AND_COUNTRY_CODE>"

The phone number ID is the long ID API Setup shows for the test number. It goes in the URL; the phone number itself never does.

Which access token should the script use?

A system user token. The token API Setup gives you works for a quick test and then dies: Meta’s access tokens page (Updated 19 Sep 2026) says user tokens “expire quickly, so you have to keep generating a new one every few hours”, and an expired one returns error 190, “Your access token has expired.”

To make a lasting one, go to Business settings, then System users, add a system user, and assign it your app with the Manage app permission. Then click Generate token, pick an expiry preference, and grant these three permissions:

  • business_management
  • whatsapp_business_management
  • whatsapp_business_messaging

Meta says to treat the token as an opaque string and not to “parse, decode, or make assumptions about the format”. Put it in an environment variable or a secrets store, and never in a log line. Rohan’s client will outlive his laptop.

A 20-line script that sends hello_world

New test setups come with a template called hello_world, the one the dashboard’s own test send uses. Meta’s overview page shows a Python requests example that sends it with the language code en_US, and this WhatsApp Cloud API Python example is the same call as a reusable function:

import os
import requests

GRAPH = "https://graph.facebook.com/v26.0"
PHONE_NUMBER_ID = os.environ["WA_PHONE_NUMBER_ID"]
TOKEN = os.environ["WA_TOKEN"]
TO = os.environ["WA_TO"]

def send(message):
    r = requests.post(
        f"{GRAPH}/{PHONE_NUMBER_ID}/messages",
        headers={"Authorization": f"Bearer {TOKEN}"},
        json={"messaging_product": "whatsapp", "to": TO, **message},
        timeout=30,
    )
    data = r.json()
    if "error" in data:
        e = data["error"]
        raise RuntimeError(f"{e.get('code')}: {e.get('message')}")
    return data["messages"][0]["id"]

print(send({"type": "template",
            "template": {"name": "hello_world", "language": {"code": "en_US"}}}))

Run it and your phone should show the template within seconds. The script prints a message ID starting wamid.. Meta’s send-messages page is explicit about what that means: the response “only indicates that the API successfully accepted your request”, and it “does not indicate successful delivery of your message”. Delivery arrives later, on the webhook.

Two details from the same page. Write the recipient with the plus sign and country code, because without the plus “your business phone number’s country calling code is prepended”. And check the version: the send-messages and text-messages pages show v26.0, while Get Started still shows v23.0. Keep it in one constant, as above, so changing it is one line. The error check reads the error code, which matches Meta’s advice to “Build your app’s error handling around error codes instead of subcodes or HTTP response status codes”.

Now a free-text reply, inside the window

Reply to hello_world from your phone with anything at all. That opens the 24-hour customer service window, and inside it you can send ordinary text:

print(send({"type": "text",
            "text": {"body": "Your spectacles are ready for pickup at the Sitabuldi branch."}}))

Send that before replying and it fails with 131047, which Meta words as “More than 24 hours have passed since the recipient last replied to the sender number.” For Rohan’s client this is the rule that shapes everything: a “ready for pickup” note to a customer who hasn’t written in a day has to be a template, and Meta will classify it. A pickup notice about the customer’s own order fits utility, at ₹0.1150 per delivered message to an Indian number before GST on Meta’s rate card effective 1 October 2026. At an example 1,200 pickups a month across both shops, that’s 1,200 × ₹0.1150 = ₹138.00.

A minimal Flask webhook that verifies and prints

The webhook has two jobs: answer Meta’s verification GET, and accept event POSTs. Meta’s webhook endpoint page (Updated 17 Jun 2026) says the GET carries hub.mode, hub.challenge and hub.verify_token, and that a valid request gets “HTTP status 200 and the hub.challenge value”. Every POST carries an X-Hub-Signature-256 header, an HMAC-SHA256 of the body keyed with your app secret.

import hashlib, hmac, os
from flask import Flask, request, abort

app = Flask(__name__)
VERIFY_TOKEN = os.environ["WA_VERIFY_TOKEN"]        # any string; type the same one in the App Dashboard
APP_SECRET = os.environ["WA_APP_SECRET"].encode()   # App settings > Basic

@app.get("/webhook")
def verify():
    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():
    expected = "sha256=" + hmac.new(APP_SECRET, request.get_data(), hashlib.sha256).hexdigest()
    if not hmac.compare_digest(request.headers.get("X-Hub-Signature-256", ""), expected):
        abort(401)
    for entry in request.get_json().get("entry", []):
        for change in entry.get("changes", []):
            value = change.get("value", {})
            for msg in value.get("messages", []):
                print("IN", msg["from"], msg["type"], msg.get("text", {}).get("body"))
            for st in value.get("statuses", []):
                print("STATUS", st["id"], st["status"])
    return "", 200

if __name__ == "__main__":
    app.run(port=5000)

Meta has to reach this over HTTPS on a public address, and “Self-signed certificates are not supported”. For the first hour, a tunnelling tool in front of your laptop is fine, or the test webhook app that Get Started links to. Then put the URL and the verify token in the App Dashboard’s Configuration panel and subscribe to the messages field.

Build for repeats and gaps now. Meta retries failed deliveries “a few more times with decreasing frequency over the next 7 days”, so the same event can arrive twice; skip message IDs you’ve already stored, and expect batches of up to 1,000 updates in one POST. And “There are no APIs for fetching historical webhook data”, so whatever this handler drops is gone.

Can you build a Python WhatsApp bot on this?

Yes. A bot is this webhook plus the send function: when a message arrives, decide on a reply and call send() inside the 24-hour window. Replies are service messages, which Meta’s pricing page makes free for the first 1,000 per business number each month and ₹0.1150 each after that.

The useful bots are narrower than people expect. For Rohan’s client, a customer replying “status” could get a lookup against the billing database. Anything else should reach a person at the counter, and that needs an inbox, which comes up below.

The errors you’ll meet in the first hour

Most first-hour failures are one of six codes. Some come back on the HTTP response; others arrive later as a failed status on the webhook, which is why the handler above prints statuses.

CodeMeta’s wordingWhat it usually means in hour one
131030”Recipient phone number is not in allowed list.”The test number can only message recipients you’ve added in API Setup
190”Your access token has expired.”You’re still on the temporary token
132001”The template does not exist in the specified language or the template has not been approved.”Wrong name or language code, such as en for a template approved as en_US
131047”More than 24 hours have passed since the recipient last replied to the sender number.”Free text before the recipient replied
131026”Unable to deliver message.” Reasons include that the number isn’t on WhatsAppCheck the number; don’t retry
131049”This message was not delivered to maintain healthy ecosystem engagement.”WhatsApp’s per-user limit on marketing templates

One gap in Meta’s docs: its main error-codes page (Updated 18 Jun 2026) doesn’t list 131030. The wording above is from the Calling API troubleshooting page (Updated 24 Jun 2026), which adds that it “Only occurs when using public test numbers”. On 131049, Meta’s per-user limits page says to “wait at least 24 hours before attempting to resend”, and repeated retries can block delivery to that person for up to 24 hours. Our 131049 explainer has the detail, and what sent, delivered and read mean covers the status webhook.

What the test number can and can’t do

It can send templates without a payment method, receive replies, open a customer service window and drive every webhook above, to the recipients on its list. Everyone else gets 131030.

Going live means registering a number of your own. Meta’s phone numbers page says it must be owned by you, have a country and area code, and be able to receive a voice call or text message, and a number already on WhatsApp must be deleted from it first. Live sending needs a payment method on the account. A new business portfolio can reach 250 unique people in a moving 24 hours outside the customer service window, and business verification is the usual route to 2,000. Our explainer on the WhatsApp Business API in India covers that path, and the glossary defines the terms.

What you still have to build to run a business on it

The send call is the small part of the job. Before Rohan’s client can use this every day, someone has to build and keep running:

  • an inbox where the four counter staff can read replies, assign them and see the history
  • template creation and Meta’s approval status, per language
  • opt-in and opt-out records, so marketing goes only to people who agreed
  • storage for status webhooks, matched to message IDs, so the client can see what failed
  • retry rules by error code: one retry for a timeout, none for 131026 or 131049
  • token rotation, monitoring, and someone on call when Meta changes a version

You’ll also see tools that promise WhatsApp messages with no Meta account at all: pywhatkit in Python, Selenium scripts driving WhatsApp Web, Baileys in JavaScript. They automate the consumer app, which breaks WhatsApp’s terms and gets numbers banned or restricted. Don’t put a client’s shop number on one.

Here is what we’d tell Rohan. If the job is only the pickup template fired from billing, build it: one function, one template, a small webhook for statuses, and about ₹138 a month in Meta’s charges at his client’s example volume. If the counter staff will also answer customers on WhatsApp, don’t build the inbox. At an example rate of ₹1,500 an hour, ten hours a month of upkeep is ₹15,000, against ₹2,499 a month for a ready-made plan such as Conecxt Basic.

Rohan’s next step is the same as anyone’s. Send hello_world to your own phone, reply to it, send one line of free text, and watch both statuses arrive at the Flask handler. Then write down which of the six items above the client actually needs, and price the build against the plan before you quote.

Common questions

How do I send a WhatsApp message using Python?

Create a Meta app with the WhatsApp use case, copy the test phone number ID and a token from API Setup, then POST JSON to graph.facebook.com/<version>/<PHONE_NUMBER_ID>/messages with Python's requests library. Send the hello_world template first; free-text messages work only after the recipient replies to you.

Can I use the WhatsApp Business API with Python for free?

For testing, yes. Meta's test number can send template messages without a payment method on file, to the recipient numbers you add in the App Dashboard. In production Meta charges per delivered message: ₹0.1150 for a utility template to an Indian number and ₹0.8631 for marketing, before GST.

How do I build a WhatsApp bot in Python?

Run a small web server, for example in Flask, that answers Meta's webhook verification and receives message events by POST. When a customer's message arrives, call the send endpoint with a reply. Replies inside the 24-hour window are service messages, free for the first 1,000 per number each month.

What does WhatsApp API error 131030 mean?

Recipient phone number is not in allowed list. Meta's calling troubleshooting page says it only occurs when using public test numbers. Add the recipient's number to the test number's recipient list in the App Dashboard's API Setup panel and send again. Numbers outside that list can't be messaged from a test number.

Sources

  1. WhatsApp Business Platform overview, with a Python requests example (Meta for Developers) · No Updated date shown; read live 25 Oct 2026
  2. WhatsApp Cloud API Get Started (Meta for Developers) · Updated 16 Jun 2026, read live 25 Oct 2026
  3. About the platform: test resources (Meta for Developers) · Updated 4 Aug 2026, read live 25 Oct 2026
  4. Access tokens (Meta for Developers) · Updated 19 Sep 2026, read live 25 Oct 2026
  5. Send messages (Meta for Developers) · Updated 21 May 2026, read live 25 Oct 2026
  6. Text messages (Meta for Developers) · Updated 2 Jul 2026, read live 25 Oct 2026
  7. Webhooks overview (Meta for Developers) · Updated 26 Jun 2026, read live 25 Oct 2026
  8. Create a webhook endpoint (Meta for Developers) · Updated 17 Jun 2026, read live 25 Oct 2026
  9. Error codes (Meta for Developers) · Updated 18 Jun 2026, read live 25 Oct 2026
  10. Calling API troubleshooting, which lists error 131030 (Meta for Developers) · Updated 24 Jun 2026, read live 25 Oct 2026
  11. Per-user marketing template message limits (Meta for Developers) · Updated 17 Jun 2026, read live 25 Oct 2026
  12. Business phone numbers (Meta for Developers) · Updated 21 May 2026, read live 25 Oct 2026
  13. Messaging limits (Meta for Developers) · Updated 21 May 2026, read live 25 Oct 2026
  14. Pricing on the WhatsApp Business Platform (Meta for Developers) · Updated 30 Sep 2026; INR rate card effective 1 Oct 2026; read live 25 Oct 2026
Share WhatsApp LinkedIn

Get the next one

One email when something new is published. Nothing else.

Unsubscribe from any email. See our privacy policy.

Run this on your own number

Create an account, connect your WhatsApp number, and invite your team.