Skip to main content

whatsarab

Official Python client for the WhatsArab API — send WhatsApp messages on the official Meta Cloud API, upload media, manage templates, send and verify one-time codes, and verify signed webhooks.

pip install whatsarab

Python 3.9+.

Quick start

import os
from whatsarab import WhatsArab

wa = WhatsArab(api_key=os.environ["WHATSARAB_API_KEY"])

# Free-form text — only inside the 24-hour customer-service window
wa.messages.send(to="201234567890", text="أهلًا يا سارة! طلبك رقم ١٠٤٢٨ خرج للتوصيل.")

# An approved template — works any time
wa.messages.send(
    to="201234567890",
    template="order_shipped",
    language="ar",
    components=[{"type": "body", "parameters": [{"type": "text", "text": "10428"}]}],
)

Get an API key from /app/integrations → API keys. Keys are shown once, at creation.

What this covers

The API-key surface, which is the eleven operations under /api in the OpenAPI document:

wa.messages.send() text · template · interactive · media
wa.media.upload() / .download() multipart up, raw bytes back
wa.templates.list() / .create() / .edit() / .delete() Meta template management
wa.otp.send() / .verify() one-time codes over WhatsApp
wa.events.list() recent webhook events
verify_webhook_signature() HMAC check for deliveries to you

Not covered, deliberately: contacts, the inbox and broadcasts are session-authenticated — they belong to a signed-in dashboard user, not to a server-side key — so there is no endpoint for this client to call. If that changes, it changes in the OpenAPI document first.

Sending

Exactly one of template, text, interactive or media per call — checked locally, so a mistake is a ValueError on your machine rather than a 400 from production.

# Media: upload once, then send by id
with open("invoice.pdf", "rb") as fh:
    uploaded = wa.media.upload(fh, filename="invoice.pdf", content_type="application/pdf")

wa.messages.send(
    to="201234567890",
    media={"id": uploaded["media_id"], "kind": "document", "filename": "invoice.pdf"},
)

# Interactive buttons
wa.messages.send(
    to="201234567890",
    interactive={
        "type": "button",
        "body": {"text": "تحب نأكد الطلب؟"},
        "action": {"buttons": [{"type": "reply", "reply": {"id": "yes", "title": "أكيد"}}]},
    },
)

# Multi-number workspace: pick the sender explicitly
wa.messages.send(to="201234567890", text="hi", from_phone_number_id="113456789012345")

# Check the call without spending a message
wa.messages.send(to="201234567890", template="order_shipped", dry_run=True)

text, interactive and media are free but only deliverable inside the recipient's 24-hour customer-service window. Outside it the call fails with OUTSIDE_CSW and you need an approved template.

The response is a 202: Meta accepted the message. Delivery arrives later on the webhook bus, matched by message_id (the wamid).

One-time codes

sent = wa.otp.send(to="201234567890", template="otp_login", language="ar")
result = wa.otp.verify(request_id=sent["request_id"], code="123456")

if result["verified"]:
    ...

The code is generated, hashed and checked on our side — it is never returned to you.

Errors

Every failure — including a refused connection or a timeout — is a WhatsArabError, so one except covers the lot. Branch on .code, which is stable; the message is for humans and may be reworded.

from whatsarab import WhatsArabError

try:
    wa.messages.send(to="201234567890", text="hi")
except WhatsArabError as err:
    if err.code == "OUTSIDE_CSW":
        send_template_instead()
    elif err.code == "OVER_QUOTA":
        queue_for_next_month()
    elif err.code in ("TIMEOUT", "NETWORK_ERROR"):
        retry_later()
    else:
        raise

err.request_id is worth logging — quote it in a support ticket and we can find the exact request.

Verifying webhooks

Deliveries to your endpoint carry X-Whatsarab-Timestamp and X-Whatsarab-Signature: sha256=<hex>, computed over f"{timestamp}.{raw_body}" with your subscription secret.

from fastapi import FastAPI, HTTPException, Request
from whatsarab import verify_webhook_signature

app = FastAPI()

@app.post("/webhooks/whatsarab")
async def hook(request: Request):
    body = await request.body()          # the raw bytes
    ok = verify_webhook_signature(
        secret=os.environ["WHATSARAB_WEBHOOK_SECRET"],
        raw_body=body,
        signature_header=request.headers.get("x-whatsarab-signature"),
        timestamp_header=request.headers.get("x-whatsarab-timestamp"),
    )
    if not ok:
        raise HTTPException(status_code=401)
    ...

Pass the raw body. A body that has been parsed and re-serialized will not match — that is the single commonest way this check is got wrong. The comparison is constant-time, and deliveries more than five minutes old are rejected (tolerance_seconds=0 turns that off).

Options

WhatsArab(
    api_key="…",                       # required
    base_url="https://whatsarab.com",  # override for staging or self-hosted
    timeout=30.0,                      # seconds; None disables
)

The client holds an httpx.Client. Close it when you are done, or use it as a context manager:

with WhatsArab(api_key="…") as wa:
    wa.messages.send(to="201234567890", text="hi")

MIT.

Metadata

Release files for whatsarab 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for whatsarab 0.1.0
File Size Uploaded Provenance Actions
whatsarab-0.1.0.tar.gz 10.2 kB Without provenance Details for whatsarab-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for whatsarab 0.1.0
File Interpreter ABI Platform Actions
whatsarab-0.1.0-py3-none-any.whl Python 3 none any Details for whatsarab-0.1.0-py3-none-any.whl

Total release size: 19.4 kB

Release files / whatsarab-0.1.0.tar.gz

Download URL whatsarab-0.1.0.tar.gz
Size 10.2 kB
Tags Source
SHA-256 checksum
How to use checksums
cd004dd6e5231d21759bd9a3220d416ce58523e27171c0962e63e25e38fc3ca1
BLAKE2b-256 checksum
How to use checksums
4f2082219e70cc46378f4766375e365e9c32ea09434464b3a6cba9b67fbcb9d4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.9.6

Release files / whatsarab-0.1.0-py3-none-any.whl

Download URL whatsarab-0.1.0-py3-none-any.whl
Size 9.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
9a8652d1da50314260f3f2cb8575ce093ed53c1fc6e9c91d1a8e4aef55a0aeeb
BLAKE2b-256 checksum
How to use checksums
19b77af574ee4c435321e640ab3f179bb994714912530cecf34e54da9251f8d5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.9.6

Security for whatsarab 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page