Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

17.8 KB
Raw Blame

OpenWA SDKs

This document describes SDK 0.7.0. Send idempotency, webhook failure redrive, message-window filters, poll choices, last-message types, and the event.response webhook event name require OpenWA 0.25.0 or later. The message.receipt and poll.vote webhook event names require OpenWA 0.26.0 or later.

Official client libraries for OpenWA, the open-source WhatsApp API Gateway. OpenWA is an independent project, not affiliated with or endorsed by WhatsApp or Meta.

All five SDKs are hand-written against the exact API surface (paths, DTOs, response shapes) and unit-tested with mocked HTTP transports that assert on the precise request URL, method, and body — so drift is caught at test time. The JavaScript, Python, Java and Go wire types live in dedicated files (types.ts / types.py / model/ / types*.go) so they can later be regenerated by an OpenAPI codegen pass without touching the hand-written resource methods; the PHP SDK has no types layer and returns plain arrays.

Language Package Notes
JavaScript / TypeScript @rmyndharis/openwa dual ESM/CJS, bundled types
Python rmyndharis-openwa sync (httpx), PEP 561 typed
PHP rmyndharis/openwa sync (Guzzle, PHP 8.1+)
Java com.rmyndharis:openwa sync (java.net.http + Gson, Java 17)
Go github.com/rmyndharis/OpenWA/sdk/go stdlib-only, context-first, injectable transport (Go 1.22+)

Coverage

All five SDKs expose the same fluent resource surface:

Resource Methods
sessions list, get, getConfig, updateConfig, getProxy, updateProxy, create, delete, start, stop, logout, forceKill, getQrCode, requestPairingCode, setOnlinePresence, stats
messages list, sendText, sendImage/Video/Audio/Document/Sticker, sendLocation, sendContact, sendTemplate, sendPoll, reply, clickButton, forward, react, delete, editMessage, history, reactions, media, pin, unpin, star, votePoll, sendBulk, batchStatus, cancelBatch
contacts list, get, check, profilePicture, profilePictures, phone, upsert, delete, block, unblock, listBlocked
groups list, get, create, joinGroup, joinInfo, add/remove/promote/demoteParticipants, setSubject, setDescription, setMemberLabel, get/updateGroupSettings, leave, getPicture, setPicture, deletePicture, inviteCode, revokeInviteCode, getMembershipRequests, approveMembershipRequests, rejectMembershipRequests
webhooks list, listAll, deliveryFailures, redriveDeliveryFailures, get, create, update, delete, test
chats list, markRead, markUnread, archive, pin, mute, clearMessages, delete, sendState, subscribePresence, getPresence
labels list, get, chats, forChat, upsert, delete, addToChat, removeFromChat (WhatsApp Business)
channels list, get, messages, create, delete, mute, subscribe, unsubscribe, demoteAdmin, transferOwnership (Newsletters)
catalog info, products, product, sendProduct (WhatsApp Business)
status list, fromContact, media, sendText, sendImage, sendVideo, sendVoice, delete (Stories)
search search (Operator)
templates list, get, create, update, delete
profile setProfileName, setProfileStatus, setProfilePicture, deleteProfilePicture (OPERATOR)
calls rejectCall, createLink (OPERATOR)
media conversionStatus, convertVoice (OPERATOR), convertVideo (OPERATOR)
health check, live, ready
auth validate (client.auth(); client.Auth.Validate in Go)

⚠️ Endpoints requiring an OPERATOR-level API key are noted in the inline docs. Deliberately not exposed, matching docs/18-sdk-design.md exactly: auth/api-keys (key validation itself is the auth row above), audit, settings, stats, automation, infra, plugins, the integration management routes, metrics, mcp, ingress and docker. These two lists have to agree — they did not, in both directions, and a list that disagrees with its own design doc reads as an accidental omission rather than a decision.

Everything else the gateway publishes is exposed. That sentence used to be an unqualified "all user-facing resources are", which was false for the session config routes and the two cross-session webhook reads until they were added.

One entry in the list above is special: mcp is absent from the generated openapi.json itself, not just from the SDKs — POST /mcp is mounted directly on the Express adapter, outside the Nest /api routing the Swagger scanner sees, so the exporter cannot emit it. Do not hand-add it to openapi.json (npm run openapi:check regenerates the file and the diff fails); the route is documented by hand in docs/06-api-specification.md, and the docs-contract gate names POST /mcp as the one heading allowed outside the contract.

Every example below addresses a session by its id: the UUID that sessions.create() returns, not the name passed to it. Create a session once (a second create with the same name answers 409); afterwards, find its id with sessions.list filtered by name.

JavaScript / TypeScript

npm install @rmyndharis/openwa
import { OpenWAClient } from '@rmyndharis/openwa';

const client = new OpenWAClient({
  baseUrl: 'http://localhost:2785',
  apiKey: 'owa_k1_…',
});

const session = await client.sessions.create({ name: 'my-session' });
await client.sessions.start(session.id);
// Link the account before sending: scan sessions.getQrCode (or use sessions.requestPairingCode for a number with no linked session),
// then wait for status 'ready'. An unlinked session answers the send with 409.
const result = await client.messages.sendText(session.id, {
  chatId: '[email protected]',
  text: 'Hello from the OpenWA SDK!',
});
console.log(result.messageId);

Errors are typed — branch with instanceof:

import { OpenWANotFoundError, OpenWAConflictError } from '@rmyndharis/openwa';
try {
  await client.messages.sendText(/* … */);
} catch (e) {
  if (e instanceof OpenWAConflictError) {
    /* a conflicting state (409): typically a session not ready, or a keyed send pending or unconfirmed */
  }
}

Requires Node 18+ (uses the global fetch). Pass a custom fetch to the client constructor to intercept or observability-wrap requests.

Python

pip install rmyndharis-openwa
from openwa import OpenWAClient, OpenWANotFoundError

client = OpenWAClient(
    base_url="http://localhost:2785",
    api_key="owa_k1_…",
)

session = client.sessions.create({"name": "my-session"})
client.sessions.start(session["id"])
# Link the account before sending: scan sessions.get_qr_code (or use sessions.request_pairing_code for a number with no linked session),
# then wait for status "ready". An unlinked session answers the send with 409.
result = client.messages.send_text(session["id"], {
    "chatId": "[email protected]",
    "text": "Hello from the OpenWA Python SDK!",
})
print(result["messageId"])

Pass transport=httpx.MockTransport(handler) for testing — no global monkey-patching required.

PHP

composer require rmyndharis/openwa
<?php
use OpenWA\Client;

$client = new Client([
    'baseUrl' => 'http://localhost:2785',
    'apiKey'  => 'owa_k1_…',
]);

$session = $client->sessions->create(['name' => 'my-session']);
$client->sessions->start($session['id']);
// Link the account before sending: scan sessions->getQrCode (or use sessions->requestPairingCode for a number with no linked session),
// then wait for status 'ready'. An unlinked session answers the send with 409.
$result = $client->messages->sendText($session['id'], [
    'chatId' => '[email protected]',
    'text'   => 'Hello from the OpenWA PHP SDK!',
]);
echo $result['messageId'];

Requires PHP 8.1+ and Guzzle 7.9+ or 8.x. For testing, inject a Guzzle client whose handler is a MockHandler — no global state, no network.

Java

<dependency>
  <groupId>com.rmyndharis</groupId>
  <artifactId>openwa</artifactId>
  <version>0.7.0</version>
</dependency>
import com.rmyndharis.openwa.OpenWAClient;
import com.rmyndharis.openwa.model.CreateSessionRequest;
import com.rmyndharis.openwa.model.MessageResponse;
import com.rmyndharis.openwa.model.SendTextRequest;
import com.rmyndharis.openwa.model.SessionResponse;

OpenWAClient client = new OpenWAClient("http://localhost:2785", "owa_k1_…");

SessionResponse session = client.sessions.create(CreateSessionRequest.builder().name("my-session").build());
client.sessions.start(session.id());
// Link the account before sending: scan sessions.getQrCode (or use sessions.requestPairingCode for a number with no linked session),
// then wait for status READY. An unlinked session answers the send with 409.
MessageResponse result = client.messages.sendText(session.id(),
    SendTextRequest.builder()
        .chatId("[email protected]")
        .text("Hello from the OpenWA Java SDK!")
        .build());
System.out.println(result.messageId());

Requires Java 17+. Errors are a typed, unchecked hierarchy — branch with instanceof OpenWANotFoundError / OpenWAConflictError. For testing, inject a custom HttpTransport that records the request — no network. See java/README.md for the full guide.

Go

go get github.com/rmyndharis/OpenWA/sdk/go
import (
    "context"
    "fmt"
    "log"

    openwa "github.com/rmyndharis/OpenWA/sdk/go"
)

client, err := openwa.New("http://localhost:2785", "owa_k1_…")
if err != nil {
    log.Fatal(err)
}

ctx := context.Background()
session, err := client.Sessions.Create(ctx, openwa.CreateSessionRequest{Name: "my-session"})
if err != nil {
    log.Fatal(err)
}
if _, err := client.Sessions.Start(ctx, session.ID); err != nil {
    log.Fatal(err)
}
// Link the account before sending: scan Sessions.QRCode (or use Sessions.RequestPairingCode for a number with no linked session),
// then wait for status "ready". An unlinked session answers the send with 409.
res, err := client.Messages.SendText(ctx, session.ID, openwa.SendTextRequest{
    ChatID: "[email protected]",
    Text:   "Hello from the OpenWA Go SDK!",
})
if err != nil {
    log.Fatal(err)
}
fmt.Println(res.MessageID)

Requires Go 1.22+. Stdlib-only, context-first. Errors are typed — match with errors.Is(err, openwa.ErrConflict) or unwrap *openwa.APIError with errors.As. Inject an http.RoundTripper with openwa.WithTransport(...) for testing, retry, tracing, or metrics. See go/README.md.

Reliability & security

  • Use HTTPS in production. The API key is sent as X-API-Key on every request and is bearer-equivalent — never send it over plaintext http:// outside local development.
  • No automatic retries by default. A failed request raises/throws immediately; wrap calls in your own backoff if you need retries (especially for 429). The injectable transport (fetch / transport / httpClient) is the extension point for retry or observability middleware. The Go client is the exception: it ships an opt-in policy (WithRetry(DefaultRetryPolicy())) that retries idempotent requests on network errors and 429/5xx, retries a POST/PATCH only on 429/503 (never after a network error), never retries a send-pacing 429 (code: "SEND_PACING_LIMITED"), honors Retry-After, and rewinds request bodies — still off unless you ask for it.
  • Webhook signatures. Every SDK verifies a delivery's X-OpenWA-Signature against the raw request body: verifyWebhookSignature (JavaScript), verify_webhook_signature (Python), VerifyWebhookSignature (Go), WebhookSignature.verify (Java) and WebhookSignature::verify (PHP). The JavaScript, Python, Go and Java SDKs also type the delivery body as WebhookDelivery.
  • Redirects are never followed. A 3xx surfaces to the caller rather than being followed, so the API key is never re-sent to a redirect target.
  • Default timeout is 30s (configurable). 0 turns it off in the JavaScript, Python and PHP clients; the Go client reads 0 as the 30s default and the Java builder refuses it. The JavaScript, PHP, Go and Java clients bound the whole call, response body included, except PHP on Guzzle 7's stream handler (below). The Python client's is per network operation (connect, read, write, pool), so a response that keeps trickling bytes is not cut off. On PHP, Guzzle 7's stream handler (a host without ext-curl) bounds each wait instead of the whole call: the wait for the response headers and each silence in the body, which can last up to about twice the timeout. A body that keeps trickling bytes is therefore not cut off. There a 0 still leaves PHP's default_socket_timeout (60s by default) before the response headers, and that wait ends with a Guzzle exception, not OpenWATimeoutException; see the PHP README. Path segments (chat / message ids) are percent-encoded; a base-URL path prefix (e.g. behind a proxy at /v1) is preserved.

Development

# JavaScript
cd sdk/javascript && npm test && npm run build && npm run smoke
# Python
cd sdk/python && python -m pytest -q
# PHP
cd sdk/php && composer install && ./vendor/bin/phpunit
# Java
cd sdk/java && mvn -B verify
# Go
cd sdk/go && go test -race ./... && go vet ./...

Each test suite mocks the HTTP layer and asserts on the exact path, so the regression that originally shipped a broken messages/text path (the real path is messages/send-text) can never recur silently.