npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@zapyapi/sdk

v1.0.0-beta.13

Published

Official TypeScript SDK for ZapyAPI - WhatsApp API

Downloads

1,345

Readme

@zapyapi/sdk

npm version npm downloads License: MIT Node.js TypeScript

Official TypeScript SDK for ZapyAPI - REST API for WhatsApp integration.

Send messages, manage instances, and receive webhooks with a simple API. No infrastructure to manage.

Installation

npm install @zapyapi/sdk
# or
yarn add @zapyapi/sdk
# or
pnpm add @zapyapi/sdk

Quick Start

import { ZapyClient } from '@zapyapi/sdk';

// Initialize the client
const client = new ZapyClient({
  apiKey: 'your-api-key', // Get yours at https://app.zapyapi.com/
});

// Send a text message
const response = await client.messages.sendText('my-instance', {
  to: '5511999999999',
  text: 'Hello from ZapyAPI SDK!',
});

console.log(`Message sent with ID: ${response.messageId}`);

Features

  • Type-safe - Full TypeScript support with comprehensive types
  • Dual Format - ESM and CommonJS support out of the box
  • Modern - Works with Node.js 18+
  • Simple - Intuitive API design for great developer experience
  • Complete - Covers all ZapyAPI endpoints (instances, messages, webhooks)

API Reference

Client Initialization

import { ZapyClient, createClient } from '@zapyapi/sdk';

// Using constructor
const client = new ZapyClient({
  apiKey: 'your-api-key',
  baseUrl: 'https://api.zapyapi.com/api', // optional
  timeout: 30000, // optional, in milliseconds
});

// Using factory function
const client = createClient({ apiKey: 'your-api-key' });

Instances

// List all instances
const instances = await client.instances.list({ page: 1, limit: 10 });
console.log(`Total: ${instances.total} instances`);

// Create a new instance (Partner only)
const instance = await client.instances.create({
  name: 'My Instance',
  metadata: { department: 'sales' },
});

// Get QR code for connection
const qr = await client.instances.getQRCode('my-instance');
// qr.qrCode is a base64 encoded image

// Restart an instance
await client.instances.restart('my-instance');

// Logout from WhatsApp
await client.instances.logout('my-instance');

Messages

Send Text Message

const response = await client.messages.sendText('my-instance', {
  to: '5511999999999',
  text: 'Hello, World!',
  quotedMessageId: 'ABC123...', // optional, for replies
});

Send Image

// Using URL
await client.messages.sendImage('my-instance', {
  to: '5511999999999',
  url: 'https://example.com/image.jpg',
  caption: 'Check this out!', // optional
});

// Using Base64
await client.messages.sendImage('my-instance', {
  to: '5511999999999',
  base64: 'data:image/jpeg;base64,...',
  caption: 'Check this out!',
});

Send Video

await client.messages.sendVideo('my-instance', {
  to: '5511999999999',
  url: 'https://example.com/video.mp4',
  caption: 'Watch this!',
});

Send Audio Note (Voice Message)

await client.messages.sendAudioNote('my-instance', {
  to: '5511999999999',
  url: 'https://example.com/audio.ogg',
});

Send Document

await client.messages.sendDocument('my-instance', {
  to: '5511999999999',
  url: 'https://example.com/document.pdf',
  filename: 'report.pdf',
  caption: 'Here is the report',
});

Other Message Operations

// Forward a message
await client.messages.forward('my-instance', {
  to: '5511888888888',
  messageId: 'ABC123...',
});

// Edit a message
await client.messages.edit('my-instance', {
  messageId: 'ABC123...',
  text: 'Updated message text',
});

// Mark as read
await client.messages.markAsRead('my-instance', 'ABC123...');

// Delete a message
await client.messages.delete('my-instance', 'ABC123...');

// Get media download link
const media = await client.messages.getMediaDownloadLink('my-instance', 'ABC123...');
console.log(media.url);

Webhooks

// Configure webhook
await client.webhooks.configure({
  url: 'https://your-server.com/webhook',
  secret: 'your-secret-min-16-chars', // for HMAC-SHA256 verification
  isActive: true,
});

// Get current configuration
const config = await client.webhooks.getConfig();

// Check queue status
const status = await client.webhooks.getQueueStatus();
console.log(`Pending: ${status.pendingCount}, Failed: ${status.failedCount}`);

// Resume paused/failed webhooks
const result = await client.webhooks.resume();
console.log(`Resumed ${result.resumedCount} webhooks`);

// Delete webhook configuration
await client.webhooks.deleteConfig();

Error Handling

The SDK provides detailed error classes for different failure scenarios:

import {
  ZapyClient,
  ZapyApiError,
  AuthenticationError,
  RateLimitError,
  NetworkError,
  TimeoutError,
  ValidationError,
} from '@zapyapi/sdk';

try {
  await client.messages.sendText('my-instance', {
    to: '5511999999999',
    text: 'Hello!',
  });
} catch (error) {
  if (error instanceof TimeoutError) {
    // Request timed out
    console.error(`Request timed out after ${error.timeout}ms`);
    console.error(`Request: ${error.method} ${error.url}`);
  } else if (error instanceof NetworkError) {
    // Network failure (no response received)
    console.error(`Network error: ${error.message}`);
    console.error(`Error code: ${error.code}`); // e.g., ECONNREFUSED
  } else if (error instanceof AuthenticationError) {
    console.error('Invalid API key');
  } else if (error instanceof RateLimitError) {
    console.error(`Rate limited. Retry after: ${error.retryAfter}ms`);
    console.error(`Retry at: ${error.getRetryAfterDate()}`);
  } else if (error instanceof ZapyApiError) {
    console.error(`API Error [${error.code}]: ${error.message}`);
    console.error(`Status: ${error.statusCode}`);
    console.error(`Request ID: ${error.requestId}`);
    console.error(`Request: ${error.method} ${error.url}`);

    // For debugging/logging
    console.error(error.toDetailedString());
    // Or serialize to JSON
    console.error(JSON.stringify(error.toJSON(), null, 2));
  }
}

Error Classes

| Error Class | Description | |-------------|-------------| | ZapyError | Base error class for all SDK errors | | ZapyApiError | API returned an error response (4xx, 5xx) | | AuthenticationError | Invalid or missing API key (401) | | RateLimitError | Rate limit exceeded (429) | | NetworkError | Network failure, no response received | | TimeoutError | Request timed out | | ValidationError | Input validation failed | | InstanceNotFoundError | Instance not found (404) |

Utilities

import { normalizePhone, isValidPhone, isGroup, extractPhone } from '@zapyapi/sdk';

// Normalize phone numbers
normalizePhone('11999999999'); // '5511999999999'
normalizePhone('+5511999999999'); // '5511999999999'

// Validate phone numbers
isValidPhone('5511999999999'); // true
isValidPhone('[email protected]'); // true

// Check if JID is a group
isGroup('[email protected]'); // true
isGroup('[email protected]'); // false

// Extract phone from JID
extractPhone('[email protected]'); // '5511999999999'

Webhook Event Types

The SDK provides fully typed webhook events with discriminated unions for each message type:

import {
  ZapyWebhookPayload,
  ZapyEventTypes,
  isTextMessage,
  isImageMessage,
  isVideoMessage,
  isAudioMessage,
} from '@zapyapi/sdk';

function handleWebhook(payload: ZapyWebhookPayload) {
  console.log(`Event from instance: ${payload.instanceId}`);

  switch (payload.event) {
    case ZapyEventTypes.MESSAGE:
      // payload.data is ZapyMessage (discriminated union)
      const message = payload.data;

      if (isTextMessage(message)) {
        console.log(`Text: ${message.text}`);
      } else if (isImageMessage(message)) {
        console.log(`Image: ${message.url}, caption: ${message.caption}`);
      } else if (isVideoMessage(message)) {
        console.log(`Video: ${message.url}`);
      } else if (isAudioMessage(message)) {
        console.log(`Audio: ${message.url}, duration: ${message.duration}s`);
      }
      break;

    case ZapyEventTypes.MESSAGE_STATUS:
      console.log(`Message ${payload.data.messageId} status: ${payload.data.status}`);
      break;

    case ZapyEventTypes.QR_CODE:
      console.log(`QR Code received, attempt: ${payload.data.attempt}`);
      break;

    case ZapyEventTypes.INSTANCE_STATUS:
      console.log(`Instance status: ${payload.data.status}`);
      break;
  }
}

Available Message Type Guards

import {
  isTextMessage,
  isImageMessage,
  isVideoMessage,
  isAudioMessage,
  isDocumentMessage,
  isStickerMessage,
  isLocationMessage,
  isContactMessage,
  isReactionMessage,
  isPollMessage,
  isMediaMessage, // matches any media type
} from '@zapyapi/sdk';

Requirements

  • Node.js 18 or higher
  • TypeScript 5.0+ (for TypeScript users)

CommonJS Usage

The SDK also works with CommonJS:

const { ZapyClient } = require('@zapyapi/sdk');

const client = new ZapyClient({ apiKey: 'your-api-key' });

Low-Level REST API Client

For advanced use cases, the SDK also exports an auto-generated REST client with full type definitions from the OpenAPI spec:

import { ZapyRestApi } from '@zapyapi/sdk';

const api = new ZapyRestApi({
  baseURL: 'https://api.zapyapi.com',
  headers: {
    'x-api-key': 'your-api-key',
  },
});

// Direct REST calls with full type safety
const response = await api.instances.managerInstancesControllerListInstances({
  page: 1,
  limit: 10,
});

// Send a message
await api.sendMessage.sendMessageControllerSendTextMessage(
  'my-instance',
  { to: '5511999999999', text: 'Hello!' }
);

License

MIT

Links

Support


Made with :heart: by ZapyAPI