SMS APIs
Adding short message services (SMS) to an application, or platform, has become common for many organizations, but can still help to legitimize a service in the market. In short, SMS APIs are simply APIs that help programs send text messages.
You have probably received text-messages from programs utilizing SMS technologies if you have ever received verification codes, appointment reminders, one-time-passwords (OTPs), etc via text messaging on your mobile device.
SMS APIs come in different sizes on RapidAPI with quite a few different API options to choose from. To help you sift through them faster you can check out RapidAPI’s picks for the Top 8 SMS APIs in this article. That would be a good place to start. On the other hand, if you know you want to use one of the popular and reliable choices, then this article will introduce you to the Twilio SMS API on RapidAPI.
Twilio SMS
Twilio is a platform for adding voice, video and messaging to applications. Later, we will be using the Twilio SMS API on RapidAPI, but there are multiple Twilio APIs available on the platform including:
The Twilio SMS API has five sections.
- Message Resource
- Media Resource
- Pricing (text-message pricing per country)
- Service Resource
- Phone Numbers
Also, there’s a stray endpoint for retrieving account information: Fetch an Account Resource.
The endpoints needed for simple SMS are located in the ‘Message Resource’ and ‘Phone Numbers’ sections.
An account needs to have a phone number attached to send messages from, which can either be a local, mobile, or toll-free number. This is a parameter option configurable at purchase time.
Twilio SMS API Dashboard
So far, I have been referencing information that can be found easily on the Twilio SMS API dashboard. The dashboard has three sections:
- endpoints
- definition and parameters
- code snippets and response objects
The dashboard is where we can read documentation, test endpoints, create real resources, change subscription preferences, and view API discussions. It’s a very important place! We will be using the dashboard extensively in our example implementation.
Pricing
On the dashboard click the tab labeled ‘Pricing’ or follow this link to the subscription page.
There is not a free option for the Twilio SMS API, but if you need a free API you can find a list of free SMS APIs by clicking here. Although there is no free subscription plan the Basic subscription allows for a maximum of 100,000 requests which is a nontrivial amount and can be calculated to equal $0.0001/request.
Once subscribed, usage and subscriptions can be managed from your developer dashboard.
Node.js
Node.js is an asynchronous event-driven JavaScript runtime and is designed to build scalable network applications. It has become popular due to it’s ‘non-blocking’ capabilities and ease of writing Javascript for front-end and backend code.
Asynchronous programming is typically described as an advanced topic. However, asynchronous programming is one of the main reasons that Node.js is popular. Therefore, to justify using Node.js, a developer should strive towards using asynchronous programming in Node.js as soon as possible.
Furthermore, It’s difficult to understand and use Node.js without a background using Javascript or another asynchronous programming language. Unless you’re feeling bold, I would recommend exploring Javascript in more depth before continuing‚ since this will not be a comprehensive look at the language.
However, once you have a grasp on Javascript, setting up a web-server will seem relatively straightforward. There are many easy-to-use libraries for setting up web servers, making HTTP requests, handling files, etc.
Package Managers
Node.js has great libraries in the community that help developers build applications. The two common package managers for Node.js are NPM and yarn. You’ll see both used when installing libraries depending on the project or developer.
Many of the same libraries are available regardless of choice, and in our example, we’ll use NPM.
You can always search for a package on the package manager’s website to learn more about functions, libraries, or parameters within a given package.
Look Ahead
In the next section, we will take a look at using RapidAPI, Twilio SMS API, and Node.js to send a text message. Later, we’ll make a few modifications to the function and integrate it into a very small sample application.
This will help you see how the function and SMS APIs can fit into an application!
How to send a Text using Javascript and Node.js
Next, let’s walk through an isolated example of sending a text with Node.js. Some important details will be missing, but they’ll make sense when we integrate the function into an application later on.
const axios = require("axios"); const TWILIO_PHONE_NUMBER = "phone number that you bought" const UNITED_STATES_COUNTRY_CODE = "+1" module.exports = { sendSMS: (body, to) => axios({ method:"POST", url :`https://twilio-sms.p.rapidapi.com/2010-04-01/Accounts/${process.env.TWILIO_SID}/Messages.json`, headers: { "content-type":"application/x-www-form-urlencoded", "x-rapidapi-host":"twilio-sms.p.rapidapi.com", "x-rapidapi-key": process.env.RAPIDAPI_KEY }, params: { from: TWILIO_PHONE_NUMBER, body, to: UNITED_STATES_COUNTRY_CODE + to } }) }
Let’s walk through it step by step.
- Import Axios, a common library for sending HTTP requests.
- Set constants. After we buy a phone number on the dashboard, it needs to be added to the
TWILIO_PHONE_NUMBER
variable. As for the country code, it would not normally be hardcoded but for this example, we are assuming we just want to send messages to U.S. numbers. - Export the function as an object from the file with
module.exports
. Exporting an object means that we can export multiple functions all on the same object. This is useful when building out this object to access more endpoints on the Twilio SMS API. For example, using this object in another file would look something like;
import TwilioAPI from '../utils/twilio.js' TwilioAPI.sendSMS(body, to) TwilioAPI.otherAPICall(arg1, arg2)
4. The function receives two arguments (body, to)
:
- body: The text sent in the message
- to: The number that we send the message to
The function is a simple Axios POST request that returns a Promise. The bulk of the function was taken directory from the RapidAPI dashboard code snippet.
That being said, some variables are added as environment variables for security reasons. Those being;
- account SID: The Twilio account number for the resource. It is a common parameter in Twilio SMS API calls
- RapidAPI key: The secret API key that RapidAPI provides to us.
This function can be called inside a node project, assuming the phone-number, SID, and RapidAPI key are initialized properly, and it will send a text to the number provided as the second argument!
Let’s see it in action.
Example Application
Prerequisites
- Node.js installed on your system
- Reputable text editor for writing code
- Understanding of how to use the terminal (i.e Bash, Powershell) to execute commands
- Internet connection
- Understanding of Javascript
1. Sign Up For a Free Account on RapidAPI
To subscribe to the Twilio SMS API, you will need an account. Visit RapidAPI to get signed up if you haven’t already!
2. Subscribe to the Twilio SMS API
Earlier, I discussed the pricing for the API. Let’s revisit the pricing page on the API dashboard. Search for Twilio SMS or follow this link to the subscription page.
Notice I have already subscribed to the Basic plan, therefore I have a link to Manage and View Usage that takes me to the developer dashboard.
You can track your API usage on the dashboard in case you have concerns about approaching your quota for any of the APIs that you subscribe to.
3. Clone Project
I created a very basic application to mock a scenario that might use SMS. Open up a new terminal in the directory that you want to place the project in. On the command-line enter these two commands:
$ git clone https://github.com/jdretz/rapidapi-twilio-node-starter.git $ npm install
Change directories into the new folder and open up your text editor in the project.
Application Overview
The application uses the express library to create a web application. The application is created, configured, and routes are defined in src/app.js
. I left comments that define each code block and what it’s doing.
Webpage views are created using the hbs library (handlebars) which is a library for HTML templating. Three webpages are located in the src/templates/views
folder. The webpages are served from the main src/app.js
file.
The public
folder holds the front-end Javascript and CSS used in the app. The front-end Javascript is plain Javascript that makes API calls to our backend routes.
Start the application by running npm run dev
in the project root. You should see the following webpage served at http://localhost:3000
.
Users
Users are saved to an array in src/utils/users.js
. This file contains the logic for adding a user, retrieving a user, and adding a verification code to a user object.
Users are deleted when the server restarts (i.e when a change is made)
Sign-up on the main page and notice that the users array logs to the terminal with the information entered.
Next, sign-in on the same page. A message should appear notifying you that you signed in. Both of these actions are managed on the backend in app.js
.
Click on the Forgot Password? link.
This page is where we trigger an SMS verification code to the phone number for the user. It’s also where we enter the verification code and change the password.
There is no verification message sent yet when a username is entered. However, type in your username (after you add one) into the Send SMS form.
Click Send SMS and notice that the user object logged to the terminal now has a value for the verification code parameter. This number will be sent in the verification text message.
4. Buy Twilio Phone Number
Before implementing the function, we need:
- account SID
- Twilio phone number
- RapidAPI key
We get all of these from the dashboard so head over to the Twilio SMS endpoints tab.
Select the Fetch an Account Resource endpoint and hit the Test Endpoint button.
Copy the value for the sid parameter in the response body.
Select the Buy a Phone Number endpoint in the Phone Numbers section.
Enter the required parameters into the middle dashboard section.
After firing off the API call you now have a new phone number to use! Take note of the SID and phone number so we can add them to the code later.
5. Add SMS API Call to Application
Create a new file named twilio.js
in src/utils
and add the following code to it.
const axios = require("axios"); const TWILIO_PHONE_NUMBER = "the phone number you just bought" const UNITED_STATES_COUNTRY_CODE = "+1" module.exports = { sendSMS: (body, to) => axios({ method:"POST", url :`https://twilio-sms.p.rapidapi.com/2010-04-01/Accounts/${process.env.TWILIO_SID}/Messages.json`, headers: { "content-type":"application/x-www-form-urlencoded", "x-rapidapi-host":"twilio-sms.p.rapidapi.com", "x-rapidapi-key": process.env.RAPIDAPI_KEY }, params: { from: TWILIO_PHONE_NUMBER, body, to: UNITED_STATES_COUNTRY_CODE + to } }) }
Next, make a .env
file in the project root. The project uses the dotenv library to add variables in this file to the environment.
Then, in the .env
add the following variables with your values.
RAPIDAPI_KEY=your rapidapi key TWILIO_SID=your twilio sid
Restart the server by entering rs
into the terminal running the server and pressing the enter key.
The environment variables now have the necessary values and the function can be used in the project.
Import and Use sendSMS
in app.js
Add the following import statement to the top of app.js
const TwilioAPI = require('./utils/twilio')
/send-sms
endpoint, change the last return statement from;return res.json({ message: "Verification sent!" })
to;
// Sends messages to user phone number TwilioAPI.sendSMS(`Your verification code is: ${code}`, String(user.phone)) .then(() => { return res.json({ message: "Verification sent!" }) }) .catch(err => { console.log(err); return res.json({ error: "Failed to send verification code." }) })
We imported the object, now we access the function on the object. The function returns a Promise so we can attach calls to then()
and catch()
on the function. This asynchronous functionality is the power of Node.js.
app.js
, change the /verify-sms
route, from;// Verifides code for password change app.post('/verify-sms', (req, res) => { const { code, newPassword, username } = req.body if (!code || !newPassword || !username) { return res.status(404).send({ error: "Please provide all information" }) } // Looks for user const user = users.getUser(username) if (!user) { return res.status(404).json({ error: "User not found" }) } // Verifies code matches code in user object if (user.verificationCode === code) { user.password = newPassword return res.json({ message: "Password changed!" }) } else { return res.status(400).json({ message: "That didn't work!" }) } })
to;
// Verifides code for password change app.post('/verify-sms', (req, res) => { const { code, newPassword, username } = req.body if (!code || !newPassword || !username) { return res.status(404).send({ error: "Please provide all information" }) } // Looks for user const user = users.getUser(username) if (!user) { return res.status(404).json({ error: "User not found" }) } // Verifies code matches code in user object if (user.verificationCode === code) { user.password = newPassword // NEW CODE START TwilioAPI.sendSMS(`Your password was changed recently. If you did not do this contact us immediately!`, user.phone) // NEW CODE END return res.json({ message: "Password changed!" }) } else { return res.status(400).json({ message: "That didn't work!" }) } })
Now the user is notified when their password is changed!
Test
Restart the server and refresh the browser.
Sign-up as a new user with a valid phone number (we will send actual messages to this number). The app will display, “New user added!”.
Next, sign-in to test that the user was added successfully. The app will display, “You are signed in!” if username and password match.
Then, click on Forgot Password?.
Enter your username into the Request Verification Code. The number attached to the user object will receive a text message with a 6-digit code.
As can be seen, I tested it a few times.
Copy the verification code from the text and enter your username, verification code, and new password into the bottom form on the forgot password page.
A message will be sent to the same number notifying them of the change.
Finally, head back to the home page and test the new password by ‘signing-in’. It should display, “You are signed in!”.
Great job!
Conclusion
The sample application should not be duplicated in terms of authentication and does not use best practices in the HTML forms for reasons of simplicity.
Although it’s just an example application the Twilio SMS API integration is very real and can be duplicated. I hope you see how, if you already had an application, it could only take minutes to add this to the app after the account information is set up.
The Twilio SMS API has many endpoints to explore so I hope that you don’t stop here. If you have any questions feel free to leave them in the comments below!
Leave a Reply