How to Send WhatsApp Messages via API (Link, Text, Media)
A send-WhatsApp API looks, from a distance, like a lookup: you already have a phone number, you already have a sentence, so one POST should be enough. That assumption is what stalls the first integration. Lookup products answer “is this number on WhatsApp?” without anyone’s account. Messaging speaks as an account. Until that account is linked, there is no sender, and a perfectly formed text field still has nowhere to go.
The job is a pipeline: link a session, then send — and validate the recipient before you attach media. Copy an authorized platform key from the dashboard after you sign in. Put it in key and keep it on the server. Opening this page or copying the snippets does not send a data request. Replacing YOUR_API_KEY and running a command does, and that call spends credits. Use only accounts you own or are authorized to operate, and follow WhatsApp’s terms.
A send is not a lookup
A lookup is stateless: one number, one answer, no inbox. A send lives on a linked device. Every operation under WhatsApp Messaging takes a sessionId that represents that device. Without a CONNECTED session, send-message has nothing to speak as.
The request shape is also not a lookup GET. Query parameters carry key and sessionId. GET and DELETE put remaining fields on the query string. POST wraps the operation JSON as a string inside a body field. Replies are wrapped twice, as {"code": 200, "message": "success", "data": {"code": 200, "data": {...}}}. The outer layer is the platform. The inner layer is the messaging service, which answers HTTP 200 even when it rejects the work and reports code, title, and detail inside. A platform 401 means the key is missing or invalid; 403 means insufficient credits or an inactive account. Reading only the HTTP status line will treat a refused send as success.
The helper below peels both envelopes. Set OPENDATA_API_KEY in the server environment.
import json
import os
import time
import requests
BASE = "https://api.opendata-api.com/api/project/whatsapp-messaging"
SUCCESS_CODES = {200, 201, 202, 204}
def call(method, operation, payload=None, **params):
"""Call one operation and return the innermost payload (dict, list or None)."""
params["key"] = os.environ["OPENDATA_API_KEY"]
kwargs = {"params": params, "timeout": 60}
if payload is not None:
kwargs["json"] = {"body": json.dumps(payload)}
resp = requests.request(method, f"{BASE}/{operation}", **kwargs)
if not resp.ok:
raise RuntimeError(f"{operation} failed: HTTP {resp.status_code}")
body = resp.json()
# Peel both envelopes; inner HTTP 200 is not a business success
while isinstance(body, dict) and "code" in body:
if body["code"] not in SUCCESS_CODES:
raise RuntimeError(f"{operation} failed: inspect redacted diagnostics")
body = body.get("data")
return body
If you only need registration, stay on the session-free checkers: how to check if a number is on WhatsApp, the WhatsApp number lookup guide, and bulk verification of WhatsApp numbers. Do not open a session just to ask whether a number exists.
Link the account before the first text
create-session starts login. QR is the usual path:
curl -X POST "https://api.opendata-api.com/api/project/whatsapp-messaging/create-session?key=YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"body":"{\"mode\":\"qr\",\"deviceName\":\"My Bot\"}"}'
Then poll get-session with the session ID. While login is pending, the payload can carry a scannable qrImage (a base64 data-URI) and a qrPageUrl you can open in a browser. On the phone, open WhatsApp, go to Settings, then Linked Devices, choose Link a device, and scan the code.
If scanning is awkward, use pairing-code login instead. Send {"mode":"pairing","phoneNumber":"8613800138000","deviceName":"My Bot"}, where phoneNumber is the full international number, digits only, with no + and no spaces. The status payload then includes an 8-character pairingCode. On the phone choose Link a device, then Link with phone number instead, and type the code. deviceName is the label shown under Linked Devices.
The create-session reply puts the session in data.data with an inner code of 201. The identifier is the id field. Every later call passes that value as the sessionId query parameter — sessionId is only the parameter name.
session = call("POST", "create-session", {"mode": "qr", "deviceName": "My Bot"})
session_id = (session or {}).get("id")
if not session_id:
raise RuntimeError("no session id in the response")
deadline = time.time() + 180
while time.time() < deadline:
state = call("GET", "get-session", sessionId=session_id)
if state.get("status") == "CONNECTED":
break
if state.get("status") in ("FAILED", "LOGGED_OUT"):
raise RuntimeError("login did not complete")
time.sleep(3)
else:
raise TimeoutError("account was not linked in time")
The statuses are CREATED, WAITING_FOR_SCAN, CONNECTING, CONNECTED, DISCONNECTED, LOGGED_OUT, and FAILED. After the first successful link, id becomes a stable value derived from the linked device. You do not scan again unless you logged out. get-session lazily reconnects a saved but offline account; an explicit reconnect is available when you want it on demand.
Text, then media, then the inbox
Do not send first and validate later. check-contact-exists uses the connected session to tell you whether a number has an active WhatsApp account. The payload carries exists, the contact’s jid, and the query you sent. Pass the number as phoneNumber, digits only.
info = call("GET", "check-contact-exists", sessionId=session_id, phoneNumber="8613800138000")
if not info.get("exists"):
raise RuntimeError("recipient is not on WhatsApp; skip the send")
For a whole list, the session-free lookups above are the better fit. Use the session check for the numbers you are about to message.
Once the session is CONNECTED and the recipient exists, call send-message with the recipient in to and the message in text. One detail trips up almost everyone: to is the full international number, digits only with no +, and it must be a JSON number, not a string. Write 8613800138000, not "+86 138 0013 8000".
curl -X POST "https://api.opendata-api.com/api/project/whatsapp-messaging/send-message?key=YOUR_API_KEY&sessionId=SESSION_ID" \
-H "Content-Type: application/json" \
-d '{"body":"{\"to\":8613800138000,\"text\":\"Hello from the API!\"}"}'
sent = call(
"POST",
"send-message",
{"to": 8613800138000, "text": "Hello from the API!"},
sessionId=session_id,
)
# sent may include id, timestamp, and to — treat it as a receipt, not a delivery guarantee
To send a quoted reply, add quoteMessageId with a message id taken from the inbox or chat history. There is no idempotency key. After a timeout, look at the chat before you send the same text again.
send-media takes the same numeric to, a type of image, video, audio, voice, document, or sticker, and the base64-encoded file as data. voice sends a push-to-talk voice note. A document requires fileName. caption adds a caption, mimeType overrides the inferred type, and seconds sets audio or video duration. Validate the recipient before this call: a bounced PDF is noisier than a bounced sentence.
import base64
with open("receipt.pdf", "rb") as fh:
data = base64.b64encode(fh.read()).decode("ascii")
call("POST", "send-media", {
"to": 8613800138000,
"type": "document",
"data": data,
"fileName": "receipt.pdf",
"caption": "Your receipt",
}, sessionId=session_id)
list-inbox returns messages received in real time while the session was connected, newest first. Each item has the message id, chatJid, sender, type, text, and timestamp. The inbox holds the most recent 500 messages per session and is cleared on restart, so poll it and copy what you need into your own store. Use limit to cap the page. mark-read with chatJid and messageIds sends read receipts.
const key = process.env.OPENDATA_API_KEY;
const sessionId = process.env.WHATSAPP_SESSION_ID;
const url = new URL(
"https://api.opendata-api.com/api/project/whatsapp-messaging/list-inbox"
);
url.searchParams.set("key", key);
url.searchParams.set("sessionId", sessionId);
url.searchParams.set("limit", "50");
const resp = await fetch(url);
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
let body = await resp.json();
while (body && typeof body === "object" && "code" in body) {
if (![200, 201, 202, 204].includes(body.code)) {
throw new Error("business failure; inspect redacted diagnostics");
}
body = body.data;
}
for (const msg of body || []) {
console.log(msg.id, msg.chatJid, msg.text);
}
What you still must not automate
This pipeline is for conversations people already expect: opted-in users, customers, transactional updates. It is not a tool for cold lists. Unsolicited or identical bulk text puts the linked account at risk, and no REST wrapper changes WhatsApp’s terms.
Do not treat HTTP 200 as a delivered message. Do not retry send-message in a loop after a timeout. Do not attach media to numbers you have not checked. Do not treat list-inbox as a durable log — it is a live window of 500, wiped on restart. Do not call disconnect with logout=true unless you intend to wipe the saved login; the default disconnect drops the live socket and keeps credentials so get-session can bring the account back.
Pace sends. Vary copy. Keep the key off the client. If sends start failing, call get-session before you invent a retry storm. The messaging project also covers polls, reactions, edits, groups, and privacy; those are extra stages, not a shortcut around linking, validating, and sending one real message at a time.