Skip to main content

DevStack

Your First Message and Call Using Bandwidth’s APIs and Node.js

Samantha Capps Samantha Capps
Samantha Capps
Share

Bandwidth has a full suite of messaging API solutions to power your business’ needs. Whether you want to send messages from toll-free numbers, local numbers, or short codes, Bandwidth’s APIs make it easy to enable in your software or platform, while Bandwidth’s relationships with the carriers give you reliable message delivery and insights. 

Introduction

In this article, you will see a quick overview of what sending your first message and creating your first call looks like when using Bandwidth’s Voice and Messaging APIs along with Bandwidth’s Node SDK. First you will see some code examples and then at the end of this article is an explanation of the variables you would need to insert into the code to make the SDK work with your Bandwidth account.

Packages and Client Initialization

First you need to install the packages needed for this example like this.

npm install @bandwidth/voice @bandwidth/messaging @bandwidth/bxml express body-parser

You then need to require the SDK in your code and initialize the configuration for the SDK clients.

The Messaging client looks like this.

const BandwidthMessaging = require("@bandwidth/messaging");
BandwidthMessaging.Configuration.basicAuthUserName = "{username}";
BandwidthMessaging.Configuration.basicAuthPassword = "{password}";
const messagingController = BandwidthMessaging.APIController;

The Voice client looks like this.

const BandwidthVoice = require("@bandwidth/voice");
BandwidthVoice.Configuration.basicAuthUserName = "{username}";
BandwidthVoice.Configuration.basicAuthPassword = "{password}";
const voiceController = BandwidthVoice.APIController;

Messaging How To

Sending a message from a Bandwidth number looks like this. This must be in the same file as your initiated Messaging client or the client must be imported here.

var messagingBody = new BandwidthMessaging.MessageRequest({
        "applicationId" : "{app_id}",
        "to" : ["{to}"],
        "from" : "{from}",
        "text" : "Hello, I am sending a message! How fun!",
    });

messagingController.createMessage("{accountId}", messagingBody);

You will need to set up a server that can receive a callback/webhooks with a JSON body that will tell you if the message was successfully delivered or not. Some simple Node server code using sinatra that can process Bandwidth messaging callbacks could look like this (note that you can provide a specific port number to app.listen() to have the server listen on that port).

const express = require("express");
const bodyParser = require("body-parser");

const app = express();

app.use(bodyParser.json());

app.post("/messaging", function(req, res) {
    if (req.body[0]["type"] == "message-delivered"){
        //successful delivery action
        res.status(200).end();
    } else if (req.body[0]["type"] == "message-failed"){
        var failure_reason = req.body[0]["description"];
        //failed delivery action
        res.status(200).end();
    } else {
       res.status(200).end();
    }
});

app.listen();

Voice How To

Creating a call from a Bandwidth number looks like this. This must be in the same file as your initiated client or the client must be imported here.

var voiceBody = new BandwidthVoice.ApiCreateCallRequest({
    "to" : "{to}",
    "from" : "{from}",
    "applicationId" : "{app_id}",
    "answerUrl" : "{url}",
    "answerMethod"  : "POST",
    "callTimeout"   : 30
});
voiceController.createCall("{account_id}", voiceBody)

When the call is answered by whoever you sent the call to, Bandwidth will send a callback/webhook with a JSON body to the URL you specified when you created the call. You can send BXML verbs back to Bandwidth in response to the callback/webhook in order to create new actions on the call. Some simple server code that would make the call play some text-to-speech audio and then hang up could look like this (note that you can provide a specific port number to app.listen() to have the server listen on that port).

const express = require("express");
const bodyParser = require("body-parser");
const BandwidthBxml = require("@bandwidth/bxml");

const app = express();

app.use(bodyParser.json());

app.post("/voice", function(req, res) {
    if (req.body["eventType"] == "answer"){
        var speakSentence = new BandwidthBxml.Verbs.SpeakSentence();
        speakSentence.setSentence("I am saying something and now will hang  up.");
        speakSentence.setVoice("julie");

        var hangup = new BandwidthBxml.Verbs.Hangup();

        var response = new BandwidthBxml.Response();
        response.addVerb(speakSentence);
        response.addVerb(hangup);

        res.send(response.toBxml());
    } else {
       res.status(200).end();
    }
});

app.listen();

And that’s it! That’s how simple it is to create your first message and call with a Bandwidth phone number, Bandwidth’s API, and Bandwidth’s Node SDK.

Variable Reference

Here is an explanation of the variables used in the above code that will be unique to your account and use case.

Variable NameExplanation
usernameyour username for the Bandwidth Dashboard
passwordyour password for the Bandwidth Dashboard
app_idthe ID of your messaging or voice application; applications are set within the Bandwidth Dashboard and are used associate your Bandwidth phone numbers with URLs for callback/webhooks
from_numberwhen creating outgoing messages or calls, the number you are sending to; this can be your cell phone number for testing or the number of one of your customers
to_numberwhen creating outgoing messages or calls, this is a number you have been assigned by Bandwidth that lives on your Bandwidth Dashboard account
account_idyour Bandwidth Dashboard account ID
urla URL you own that to which Bandwidth will send callbacks/webhooks related to call and messaging events; note that for messaging, this URL is not set at the time of message creation and is instead defined by the Bandwidth Dashboard application used to send the message

Learn more

Want to learn more about creating your first call or message using Bandwidth's APIs and PHP? Get in touch with our experts and check out our developer resources.

Talk to an expert Bandwidth Developer Resources