Code Samples

Code samples for every use case

Copy-paste examples in JavaScript, Python, and cURL. Each sample uses real API endpoints and shows complete request and response handling.

SMS

SMS API samples

Send single messages, bulk campaigns, and handle delivery receipts with the Messages API.

Send single SMS

Send a single text message to one recipient with delivery tracking.

const response = await fetch("https://sakurasms.com/api/v1/messages", {
  method: "POST",
  headers: {
    "Authorization": "Bearer sk_live_your_api_key",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    to: "255712345678",
    sender: "MYBRAND",
    message: "Hi Amina, your order #4821 has been confirmed. Expected delivery: tomorrow by 3 PM.",
  }),
});

const message = await response.json();
console.log(message.id);     // cm3x9k2m1...
console.log(message.status); // "queued"

Send bulk SMS

Send the same or personalized messages to multiple recipients in a single API call.

// Pass every recipient in the "to" array -- one API call, one credit
// reservation, no separate batch endpoint needed.
const response = await fetch("https://sakurasms.com/api/v1/messages", {
  method: "POST",
  headers: {
    "Authorization": "Bearer sk_live_your_api_key",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    to: ["255712345678", "255754321098", "255688765432"],
    sender: "MYBRAND",
    message: "Flash sale starts now! 30% off all items. Shop: https://shop.example.com",
  }),
});

const batch = await response.json();
console.log(batch.id);       // cm3x9k2m1...
console.log(batch.to);       // ["255712345678", "255754321098", "255688765432"]
console.log(batch.cost);     // 3 (1 credit per recipient per segment)

Receive delivery receipt

Set up a webhook to receive real-time delivery status updates for every message.

// Express.js webhook handler for delivery receipts
import express from "express";

const app = express();
app.use(express.json());

app.post("/webhooks/dlr", (req, res) => {
  const { event, message_id, status, to, error_code } = req.body;

  console.log(`${event}: message ${message_id} to ${to} is ${status}`);
  // event: "message.sent" | "message.delivered" | "message.failed" | "campaign.completed"

  if (event === "message.failed") {
    console.log(`Error code: ${error_code}`);
    // Handle retry logic
  }

  res.status(200).json({ received: true });
});

app.listen(3000);
WhatsApp

WhatsApp API samples

Send template messages, media, and handle incoming webhooks with the WhatsApp Business API.

Send template message

Send a pre-approved WhatsApp template message with dynamic parameters.

const response = await fetch("https://sakurasms.com/api/v1/whatsapp/send", {
  method: "POST",
  headers: {
    "Authorization": "Bearer sk_live_your_api_key",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    to: "255712345678",
    template: "order_confirmation",
    language: "en",
    components: [
      {
        type: "body",
        parameters: [
          { type: "text", text: "Amina" },
          { type: "text", text: "#4821" },
          { type: "text", text: "January 16, 2026" },
        ],
      },
    ],
  }),
});

const message = await response.json();
console.log(message.messageId); // wamid.HBgL...

Send media message

Send images, documents, or videos via WhatsApp with optional captions.

// Media rides in the header of an approved template -- attach an image,
// video, or document alongside the templated text body.
const response = await fetch("https://sakurasms.com/api/v1/whatsapp/send", {
  method: "POST",
  headers: {
    "Authorization": "Bearer sk_live_your_api_key",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    to: "255712345678",
    template: "new_arrival_promo",
    language: "en",
    components: [
      {
        type: "header",
        parameters: [
          { type: "image", image: { link: "https://cdn.example.com/products/shoe-red.jpg" } },
        ],
      },
      {
        type: "body",
        parameters: [
          { type: "text", text: "Red sneakers" },
          { type: "text", text: "TZS 45,000" },
        ],
      },
    ],
  }),
});

const message = await response.json();
console.log(message.messageId); // wamid.HBgL...

Handle incoming webhook

Receive and process incoming WhatsApp messages from your customers.

// Express.js webhook handler for incoming WhatsApp messages
import express from "express";

const app = express();
app.use(express.json());

app.post("/webhooks/dlr", (req, res) => {
  const { event, message_id, status, to } = req.body;

  // Inbound customer replies land in your Sakura SMS dashboard inbox in
  // real time. This webhook covers outbound delivery status for messages
  // you sent -- useful for triggering follow-up flows on delivery/failure.
  console.log(`${event}: ${message_id} to ${to} is ${status}`);

  res.status(200).json({ received: true });
});

app.listen(3000);
OTP / Verify

OTP and verification samples

Request and validate one-time passwords with automatic channel fallback and fraud detection.

Request OTP

Generate and send a one-time password to a phone number via SMS, WhatsApp, or voice.

const response = await fetch("https://sakurasms.com/api/otp/request", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ msisdn: "255712345678" }),
});

const verification = await response.json();
console.log(verification.pinId);   // used in the check step below
console.log(verification.success); // true

Verify OTP

Validate the code entered by the user and confirm their identity.

const response = await fetch("https://sakurasms.com/api/otp/verify", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ pinId: "the-pinId-from-request-step", pin: "482910" }),
});

const result = await response.json();
console.log(result.valid); // true | false

if (result.valid) {
  // User verified successfully -- proceed with login / transaction
  console.log("Verification successful");
} else {
  console.log("Verification failed:", result.error);
}
Contacts

Contacts API samples

Manage your contact lists with tags, custom fields, and powerful filtering.

Create contact

Add a new contact to your address book with tags and custom fields.

// There is no separate contacts endpoint to call before sending -- add
// contacts from the dashboard (Contacts -> Add), or just pass phone numbers
// straight into the Messages API. Sakura SMS tracks delivery history per
// recipient automatically.
const response = await fetch("https://sakurasms.com/api/v1/messages", {
  method: "POST",
  headers: {
    "Authorization": "Bearer sk_live_your_api_key",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    to: "255712345678",
    sender: "MYBRAND",
    message: "Hi Amina, thanks for signing up! Save this number for order updates.",
  }),
});

const message = await response.json();
console.log(message.id); // cm3x9k2m1...

List contacts

Retrieve a paginated list of contacts with filtering and sorting options.

// Manage and segment your contact list from the dashboard (Contacts tab).
// From the API, list the messages you've sent -- each one carries the
// recipient number, cost, and delivery status.
const response = await fetch(
  "https://sakurasms.com/api/v1/messages?limit=25",
  { headers: { "Authorization": "Bearer sk_live_your_api_key" } }
);

const result = await response.json();
console.log(result.next_cursor); // pass as ?cursor= to page forward

for (const message of result.data) {
  console.log(`${message.id}: ${message.status} (${message.totalRecipients} recipients)`);
}

Ready to build? Get your API key

Create a free account and start sending messages in minutes. 100 free test messages included.