Skip to main content
Version: v0.31.0

Use an official OpenWA SDK

The OpenWA SDKs are official client libraries that wrap the REST API in a typed, fluent interface. You instantiate one client, point it at your gateway, and call resource methods like client.messages.sendText(...) instead of hand-building HTTP requests, signing headers, and parsing error envelopes.

This page gets you from npm install to a sent WhatsApp message: pick an SDK, install it, and run a verified hello-world.

Prerequisites
  • A running OpenWA gateway. See Installation — the examples assume the local default http://localhost:2785.
  • An API key sent as the X-API-Key header. See Authentication to obtain one.
  • A WhatsApp account you can scan a QR code with from your phone.

Which SDK to use​

There are five first-party SDKs. All five are hand-written against the exact API surface (paths, request bodies, response shapes), and each has unit tests that run against a mocked transport and check the requests the SDK builds.

LanguagePackageInstallRequires
JavaScript / TypeScript@rmyndharis/openwanpm install @rmyndharis/openwaNode 18+
Pythonrmyndharis-openwa (imports as openwa)pip install rmyndharis-openwaPython 3.9+
PHPrmyndharis/openwacomposer require rmyndharis/openwaPHP 8.1+, Guzzle 7.9+ or 8.x
Javacom.rmyndharis:openwaMaven / Gradle (see below)Java 17+
Gogithub.com/rmyndharis/OpenWA/sdk/gogo get github.com/rmyndharis/OpenWA/sdk/goGo 1.22+

They expose the same resource surface; only the language idioms differ — camelCase methods with objects in JS and PHP, snake_case methods with dicts in Python, fluent builders in Java, and exported service fields (client.Messages, client.Sessions) in Go. Examples on this page use the JavaScript/TypeScript SDK; the Python and PHP equivalents are below the hello-world.

Java install (Maven / Gradle):

<dependency>
<groupId>com.rmyndharis</groupId>
<artifactId>openwa</artifactId>
<version>0.13.0</version>
</dependency>
implementation 'com.rmyndharis:openwa:0.13.0'

The Java SDK is synchronous, has a single runtime dependency (Gson), and builds typed request/response records with a fluent Builder. The Go SDK is stdlib-only (zero third-party dependencies), context-first, and groups the API onto exported service fields with typed sentinel errors you match with errors.Is/errors.As.

The SDKs version independently of the gateway

SDK versions follow SemVer but do not track the gateway version (documented here at v0.31.0). The latest released version of all five SDKs is 0.13.0, which adds the optional phone field of a chat summary (gateway v0.31.0+) and lets the JavaScript and Python types of a webhook update send secret: null, alongside the 0.12.0 linkPreview session config key (gateway v0.30.3+), the 0.11.0 passkey_required (PASSKEY_REQUIRED in Java, RestrictionPasskeyRequired in Go) on AccountRestrictionKind (gateway v0.30.0+) and optional isForwarded and forwardingScore fields on ChatHistoryMessage (gateway v0.29.1+), the 0.10.0 per-recipient delivery receipts read (messages.receipts / messages.getReceipts / Messages.Receipts, gateway v0.28.0+), the 0.9.0 LID lookup (contacts.lid / contacts.getLid / Contacts.Lid, gateway v0.27.1+), and the 0.8.0 additions (groups.setMemberLabel, search.search match, and customLinkPreview thumbnailUrl / thumbnailBase64). While they are below 1.0, a minor bump can still break you, 0.3.0, 0.4.0, 0.5.0, 0.6.0, 0.7.0, 0.9.0, 0.10.0, 0.11.0, 0.12.0, and 0.13.0 all did, and so did the 0.5.1 patch, and the changes are listed below. Pin the SDK version your code is tested against, and read the release notes before you move off it. Note the one gateway/SDK mismatch that straddles v0.19.0: SDK 0.3.0 still carries the five sendCatalog methods, whose route the v0.19.0 server removed, that call now gets 404 where it used to get 501. SDK 0.4.0 drops the methods entirely.

Since v0.14.2 the JavaScript, Python and PHP SDK releases are cut from CI on their own tag rather than by hand: the JavaScript SDK publishes to npm via Trusted Publishing (js-sdk-v* tag), the Python SDK publishes to PyPI via Trusted Publishing (py-sdk-v* tag), and the PHP SDK cuts versioned releases that tag the Packagist mirror (php-sdk-v* tag). The Java SDK is also released from CI, on a java-sdk-v* tag. The Go SDK has no release workflow: the module is served from the repository tag, so pushing a tag that carries the sdk/go/ module prefix is the release, and a bare v* tag never publishes it. The npm package carries build provenance and the PyPI files carry attestations, the Maven Central artifacts are GPG-signed, and the PHP and Go packages carry none of these. Only the Java SDK needs registry credentials: Maven Central has no Trusted Publishing equivalent, so it publishes with a Sonatype Central user token and a GPG signing key held as repository secrets. The PHP release needs a repository secret of its own, PHP_SDK_SPLIT_TOKEN, to tag the Packagist mirror; a missing token fails that release outright rather than skipping quietly, since a release that publishes nothing looks exactly like one that worked. The JavaScript, Python and Go releases need no secret at all.

Who the SDK is for​

Use the SDK if you are building an application or automation against an OpenWA gateway — sending messages, managing sessions and groups, configuring webhooks, or working with the WhatsApp Business surfaces. If you would otherwise write fetch/curl calls against the API reference, the SDK gives you the same capabilities plus type safety, percent-encoded path segments, typed errors, and a 30-second per-request timeout out of the box.

It is a request/response client, not an event SDK

The SDK does not open WebSockets, emit events, or expose client.on(...). To receive inbound messages and delivery acks, register a webhook with the webhooks resource and host your own HTTP receiver. See the Webhooks guide.

The resource surface​

A single client exposes each user-facing resource as a property — everything the gateway publishes except the administrative and operational modules listed below. Each maps to one API resource.

ResourceWhat it does
sessionsList, create, start, stop, force-kill, and inspect sessions; read and change a running session's config; read and change its proxy; fetch QR / pairing codes
messagesSend text, media, location, contacts, templates; reply, forward, react, bulk-send; read a chat's live history, a message's reactions, and an outbound message's per-recipient delivery receipts (whatsapp-web.js only: Baileys answers 501)
contactsLook up contacts, check numbers, resolve phone numbers and Linked Identities (lid / getLid / Lid, v0.27.1+), block / unblock
groupsCreate groups (Baileys only: whatsapp-web.js answers 501), manage participants, set subject / description / own member label (setMemberLabel, Baileys only, v0.27.0+), invite codes
webhooksConfigure event delivery to your own HTTP endpoints; list webhooks across every session, read the delivery-failure log, and redrive retained failures
chatsList chats (a Baileys chat held under a privacy id carries its phone when the session can map it, v0.31.0+), mark read / unread, send typing state, pin / unpin, mute / unmute (v0.16.0+)
templatesManage reusable message templates
labelsWhatsApp Business labels; reading them (list, get, chats, forChat) is whatsapp-web.js only: Baileys answers 501
channelsWhatsApp Channels / newsletters: list them and read their messages (whatsapp-web.js only), subscribe by invite code (Baileys only), demote an admin and transfer ownership (v0.16.0+, Baileys only). The engine that cannot do it answers 501
catalogWhatsApp Business product catalog (Baileys only: whatsapp-web.js answers 501)
statusWhatsApp Status / stories
searchSearch messages and chats (word-prefix or match=contains substring search on gateway v0.27.0+)
profileSet the linked account's display name, status text, and profile picture
callsReject an incoming call (Baileys only: whatsapp-web.js answers 501 since v0.23.6), create a shareable call link (v0.16.0+)
mediaServer-side conversion into the formats WhatsApp plays, plus a check for whether it is available
healthLiveness / readiness checks

The client also carries two top-level methods: auth() (client.Auth.Validate in Go) validates the configured key and resolves its role, and request() (client.Do in Go) is a raw escape hatch for any endpoint the resources do not yet wrap. SDK 0.5.1 and later include sessions.getProxy, sessions.updateProxy and messages.clickButton (snake_case in Python, Sessions.GetProxy, Sessions.UpdateProxy and Messages.ClickButton in Go). See SDK usage for the proxy and the button click.

What the SDKs deliberately leave out

The SDKs cover the user-facing resources above and stop there. The administrative and operational surfaces are not exposed, by design: API-key management under auth, audit, settings, the standalone stats module, automation, infra, plugins, and the integration management routes are predominantly ADMIN-gated; metrics is a Prometheus scrape gated by a token rather than by role; mcp is a Streamable-HTTP transport mounted straight onto the HTTP adapter; ingress is the public receiver integration providers post into; and docker has no HTTP surface at all. Everything else the gateway publishes is reachable through a resource method — request() is for a route newer than your SDK, not for a whole module.

Individual methods that still need an OPERATOR-level key (for example creating a session or a webhook) are annotated in the SDK's inline docs; a non-operator key receives 403.

Migrating to SDK 0.13.0

Breaking (Python callers).

  • Call link startTime. CreateCallLinkRequest.startTime is int instead of float, so a float, such as time.time() * 1000, now fails type-checking. The wire is unchanged: the gateway refuses a fraction with 400. The PHP docblock narrows startTime to int as well. In JavaScript, Go and Java the type is unchanged and the field comments say a whole number.

Additive.

  • Chat phone: ChatSummary.phone carries the phone digits of a Baileys chat held under a privacy id (@lid) when the session can map it, as phone?: string in JavaScript, NotRequired[str] in Python, Phone string (omitted when empty) in Go and String phone in Java; PHP returns it in the decoded array. whatsapp-web.js lists no phone. A Baileys privacy-id chat with no name of its own lists name as "", so title it by phone, else by id. Requires gateway v0.31.0 or later. Java's ChatSummary keeps its earlier 11- and 12-argument constructors, which leave phone null.
  • Webhook secret: UpdateWebhookRequest.secret accepts null in the JavaScript (string | null) and Python (str | None) types. The gateway clears the stored secret for null as it does for "". In Go and Java clear it with the empty string: a nil Secret in Go and a null secret(...) in Java are left out of the request.

Fixes.

  • PHP: the list fields mentions (text, media, template, reply and edit sends, and bulk items), poll options (sendPoll and votePoll), status recipients, webhook events and filters (the conditions list and a condition's list value), the ids of redriveDeliveryFailures and the messageIds of chats->markRead are sent as JSON arrays when their keys have gaps (array_filter, array_unique), which the gateway refused with 400. Group participants and the bulk messages list were already re-indexed. A body passed to the raw request() is sent as given, so pass its lists through array_values().
  • Python: the source distribution ships tests/conftest.py, so the tests run from the unpacked archive.
What's new in SDK 0.12.1

Fixes.

  • PHP: an empty request body is sent as {} instead of [], which the gateway refused with 400 on config, proxy, webhook and template updates. It applies to every call whose body is empty, the raw request() included, and not to an empty list nested inside a body.
  • Java: an OpenWAApiError with a JSON body can be Java-serialized, where it threw NotSerializableException for the Gson body; the body reads back as the same JSON.
Migrating to SDK 0.12.0

Breaking (JavaScript and Python callers).

  • SessionConfig requires linkPreview. The JavaScript and Python types declare linkPreview (boolean | null, bool | None) as a required field of the config read, so a hand-built SessionConfig or a test double needs it. A gateway older than v0.30.3 does not send the key, so Python's config["linkPreview"] raises KeyError and JavaScript reads undefined against one.

Additive.

  • Session config linkPreview: sessions.getConfig and sessions.updateConfig read and write the default link preview of a send-text or send-template that sets neither linkPreview nor customLinkPreview. It is linkPreview on SessionConfig and UpdateSessionConfigRequest in JavaScript (boolean | null) and Python (bool | None), LinkPreview *bool with a ClearLinkPreview flag in Go, and a linkPreview component on Java's SessionConfig and UpdateSessionConfigRequest, with linkPreview(Boolean) and clearLinkPreview() on the request builder; PHP takes the key in the body array. null restores the engine's default. Requires gateway v0.30.3 or later. Java's SessionConfig and UpdateSessionConfigRequest keep their earlier 3- and 6-argument constructors, which leave linkPreview unset.
Migrating to SDK 0.11.0

Breaking (Java callers).

  • AccountRestrictionKind gains PASSKEY_REQUIRED. In Java, AccountRestrictionKind adds @SerializedName("passkey_required") PASSKEY_REQUIRED, so a switch expression over it without a default branch must handle the new constant. ChatHistoryMessage also adds Boolean isForwarded and Long forwardingScore to its record components while keeping a 26-argument compatibility constructor that preserves the 0.10.0 signature.

Additive.

  • Passkey restriction kind: AccountRestrictionKind includes 'passkey_required' in JavaScript and Python, RestrictionPasskeyRequired ("passkey_required") in Go, and PASSKEY_REQUIRED in Java, matching gateway v0.30.0 (restriction on GET /api/sessions/{sessionId}, GET /api/sessions, POST /api/sessions/{sessionId}/start, and session.restriction webhook payloads when WhatsApp requests a passkey during Baileys linking).
  • Forwarded live-history metadata: ChatHistoryMessage declares optional isForwarded and forwardingScore in JavaScript (isForwarded?: boolean; forwardingScore?: number), Python (NotRequired[bool] / NotRequired[int]), Go (IsForwarded bool, ForwardingScore int64), and Java (Boolean isForwarded, Long forwardingScore), matching GET /api/sessions/{sessionId}/messages/{chatId}/history since gateway v0.29.1.
Migrating to SDK 0.10.0

Breaking.

  • Raw request path validation. request() (client.Do in Go) now rejects any raw path containing a .. dot-segment (such as /api/sessions/../health, ../x, or percent-encoded ..%2F / %2e%2e, case-insensitively) before sending in all five SDKs, matching the check already applied to resource-id path segments.

Additive.

  • Per-recipient message delivery receipts: messages.receipts(sessionId, chatId, messageId) in JavaScript, Python, and PHP, messages.getReceipts(sessionId, chatId, messageId) in Java (MessageReceiptsResult with List<MessageRecipientReceipt>), and Messages.Receipts(ctx, sessionID, chatID, messageID) in Go (*MessageReceiptsResult with []MessageRecipientReceipt) call GET /api/sessions/{sessionId}/messages/{chatId}/{messageId}/receipts ({ messageId, chatId, receipts: [{ participantId, deliveredAt, readAt, playedAt }] }, Unix epoch seconds). Requires gateway v0.28.0 or later and a whatsapp-web.js session (Baileys answers 501).

Fixes.

  • Go: WithRetry now replays a POST on 503 only when the request context carries an Idempotency-Key (openwa.WithIdempotencyKey) or the 503 response carries a Retry-After header (which the gateway sends when a request is shed before execution by the in-flight body budget or an ingress preflight). An unkeyed POST that gets a 503 without Retry-After is no longer replayed automatically.
Migrating to SDK 0.9.0

Breaking (Go callers).

  • Contacts.Phone and Contacts.Lid nullable result fields. In Go, ContactPhoneResult.Phone is now *string instead of string (alongside the new ContactLidResult.Lid as *string) so a JSON null ({ "phone": null } when no mapping is known) is distinguishable from an empty string. Check for nil before dereferencing. The other four SDKs already represent null natively (string | null in TypeScript, Optional[str] in Python, ?string in PHP, nullable String in Java).

Additive.

  • Contact LID lookup: contacts.lid(sessionId, number) in JavaScript, Python, and PHP, contacts.getLid(sessionId, number) in Java (ContactLidResult), and Contacts.Lid(ctx, sessionID, number) in Go (*ContactLidResult) call GET /api/sessions/{sessionId}/contacts/{number}/lid and return { lid: string | null }. Requires gateway v0.27.1 or later.
  • Python: the raw escape hatch client.request(method, path, ..., idempotency_key=...) now accepts a keyword-only idempotency_key: Optional[str] = None argument that validates the key (1 to 255 visible ASCII characters) and sets the Idempotency-Key header.
What's new in SDK 0.8.0

Additive.

  • Group member label: groups.setMemberLabel(sessionId, groupId, label) (set_member_label in Python, Groups.SetMemberLabel in Go, groups->setMemberLabel in PHP, groups.setMemberLabel in Java) calls PUT /api/sessions/{sessionId}/groups/{groupId}/member-label with { label } to set or clear this account's own member label in a group (up to 30 UTF-16 code units; "" clears it). Requires gateway v0.27.0 or later and a Baileys session (whatsapp-web.js answers 501).
  • Search match mode: search.search accepts match ('word' or 'contains'; SearchMatch.WORD and SearchMatch.CONTAINS in Java, SearchQuery.Match as *string in Go) on gateway v0.27.0 or later. Java's SearchQuery keeps the 10-argument constructor from 0.7.0, defaulting match to null.
  • Custom link preview thumbnails: customLinkPreview on messages.sendText accepts thumbnailUrl and thumbnailBase64 (ThumbnailURL and ThumbnailBase64 in Go) on gateway v0.27.0 or later (Baileys only, up to 5 MiB). Java's CustomLinkPreview keeps the 3-argument (url, title, description) constructor.

Fixes.

  • Java: when a 2xx response body cannot be parsed as the expected JSON shape, OpenWAError now attaches the underlying Gson parse exception as its cause and reports Unexpected response body for <method> <path>.
  • PHP: addParticipants, removeParticipants, promoteParticipants, demoteParticipants, approveMembershipRequests and rejectMembershipRequests normalize the participant list with array_values so a list with non-consecutive keys (array_unique, array_filter) is encoded as a JSON array instead of an object.
  • PHP: raises a Guzzle TransferException when a 2xx response body ends before its declared Content-Length on the stream handler.
Migrating to SDK 0.7.0

Breaking.

  • Response types. The JavaScript and Python types mark the fields the gateway always sends as required and no longer allow the null it never sends. The wire is unchanged. In JavaScript, for example, ContactRecord.number, isMyContact and isBlocked, CheckNumberResponse.whatsappId (still string | null), SessionStatsOverview.memoryUsage and HealthResponse.timestamp are required, while ContactRecord.name, pushName and profilePicUrl and the catalog description and imageUrl are optional strings, not string | null. In Python, response TypedDicts such as ContactRecord, StatusRecord, CatalogProduct, ChannelRecord and LabelRecord require the always-sent keys and mark the others NotRequired. In Go the field types are unchanged, but several always-sent fields lose omitempty, so a response struct marshals them even at their zero value (ContactRecord.IsBlocked as false, CheckNumberResponse.WhatsappID as null). A hand-built record, a test double, or a null test on one of these fields needs updating. Java and PHP are unaffected.
  • ParticipantsResult. In JavaScript and Python it no longer extends SuccessResult: it declares success, message and results, all required, because the gateway always sends all three.
  • Key validation role. The role of the auth() result is the union 'admin' | 'operator' | 'viewer' in JavaScript and Python (a Literal in Python), where it was a plain string.
  • PHP defaultHeaders. A default header whose value is an empty list throws OpenWAException when the client is built, naming the header; 0.6.0 accepted it. Use '' for an empty header value. A value can still be text, a number, a boolean, null or a non-empty list.
  • Java. WebhookEvent gains MESSAGE_RECEIPT and POLL_VOTE, so a switch expression over it needs a branch for each new constant.

Additive.

  • message.receipt and poll.vote in the webhook event lists of the JavaScript, Python, Go (EventMessageReceipt, EventPollVote) and Java (MESSAGE_RECEIPT, POLL_VOTE) clients; PHP takes event strings. Both names need gateway v0.26.0 or later. '*' (WebhookEvent.ALL in Java, EventAll in Go) does not deliver message.receipt: name it. See the event table.
  • The PHP SDK installs with Guzzle 8 as well as Guzzle 7.9 and later.
  • Go status font constants carry the WhatsApp protocol's names: StatusFontSystemText (1), StatusFontFBScript (2), StatusFontMorningBreezeRegular (7), StatusFontCalistogaRegular (8), StatusFontExo2ExtraBold (9) and StatusFontCourierPrimeBold (10), beside StatusFontDefault (0) and StatusFontBold (6). The old names StatusFontSerif, StatusFontNorican, StatusFontOswald, StatusFontDamion, StatusFontMorningbreeze and StatusFontBryndan stay as deprecated aliases with the wire value they always had, so nothing breaks. They did not match the font each id selects; map them by id, because StatusFontMorningbreeze is 9 and StatusFontMorningBreezeRegular is 7. whatsapp-web.js honors fonts 0 to 7 and posts a higher id in the default font.
  • The inline docs name the engine that answers 501 for the catalog, channel, group creation, label, live history and reaction methods, as the resource table above does.

Fixes.

  • A raw request (request(), client.Do in Go) sends its method in upper case in JavaScript, Go and PHP, so a lowercase patch no longer reaches the gateway as written and answers 400. Query parameters added to a raw path that holds a #fragment go ahead of the fragment in JavaScript, Go, Java and PHP, where they were sent inside it, and Go sends the Idempotency-Key on a raw send path that carries a query or a fragment.
  • An oversized Retry-After no longer yields a wrong wait or a different error. JavaScript caps retryAfterSeconds at 2147483 (about 24.8 days), so retryAfterSeconds * 1000 is always a valid setTimeout delay; PHP caps at PHP_INT_MAX; Go reports the largest time.Duration (about 292 years), a stand-in for "do not retry". Python returns None instead of raising ValueError for a digit string past the interpreter's integer limit, and Java returns null instead of letting ArithmeticException replace the API error for a date out of range.
  • Python: API and timeout errors survive pickle and copy, so they cross a worker process boundary.
  • A final 1xx response from a custom transport is an error in Python, Go and PHP instead of a success.
  • Go: with WithRetry, a 429 that would be retried but whose body cannot be read to the end is no longer retried or reported as an API error; the read error comes back instead.
  • PHP: a typed call whose 2xx body is not JSON throws OpenWAException instead of a TypeError (the raw request() still returns the text), and the vars of sendTemplate and the variables of sendBulk go out as JSON objects, not lists, when the map has list-style keys (0.6.0 handled only an empty map), as does the options of sendBulk, empty or not.
  • PHP: on a host without ext-curl, a gateway that stays silent past timeout throws OpenWATimeoutException instead of a Guzzle exception, and responses are buffered even when an injected client sets stream to true, so a stalled body is a timeout too.
Migrating to SDK 0.6.0

Breaking.

  • Typed Python. CustomLinkPreview requires url and title, and WebhookFilterCondition requires field, operator and value, with operator narrowed to "is", "isNot", "contains" or "equals". A dict that leaves a required key out, or types the operator as a plain str, now fails type-checking. The wire body is unchanged.
  • Delivery-failure records. replayable is a required field of WebhookDeliveryFailure in the JavaScript and Python types, so a hand-built record or a test double needs it. Java keeps the earlier constructor, which sets it to false.
  • Java. WebhookEvent gains EVENT_RESPONSE, so a switch expression over it needs a branch for the new constant. The request timeout (default 30 s) also bounds the response body with the default transport, so a stalled body raises OpenWATimeoutError; raise it for large media downloads.
  • Client construction. JavaScript, Python, PHP and Go trim the API key, so a trailing newline from a secret file no longer fails. A control character left in the key is refused when the client is built in all five SDKs (JavaScript allows a tab inside the key), and so is a non-ASCII character in Python, PHP and Java or a non-Latin-1 character in JavaScript; the error never repeats the key. A default header value with a control or non-ASCII character (non-Latin-1 in JavaScript) is refused the same way in JavaScript, Python, PHP and Java, naming the header and not its value; JavaScript first trims spaces, tabs and line breaks at both ends of the value, as fetch does, so a value that ends in a newline builds there and is refused in Python, PHP and Java. Python, PHP and Java also refuse a default header name that is not a valid HTTP token. Go checks only the key.
  • Python timeout. None, 0 or infinity means no timeout, a four-value tuple takes the same for each element, an httpx.Timeout is passed to httpx as given, and a negative, NaN or non-number raises ValueError when the client is built.

Additive.

  • Stored-message filters on messages.list: since and until (epoch milliseconds), direction, type, messageId and orderBy, plus unknownTimestampTotal in the response. The JavaScript, Python, Java and Go clients declare them; PHP already forwarded any query key.
  • lastMessageType on chat summaries and the poll of a live history message (name, options, allowMultipleAnswers), in the JavaScript, Python, Java and Go types.
  • event.response in the webhook event lists of the JavaScript, Python, Java and Go clients; PHP takes event strings.
  • Webhook failure redrive: webhooks.redriveDeliveryFailures (redrive_delivery_failures in Python, Webhooks.RedriveDeliveryFailures in Go), and replayable on delivery-failure records.
  • Send idempotency keys. JavaScript, PHP and Java take an optional trailing idempotencyKey argument on the twelve single-recipient sends, Python a keyword-only idempotency_key; Go reads the key from the context with openwa.WithIdempotencyKey(ctx, key) and sends the header only on those twelve routes. A key outside 1-255 visible ASCII characters is refused before the request is sent.

Fixes.

  • Python: an error with an empty body names the response's status text instead of None.
  • JavaScript and PHP: printing or dumping a client no longer shows its API key, and the PHP client keeps its default header values out of a dump, an export and a cast as well.
  • Java: a connection failure names its exception class and keeps it as the cause instead of ending in null, a logged HttpRequestData shows neither the key nor the body, and the default transport speaks HTTP/1.1, so calls to a gateway over plain http:// no longer fail with HTTP/1.1 header parser received no bytes.
  • Go: an error answer from a proxy reads its own message or the status text.
  • PHP: an omitted participant list in approveMembershipRequests and rejectMembershipRequests goes out as {}, and an error body whose error is not a string maps to the SDK's exception instead of raising a TypeError.
  • Every SDK package ships the MIT license text.
Migrating to SDK 0.5.1

Type corrections.

  • cancelBatch returns BatchCancelResponse (batchId, status, progress), without the results array that only batchStatus returns.
  • Catalog info and product reads may return null when the gateway has no catalog or matching product. Handle that before reading fields.
  • Python's ChatSummary.timestamp is an integer in Unix seconds; its httpx dependency now requires 0.27.1 or newer. Java's readiness response uses DependencyStatus records.
  • In JavaScript and typed Python each health.ready() dependency is a { status } object (HealthDependencyStatus) instead of a string, and details is always present; code that compared a dependency to a string needs updating.
  • Go CatalogProduct.Price is *float64, Java CatalogProduct.price is Double, and JavaScript CatalogProduct.price, currency and priceFormatted are optional. Check for nil, null or undefined before reading.
  • webhooks.deliveryFailures returns []WebhookDeliveryFailure in Go and List<WebhookDeliveryFailure> in Java, where it returned any and Object.
  • Java SessionStatus, DeliveryStatus, BatchMessageStatus, BatchLifecycleStatus, PresenceState, AccountRestrictionKind, MemberAddMode and MembershipRequestMethod gain an UNKNOWN constant, so a switch expression over one of them needs a default or UNKNOWN branch. A response value newer than the SDK decodes to UNKNOWN instead of null for those eight and for MessageType and ChatKind, so a null test for an unrecognised value no longer matches. WebhookEvent, ProxyType and MessageDirection have no UNKNOWN constant and still decode such a value to null.

Other breaking changes.

  • Go Catalog.Info and Catalog.Product return nil without an error when there is no catalog or no such product, and Channels.Create, Channels.Delete, Channels.Mute, Chats.SubscribePresence, Groups.JoinInfo, Labels.Upsert and Labels.Delete return a nil result with an error instead of a zero-valued one.
  • A raw request (request(), client.Do in Go) refuses a path that does not begin with / in all five SDKs.
  • Java record types gained components without a constructor for the old shape: ListMessagesQuery (after, inlineMedia), ChatSummary (archived, pinned, muted, muteExpiration), ChatHistoryMessage (order, product) and AuthValidateResponse (engineType, scoped). A new call with the old argument list no longer compiles, so build message-list queries with ListMessagesQuery.builder() and update any hand-built response record or test double.

Available in 0.5.1.

  • All five clients expose session proxy reads and updates, button replies, session lookup by name, and message-list after / inlineMedia options.
  • API errors expose the response's code, response headers, and retry delay. All five SDKs add webhook signature verification helpers; the four typed clients also declare WebhookDelivery and delivery-failure records.
  • Raw requests preserve an existing path query when additional query parameters are supplied. Empty, . and .. resource ids are refused before sending.
Migrating to SDK 0.5.0

Breaking (Go, Java, TypeScript, and typed Python callers).

  • markRead and subscribePresence each take their own request type rather than the shared MarkChatRequest, which now serves markUnread alone. Go and Java swap in MarkChatReadRequest / SubscribePresenceRequest at both call sites (MarkChatRequest stays on markUnread); typed Python swaps at markRead only, its subscribePresence body being structurally identical. The wire body is unchanged; JavaScript and PHP are unaffected by this swap.
  • In Go and Java, fields that carried a closed set of strings or numbers are now named types (for example SessionResponse.Status is SessionStatus in Go, ChatSummary.kind is ChatKind in Java). A request field of such a type no longer accepts a bare string, int or String variable: SendChatStateRequest.State, CreateCallLinkRequest.Type, CreateSessionRequest.ProxyType, PinMessageRequest.DurationSeconds, SendTextStatusRequest.Font and BulkMessageItem.Type in Go, and CreateCallLinkRequest.type and CreateSessionRequest.proxyType in Java.
  • Go also changes ChatSummary.Name, GroupInfo.Description and GroupInfo.Owner to string instead of *string, ChatSummary.Timestamp to int64 instead of any, SessionResponse.EngineLoaded to bool instead of *bool, and BatchStatusResponse.StartedAt and CompletedAt to *string. Java ChatSummary.timestamp is a Long instead of an Object.
  • In TypeScript, WebhookFilterCondition.operator and the status font are literal unions, SessionResponse.engineLoaded is required, and GroupInfo.description no longer allows null. Also in TypeScript, BulkMessageResponse.estimatedCompletionTime and WebhookResponse.lastTriggeredAt are optional, BatchStatusResponse.startedAt and completedAt can be null, ChatHistoryMessage.type is the MessageType union, and the batch statuses are the BatchLifecycleStatus and BatchMessageStatus unions. Typed Python narrows the same kinds of fields to Literal types, for example BatchMessageStatus, BatchLifecycleStatus, ChatKind, PinDurationSeconds and StatusFont.

Additive.

  • markRead accepts an optional messageIds array (up to 100) naming which messages a read receipt covers; without it a burst on the Baileys engine leaves its earlier messages unread. Available in all five clients; ignored by whatsapp-web.js, whose read receipt is chat-level. In Go the field is a pointer so absent and empty stay distinct on the wire.
Migrating to SDK 0.4.0

Breaking.

  • catalog.sendCatalog is removed in all five SDKs. The gateway route it called answered 501 on every engine since it shipped and was removed in v0.19.0, so the method could never succeed. The four typed SDKs fail at compile or type-check time if you still call it; PHP fails at runtime with an undefined-method error. Nothing that ever worked stops working through this change: catalog reads and sendProduct are unchanged.
  • Go: UpdateWebhookRequest.Secret and .Headers and UpdateTemplateRequest.Header and .Footer are pointers (*string, *map[string]string), so pass the address of a variable; a nil field leaves the stored value unchanged. UpdateWebhookRequest also gains a ClearFilters flag.

Additive.

  • New routes exposed in all five clients: the channel administration routes (demote an admin, transfer ownership), the chat pin and mute routes, the call-link route, the blocked-contacts route, the group membership-request routes, and the account's own presence route.
  • quotedMessageId is exposed on the send request types in all five clients — every quotable send can now quote, including send-audio in Java, whose separate request record had been the one quotable route a Java caller could not quote on.

Fixes.

  • The JavaScript SDK now recognises the error envelope a production gateway sends ({ statusCode, message } without error), so its typed errors decode correctly in production and not only in development; the other four SDKs already did.
  • Python list returns are annotated with typing.List, and the chat-history fields the endpoint actually returns are declared — both are typing-accuracy corrections that can surface at type-check time.
  • Go: an empty participant list no longer acts on every join request, and the client can send the values that clear a field.
Migrating to SDK 0.3.0

Nothing on the wire changed in any of the items below — the gateway is untouched. What moved is what the SDKs declare they get back, and for four response shapes that declaration was simply wrong, so correcting it breaks source that read the old fields. Only the four typed SDKs — JavaScript, Python, Java, and Go — break at compile or type-check time; the PHP SDK hands back associative arrays, so it keeps running, but the field names below are still what you read out of them.

Breaking.

  • groups.create returns the group summary, { id, name, participantsCount?, isAdmin?, linkedParentJID? }. The SDKs declared the detail type groups.get returns, so participants, description, owner, and createdAt were typed as present on a response that never carries them. Call groups.get when you need the detail shape.
  • The four membership writes return ParticipantsResult, not { success, message } — addParticipants, removeParticipants, promoteParticipants, and demoteParticipants. It is a superset, so existing reads of success and message keep compiling, and it adds the per-participant results array. A partial refusal does not fail the batch: the request answers 200 and the rejected member is visible only in results, which the old type gave you no way to see.
  • ContactRecord.pushname is now pushName — the spelling both engines actually emit. Java's case-sensitive binder returned null for every contact under the old one.
  • ContactRecord.isBusiness is gone. The API never sent it, so it was always empty. The same type gained isBlocked and profilePicUrl.
  • catalog.sendProduct returns { id, timestamp }, not { messageId, … }. This one route answers id where every other send answers messageId, and the SDKs decoded the neighbouring field.

Additive.

  • The per-participant group result now carries message — the engine's reason for a participant it refused — alongside id, success, and status.
  • The send-product response now carries timestamp alongside id.
  • sessions.list now accepts limit and offset in the JavaScript, Python, PHP, and Java SDKs. GET /api/sessions has always taken them, but only the Go SDK exposed them; the other four sent a bare path and pinned you to the server default.

Install​

npm install @rmyndharis/openwa

The JavaScript SDK requires Node 18+ because it uses the global fetch. It ships both ESM and CommonJS builds with bundled type definitions, so it works in TypeScript and plain JavaScript without extra setup. On an older runtime, pass your own fetch to the constructor.

Hello world​

The flow is: instantiate the client → start a session → authenticate by scanning a QR code → send a message. Starting a session brings the WhatsApp connection up but does not log you in; the session reaches ready only after you scan its QR code from your phone.

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

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

// 1. Create the session. Keep the generated id — every later call takes the id,
// never the name.
const session = await client.sessions.create({ name: 'my-session' });

// 2. Start it and bring the WhatsApp connection up.
await client.sessions.start(session.id);

// 3. Fetch the QR code and scan it from WhatsApp on your phone
// (Settings → Linked devices → Link a device).
const { qrCode, status } = await client.sessions.getQrCode(session.id);
console.log(status, qrCode); // qrCode is a data:image/png;base64,… URL

// 4. Once the session status is 'ready', send a text message.
const result = await client.messages.sendText(session.id, {
chatId: '628123456789@c.us',
text: 'Hello from the OpenWA SDK!',
});

console.log(result.messageId);

sendText resolves to { messageId, timestamp }, where timestamp is a Unix epoch value in seconds:

{ "messageId": "3EB0XXXXXXXXXXXXXXXX", "timestamp": 1740000000 }

chatId is a WhatsApp JID: 628123456789@c.us for an individual contact and 123456789-123456789@g.us for a group. See the Glossary for the JID format.

The session must be ready before you send

start returns as soon as the engine is initializing — its status will be initializing or qr_ready, not ready. If you call sendText before scanning the QR code, the API returns 409 Conflict (the SDK throws OpenWAConflictError). Poll client.sessions.get(session.id) until status === 'ready', or wait for the webhook session event. See Sessions for the full lifecycle.

create needs an OPERATOR-level key. If the session already exists, read its id from client.sessions.list() or from the dashboard and skip straight to start, no session-scoped route accepts the name in place of the id in its path. Since gateway v0.23.5 a known name resolves to its id in one call: GET /api/sessions?name=my-session returns only the session whose name matches exactly (case-sensitive), and an empty array when nothing matches or the name falls outside the key's allowedSessions. SDK 0.5.1 and later expose it as client.sessions.list({ name: 'my-session' }). A key restricted to selected chats (allowedChats, v0.23.6+) cannot run this flow: create, start, getQrCode and list, with or without name, answer 403 for it. Of the sessions methods only get stays open to such a key, so take the session id from an unrestricted key or from the dashboard.

Python​

from openwa import OpenWAClient

with OpenWAClient(base_url="http://localhost:2785", api_key="YOUR_API_KEY") as client:
session = client.sessions.create({"name": "my-session"})

client.sessions.start(session["id"])

qr = client.sessions.get_qr_code(session["id"])
print(qr["status"], qr["qrCode"]) # scan from your phone

# After the session reaches 'ready':
result = client.messages.send_text(session["id"], {
"chatId": "628123456789@c.us",
"text": "Hello from the OpenWA Python SDK!",
})
print(result["messageId"])

The Python client is synchronous and returns plain dict/list values. It is also a context manager, so the connection pool is closed for you. On Python 3.9 the TypedDicts of openwa.types serve static type checkers only: typing.get_type_hints raises TypeError for those whose annotations use X | None or X | Y, which that version cannot evaluate.

PHP​

<?php
require 'vendor/autoload.php';

use OpenWA\Client;

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

// The session's id, not its name — from POST /sessions, or the dashboard.
$sessionId = '8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a';

$client->sessions->start($sessionId);

$qr = $client->sessions->getQrCode($sessionId);
echo $qr['status'], PHP_EOL; // scan $qr['qrCode'] from your phone

// After the session reaches 'ready':
$result = $client->messages->sendText($sessionId, [
'chatId' => '628123456789@c.us',
'text' => 'Hello from the OpenWA PHP SDK!',
]);

echo $result['messageId'];

The PHP entry class is OpenWA\Client; payloads are associative arrays.

Errors you will hit​

Every non-2xx response throws a typed error you can branch on. In JavaScript, all error classes extend OpenWAError and are exported, so they are instanceof-checkable; a timeout throws OpenWATimeoutError. In a multi-node deployment the forwarding layer answers 503 itself only when the session's owner node was never reached (v0.23.5+), so repeating that one cannot duplicate anything; an owner that did answer has its own status relayed back unchanged, 503 included. A forward that fails after the request was already sent answers 502, or 504 when the owner did not answer within SESSION_PROXY_TIMEOUT_MS. Both arrive as a plain OpenWAApiError, and the owner may already have carried the request out, so do not replay a non-idempotent send on them.

Error class (JS)StatusWhen it happens
OpenWAAuthError401Missing or invalid API key
OpenWAForbiddenError403The key's role is insufficient for an OPERATOR-only route, or the key is restricted to selected chats (v0.23.6+) and the route or the chat is outside that list, or the client IP or the session is outside the key's allowedIps or allowedSessions (v0.24.0+), or WhatsApp refused a well-formed operation (for example a group or channel write the account has no admin rights for); the error message says which
OpenWANotFoundError404Session, chat, or resource does not exist
OpenWAConflictError409Engine not ready, a send idempotency conflict, or a whatsapp-web.js page reload (code ENGINE_PAGE_RELOADING since v0.31.0); inspect code before retrying. A send cut short while it ran answers with no code and says it may or may not have been sent (v0.31.0+): check the chat before sending it again. See Handle errors
OpenWARateLimitError429Rate limited. A refusal by the gateway's rate limiter gives the seconds to wait in the Retry-After header (sent since v0.23.6). A send refused by send pacing carries no header; its body has code: "SEND_PACING_LIMITED" and the wait in retryAfterSeconds
OpenWANotImplementedError501The active engine does not support this operation; on whatsapp-web.js (v0.31.0+) also when the WhatsApp Web build the session runs has no job for a group, profile or message pin route. See Handle errors
OpenWAServiceUnavailableError503The gateway could not complete the request right now: it was refused before execution, WhatsApp did not confirm it, or, on Baileys, WhatsApp throttled it or timed it out. Back off before repeating; repeat safe operations, and for sends preserve the idempotency key or inspect the outcome first
OpenWATimeoutError—The request exceeded the 30-second timeout
import { OpenWAConflictError, OpenWAAuthError } from '@rmyndharis/openwa';

const sessionId = '8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a'; // the session's id, not its name

try {
await client.messages.sendText(sessionId, {
chatId: '628123456789@c.us',
text: 'Hi!',
});
} catch (err) {
if (err instanceof OpenWAConflictError) {
// 409 — engine not ready; start the session and scan its QR code first.
} else if (err instanceof OpenWAAuthError) {
// 401 — check your API key.
} else {
throw err;
}
}

The Python (OpenWAConflictError, …) and PHP (OpenWAConflictException, …) hierarchies mirror these one-to-one. Every Python error class is importable from the package root, including the newest one — from openwa import OpenWAServiceUnavailableError.

Send the API key over HTTPS in production

X-API-Key is bearer-equivalent, anyone holding it can act as you. Send it only over https:// outside local development. The SDK never follows redirects, so the key is never re-sent to a redirect target. The JavaScript, Python, PHP and Java SDKs do no automatic retries; wrap calls in your own backoff if you need them, especially for 429. The Go SDK retries only when built with WithRetry, and with DefaultRetryPolicy() it waits out a Retry-After, bounded by its per-request timeout. Since gateway v0.23.6 every 429 from the gateway's rate limiter carries a standard Retry-After header with the seconds to wait, which can be up to an hour when the default hourly window is the one exhausted. A send refused by send pacing is also a 429 but carries no Retry-After; its wait is retryAfterSeconds in err.body. SDK 0.5.1 and later expose err.retryAfterSeconds and err.headers alongside the status, body and error code (see SDK usage).

Next steps​

  • SDK usage — client configuration, sending media, custom transports, and request patterns
  • Sessions — the full session lifecycle and how to wait for ready
  • Sending messages — every message type and formatting
  • Webhooks — receive inbound messages and delivery events
  • API reference — the underlying REST endpoints the SDK wraps