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.
- A running OpenWA gateway. See Installation — the examples assume the local default
http://localhost:2785. - An API key sent as the
X-API-Keyheader. 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.
| Language | Package | Install | Requires |
|---|---|---|---|
| JavaScript / TypeScript | @rmyndharis/openwa | npm install @rmyndharis/openwa | Node 18+ |
| Python | rmyndharis-openwa (imports as openwa) | pip install rmyndharis-openwa | Python 3.9+ |
| PHP | rmyndharis/openwa | composer require rmyndharis/openwa | PHP 8.1+, Guzzle 7.9+ or 8.x |
| Java | com.rmyndharis:openwa | Maven / Gradle (see below) | Java 17+ |
| Go | github.com/rmyndharis/OpenWA/sdk/go | go get github.com/rmyndharis/OpenWA/sdk/go | Go 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.
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.
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.
| Resource | What it does |
|---|---|
sessions | List, 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 |
messages | Send 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) |
contacts | Look up contacts, check numbers, resolve phone numbers and Linked Identities (lid / getLid / Lid, v0.27.1+), block / unblock |
groups | Create groups (Baileys only: whatsapp-web.js answers 501), manage participants, set subject / description / own member label (setMemberLabel, Baileys only, v0.27.0+), invite codes |
webhooks | Configure event delivery to your own HTTP endpoints; list webhooks across every session, read the delivery-failure log, and redrive retained failures |
chats | List 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+) |
templates | Manage reusable message templates |
labels | WhatsApp Business labels; reading them (list, get, chats, forChat) is whatsapp-web.js only: Baileys answers 501 |
channels | WhatsApp 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 |
catalog | WhatsApp Business product catalog (Baileys only: whatsapp-web.js answers 501) |
status | WhatsApp Status / stories |
search | Search messages and chats (word-prefix or match=contains substring search on gateway v0.27.0+) |
profile | Set the linked account's display name, status text, and profile picture |
calls | Reject an incoming call (Baileys only: whatsapp-web.js answers 501 since v0.23.6), create a shareable call link (v0.16.0+) |
media | Server-side conversion into the formats WhatsApp plays, plus a check for whether it is available |
health | Liveness / 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.
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.
Breaking (Python callers).
- Call link
startTime.CreateCallLinkRequest.startTimeisintinstead offloat, so a float, such astime.time() * 1000, now fails type-checking. The wire is unchanged: the gateway refuses a fraction with400. The PHP docblock narrowsstartTimetointas well. In JavaScript, Go and Java the type is unchanged and the field comments say a whole number.
Additive.
- Chat
phone:ChatSummary.phonecarries the phone digits of a Baileys chat held under a privacy id (@lid) when the session can map it, asphone?: stringin JavaScript,NotRequired[str]in Python,Phone string(omitted when empty) in Go andString phonein Java; PHP returns it in the decoded array. whatsapp-web.js lists nophone. A Baileys privacy-id chat with no name of its own listsnameas"", so title it byphone, else byid. Requires gateway v0.31.0 or later. Java'sChatSummarykeeps its earlier 11- and 12-argument constructors, which leavephonenull. - Webhook secret:
UpdateWebhookRequest.secretacceptsnullin the JavaScript (string | null) and Python (str | None) types. The gateway clears the stored secret fornullas it does for"". In Go and Java clear it with the empty string: a nilSecretin Go and a nullsecret(...)in Java are left out of the request.
Fixes.
- PHP: the list fields
mentions(text, media, template, reply and edit sends, and bulk items), polloptions(sendPollandvotePoll), statusrecipients, webhookeventsandfilters(theconditionslist and a condition's listvalue), theidsofredriveDeliveryFailuresand themessageIdsofchats->markReadare sent as JSON arrays when their keys have gaps (array_filter,array_unique), which the gateway refused with400. Groupparticipantsand the bulkmessageslist were already re-indexed. A body passed to the rawrequest()is sent as given, so pass its lists througharray_values(). - Python: the source distribution ships
tests/conftest.py, so the tests run from the unpacked archive.
Fixes.
- PHP: an empty request body is sent as
{}instead of[], which the gateway refused with400on config, proxy, webhook and template updates. It applies to every call whose body is empty, the rawrequest()included, and not to an empty list nested inside a body. - Java: an
OpenWAApiErrorwith a JSON body can be Java-serialized, where it threwNotSerializableExceptionfor the Gson body; the body reads back as the same JSON.
Breaking (JavaScript and Python callers).
SessionConfigrequireslinkPreview. The JavaScript and Python types declarelinkPreview(boolean | null,bool | None) as a required field of the config read, so a hand-builtSessionConfigor a test double needs it. A gateway older than v0.30.3 does not send the key, so Python'sconfig["linkPreview"]raisesKeyErrorand JavaScript readsundefinedagainst one.
Additive.
- Session config
linkPreview:sessions.getConfigandsessions.updateConfigread and write the default link preview of asend-textorsend-templatethat sets neitherlinkPreviewnorcustomLinkPreview. It islinkPreviewonSessionConfigandUpdateSessionConfigRequestin JavaScript (boolean | null) and Python (bool | None),LinkPreview *boolwith aClearLinkPreviewflag in Go, and alinkPreviewcomponent on Java'sSessionConfigandUpdateSessionConfigRequest, withlinkPreview(Boolean)andclearLinkPreview()on the request builder; PHP takes the key in the body array.nullrestores the engine's default. Requires gateway v0.30.3 or later. Java'sSessionConfigandUpdateSessionConfigRequestkeep their earlier 3- and 6-argument constructors, which leavelinkPreviewunset.
Breaking (Java callers).
AccountRestrictionKindgainsPASSKEY_REQUIRED. In Java,AccountRestrictionKindadds@SerializedName("passkey_required") PASSKEY_REQUIRED, so aswitchexpression over it without adefaultbranch must handle the new constant.ChatHistoryMessagealso addsBoolean isForwardedandLong forwardingScoreto its record components while keeping a 26-argument compatibility constructor that preserves the 0.10.0 signature.
Additive.
- Passkey restriction kind:
AccountRestrictionKindincludes'passkey_required'in JavaScript and Python,RestrictionPasskeyRequired("passkey_required") in Go, andPASSKEY_REQUIREDin Java, matching gateway v0.30.0 (restrictiononGET /api/sessions/{sessionId},GET /api/sessions,POST /api/sessions/{sessionId}/start, andsession.restrictionwebhook payloads when WhatsApp requests a passkey during Baileys linking). - Forwarded live-history metadata:
ChatHistoryMessagedeclares optionalisForwardedandforwardingScorein JavaScript (isForwarded?: boolean; forwardingScore?: number), Python (NotRequired[bool]/NotRequired[int]), Go (IsForwarded bool,ForwardingScore int64), and Java (Boolean isForwarded,Long forwardingScore), matchingGET /api/sessions/{sessionId}/messages/{chatId}/historysince gateway v0.29.1.
Breaking.
- Raw request path validation.
request()(client.Doin 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 (MessageReceiptsResultwithList<MessageRecipientReceipt>), andMessages.Receipts(ctx, sessionID, chatID, messageID)in Go (*MessageReceiptsResultwith[]MessageRecipientReceipt) callGET /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 awhatsapp-web.jssession (Baileys answers501).
Fixes.
- Go:
WithRetrynow replays aPOSTon503only when the request context carries anIdempotency-Key(openwa.WithIdempotencyKey) or the503response carries aRetry-Afterheader (which the gateway sends when a request is shed before execution by the in-flight body budget or an ingress preflight). An unkeyedPOSTthat gets a503withoutRetry-Afteris no longer replayed automatically.
Breaking (Go callers).
Contacts.PhoneandContacts.Lidnullable result fields. In Go,ContactPhoneResult.Phoneis now*stringinstead ofstring(alongside the newContactLidResult.Lidas*string) so a JSONnull({ "phone": null }when no mapping is known) is distinguishable from an empty string. Check fornilbefore dereferencing. The other four SDKs already representnullnatively (string | nullin TypeScript,Optional[str]in Python,?stringin PHP, nullableStringin Java).
Additive.
- Contact LID lookup:
contacts.lid(sessionId, number)in JavaScript, Python, and PHP,contacts.getLid(sessionId, number)in Java (ContactLidResult), andContacts.Lid(ctx, sessionID, number)in Go (*ContactLidResult) callGET /api/sessions/{sessionId}/contacts/{number}/lidand 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-onlyidempotency_key: Optional[str] = Noneargument that validates the key (1 to 255 visible ASCII characters) and sets theIdempotency-Keyheader.
Additive.
- Group member label:
groups.setMemberLabel(sessionId, groupId, label)(set_member_labelin Python,Groups.SetMemberLabelin Go,groups->setMemberLabelin PHP,groups.setMemberLabelin Java) callsPUT /api/sessions/{sessionId}/groups/{groupId}/member-labelwith{ 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.jsanswers501). - Search match mode:
search.searchacceptsmatch('word'or'contains';SearchMatch.WORDandSearchMatch.CONTAINSin Java,SearchQuery.Matchas*stringin Go) on gateway v0.27.0 or later. Java'sSearchQuerykeeps the 10-argument constructor from 0.7.0, defaultingmatchtonull. - Custom link preview thumbnails:
customLinkPreviewonmessages.sendTextacceptsthumbnailUrlandthumbnailBase64(ThumbnailURLandThumbnailBase64in Go) on gateway v0.27.0 or later (Baileys only, up to 5 MiB). Java'sCustomLinkPreviewkeeps the 3-argument(url, title, description)constructor.
Fixes.
- Java: when a
2xxresponse body cannot be parsed as the expected JSON shape,OpenWAErrornow attaches the underlying Gson parse exception as its cause and reportsUnexpected response body for <method> <path>. - PHP:
addParticipants,removeParticipants,promoteParticipants,demoteParticipants,approveMembershipRequestsandrejectMembershipRequestsnormalize the participant list witharray_valuesso a list with non-consecutive keys (array_unique,array_filter) is encoded as a JSON array instead of an object. - PHP: raises a Guzzle
TransferExceptionwhen a2xxresponse body ends before its declaredContent-Lengthon the stream handler.
Breaking.
- Response types. The JavaScript and Python types mark the fields the gateway always sends as required and no longer allow the
nullit never sends. The wire is unchanged. In JavaScript, for example,ContactRecord.number,isMyContactandisBlocked,CheckNumberResponse.whatsappId(stillstring | null),SessionStatsOverview.memoryUsageandHealthResponse.timestampare required, whileContactRecord.name,pushNameandprofilePicUrland the catalogdescriptionandimageUrlare optional strings, notstring | null. In Python, responseTypedDicts such asContactRecord,StatusRecord,CatalogProduct,ChannelRecordandLabelRecordrequire the always-sent keys and mark the othersNotRequired. In Go the field types are unchanged, but several always-sent fields loseomitempty, so a response struct marshals them even at their zero value (ContactRecord.IsBlockedasfalse,CheckNumberResponse.WhatsappIDasnull). A hand-built record, a test double, or anulltest on one of these fields needs updating. Java and PHP are unaffected. ParticipantsResult. In JavaScript and Python it no longer extendsSuccessResult: it declaressuccess,messageandresults, all required, because the gateway always sends all three.- Key validation role. The
roleof theauth()result is the union'admin' | 'operator' | 'viewer'in JavaScript and Python (aLiteralin Python), where it was a plain string. - PHP
defaultHeaders. A default header whose value is an empty list throwsOpenWAExceptionwhen 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,nullor a non-empty list. - Java.
WebhookEventgainsMESSAGE_RECEIPTandPOLL_VOTE, so aswitchexpression over it needs a branch for each new constant.
Additive.
message.receiptandpoll.votein 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.ALLin Java,EventAllin Go) does not delivermessage.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) andStatusFontCourierPrimeBold(10), besideStatusFontDefault(0) andStatusFontBold(6). The old namesStatusFontSerif,StatusFontNorican,StatusFontOswald,StatusFontDamion,StatusFontMorningbreezeandStatusFontBryndanstay 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, becauseStatusFontMorningbreezeis 9 andStatusFontMorningBreezeRegularis 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
501for the catalog, channel, group creation, label, live history and reaction methods, as the resource table above does.
Fixes.
- A raw request (
request(),client.Doin Go) sends its method in upper case in JavaScript, Go and PHP, so a lowercasepatchno longer reaches the gateway as written and answers400. Query parameters added to a raw path that holds a#fragmentgo ahead of the fragment in JavaScript, Go, Java and PHP, where they were sent inside it, and Go sends theIdempotency-Keyon a raw send path that carries a query or a fragment. - An oversized
Retry-Afterno longer yields a wrong wait or a different error. JavaScript capsretryAfterSecondsat 2147483 (about 24.8 days), soretryAfterSeconds * 1000is always a validsetTimeoutdelay; PHP caps atPHP_INT_MAX; Go reports the largesttime.Duration(about 292 years), a stand-in for "do not retry". Python returnsNoneinstead of raisingValueErrorfor a digit string past the interpreter's integer limit, and Java returnsnullinstead of lettingArithmeticExceptionreplace the API error for a date out of range. - Python: API and timeout errors survive
pickleandcopy, so they cross a worker process boundary. - A final
1xxresponse from a custom transport is an error in Python, Go and PHP instead of a success. - Go: with
WithRetry, a429that 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
2xxbody is not JSON throwsOpenWAExceptioninstead of aTypeError(the rawrequest()still returns the text), and thevarsofsendTemplateand thevariablesofsendBulkgo out as JSON objects, not lists, when the map has list-style keys (0.6.0 handled only an empty map), as does theoptionsofsendBulk, empty or not. - PHP: on a host without ext-curl, a gateway that stays silent past
timeoutthrowsOpenWATimeoutExceptioninstead of a Guzzle exception, and responses are buffered even when an injected client setsstreamtotrue, so a stalled body is a timeout too.
Breaking.
- Typed Python.
CustomLinkPreviewrequiresurlandtitle, andWebhookFilterConditionrequiresfield,operatorandvalue, withoperatornarrowed to"is","isNot","contains"or"equals". A dict that leaves a required key out, or types the operator as a plainstr, now fails type-checking. The wire body is unchanged. - Delivery-failure records.
replayableis a required field ofWebhookDeliveryFailurein the JavaScript and Python types, so a hand-built record or a test double needs it. Java keeps the earlier constructor, which sets it tofalse. - Java.
WebhookEventgainsEVENT_RESPONSE, so aswitchexpression 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 raisesOpenWATimeoutError; 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,0or infinity means no timeout, a four-value tuple takes the same for each element, anhttpx.Timeoutis passed to httpx as given, and a negative, NaN or non-number raisesValueErrorwhen the client is built.
Additive.
- Stored-message filters on
messages.list:sinceanduntil(epoch milliseconds),direction,type,messageIdandorderBy, plusunknownTimestampTotalin the response. The JavaScript, Python, Java and Go clients declare them; PHP already forwarded any query key. lastMessageTypeon chat summaries and the poll of a live history message (name,options,allowMultipleAnswers), in the JavaScript, Python, Java and Go types.event.responsein the webhook event lists of the JavaScript, Python, Java and Go clients; PHP takes event strings.- Webhook failure redrive:
webhooks.redriveDeliveryFailures(redrive_delivery_failuresin Python,Webhooks.RedriveDeliveryFailuresin Go), andreplayableon delivery-failure records. - Send idempotency keys. JavaScript, PHP and Java take an optional trailing
idempotencyKeyargument on the twelve single-recipient sends, Python a keyword-onlyidempotency_key; Go reads the key from the context withopenwa.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 loggedHttpRequestDatashows neither the key nor the body, and the default transport speaks HTTP/1.1, so calls to a gateway over plainhttp://no longer fail withHTTP/1.1 header parser received no bytes. - Go: an error answer from a proxy reads its own
messageor the status text. - PHP: an omitted participant list in
approveMembershipRequestsandrejectMembershipRequestsgoes out as{}, and an error body whoseerroris not a string maps to the SDK's exception instead of raising aTypeError. - Every SDK package ships the MIT license text.
Type corrections.
cancelBatchreturnsBatchCancelResponse(batchId,status,progress), without theresultsarray that onlybatchStatusreturns.- Catalog info and product reads may return
nullwhen the gateway has no catalog or matching product. Handle that before reading fields. - Python's
ChatSummary.timestampis an integer in Unix seconds; its httpx dependency now requires 0.27.1 or newer. Java's readiness response usesDependencyStatusrecords. - In JavaScript and typed Python each
health.ready()dependency is a{ status }object (HealthDependencyStatus) instead of a string, anddetailsis always present; code that compared a dependency to a string needs updating. - Go
CatalogProduct.Priceis*float64, JavaCatalogProduct.priceisDouble, and JavaScriptCatalogProduct.price,currencyandpriceFormattedare optional. Check for nil,nullorundefinedbefore reading. webhooks.deliveryFailuresreturns[]WebhookDeliveryFailurein Go andList<WebhookDeliveryFailure>in Java, where it returnedanyandObject.- Java
SessionStatus,DeliveryStatus,BatchMessageStatus,BatchLifecycleStatus,PresenceState,AccountRestrictionKind,MemberAddModeandMembershipRequestMethodgain anUNKNOWNconstant, so aswitchexpression over one of them needs adefaultorUNKNOWNbranch. A response value newer than the SDK decodes toUNKNOWNinstead ofnullfor those eight and forMessageTypeandChatKind, so anulltest for an unrecognised value no longer matches.WebhookEvent,ProxyTypeandMessageDirectionhave noUNKNOWNconstant and still decode such a value tonull.
Other breaking changes.
- Go
Catalog.InfoandCatalog.Productreturnnilwithout an error when there is no catalog or no such product, andChannels.Create,Channels.Delete,Channels.Mute,Chats.SubscribePresence,Groups.JoinInfo,Labels.UpsertandLabels.Deletereturn a nil result with an error instead of a zero-valued one. - A raw request (
request(),client.Doin 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) andAuthValidateResponse(engineType,scoped). Anewcall with the old argument list no longer compiles, so build message-list queries withListMessagesQuery.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-listafter/inlineMediaoptions. - 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 declareWebhookDeliveryand delivery-failure records. - Raw requests preserve an existing path query when additional query parameters are supplied. Empty,
.and..resource ids are refused before sending.
Breaking (Go, Java, TypeScript, and typed Python callers).
markReadandsubscribePresenceeach take their own request type rather than the sharedMarkChatRequest, which now servesmarkUnreadalone. Go and Java swap inMarkChatReadRequest/SubscribePresenceRequestat both call sites (MarkChatRequeststays onmarkUnread); typed Python swaps atmarkReadonly, itssubscribePresencebody 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.StatusisSessionStatusin Go,ChatSummary.kindisChatKindin Java). A request field of such a type no longer accepts a barestring,intorStringvariable:SendChatStateRequest.State,CreateCallLinkRequest.Type,CreateSessionRequest.ProxyType,PinMessageRequest.DurationSeconds,SendTextStatusRequest.FontandBulkMessageItem.Typein Go, andCreateCallLinkRequest.typeandCreateSessionRequest.proxyTypein Java. - Go also changes
ChatSummary.Name,GroupInfo.DescriptionandGroupInfo.Ownertostringinstead of*string,ChatSummary.Timestamptoint64instead ofany,SessionResponse.EngineLoadedtoboolinstead of*bool, andBatchStatusResponse.StartedAtandCompletedAtto*string. JavaChatSummary.timestampis aLonginstead of anObject. - In TypeScript,
WebhookFilterCondition.operatorand the statusfontare literal unions,SessionResponse.engineLoadedis required, andGroupInfo.descriptionno longer allowsnull. Also in TypeScript,BulkMessageResponse.estimatedCompletionTimeandWebhookResponse.lastTriggeredAtare optional,BatchStatusResponse.startedAtandcompletedAtcan benull,ChatHistoryMessage.typeis theMessageTypeunion, and the batch statuses are theBatchLifecycleStatusandBatchMessageStatusunions. Typed Python narrows the same kinds of fields toLiteraltypes, for exampleBatchMessageStatus,BatchLifecycleStatus,ChatKind,PinDurationSecondsandStatusFont.
Additive.
markReadaccepts an optionalmessageIdsarray (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.
Breaking.
catalog.sendCatalogis removed in all five SDKs. The gateway route it called answered501on 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:catalogreads andsendProductare unchanged.- Go:
UpdateWebhookRequest.Secretand.HeadersandUpdateTemplateRequest.Headerand.Footerare pointers (*string,*map[string]string), so pass the address of a variable; a nil field leaves the stored value unchanged.UpdateWebhookRequestalso gains aClearFiltersflag.
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.
quotedMessageIdis 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 }withouterror), 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.
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.createreturns the group summary,{ id, name, participantsCount?, isAdmin?, linkedParentJID? }. The SDKs declared the detail typegroups.getreturns, soparticipants,description,owner, andcreatedAtwere typed as present on a response that never carries them. Callgroups.getwhen you need the detail shape.- The four membership writes return
ParticipantsResult, not{ success, message }—addParticipants,removeParticipants,promoteParticipants, anddemoteParticipants. It is a superset, so existing reads ofsuccessandmessagekeep compiling, and it adds the per-participantresultsarray. A partial refusal does not fail the batch: the request answers200and the rejected member is visible only inresults, which the old type gave you no way to see. ContactRecord.pushnameis nowpushName— the spelling both engines actually emit. Java's case-sensitive binder returnednullfor every contact under the old one.ContactRecord.isBusinessis gone. The API never sent it, so it was always empty. The same type gainedisBlockedandprofilePicUrl.catalog.sendProductreturns{ id, timestamp }, not{ messageId, … }. This one route answersidwhere every other send answersmessageId, 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 — alongsideid,success, andstatus. - The
send-productresponse now carriestimestampalongsideid. sessions.listnow acceptslimitandoffsetin the JavaScript, Python, PHP, and Java SDKs.GET /api/sessionshas 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.
ready before you sendstart 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) | Status | When it happens |
|---|---|---|
OpenWAAuthError | 401 | Missing or invalid API key |
OpenWAForbiddenError | 403 | The 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 |
OpenWANotFoundError | 404 | Session, chat, or resource does not exist |
OpenWAConflictError | 409 | Engine 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 |
OpenWARateLimitError | 429 | Rate 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 |
OpenWANotImplementedError | 501 | The 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 |
OpenWAServiceUnavailableError | 503 | The 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.
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