Why use SMS APIs in JavaScript?
Adding SMS capabilities to your modern web app or website is one of the quickest and most reliable ways to interact with customers and user bases. There are many things you can do with SMS APIs:
- Learning a caller’s registered name or carrier.
- Sending verification codes from a website or web app.
- Sending SMS texts containing arbitrary content.
But adding these SMS features may seem like a daunting task. Don’t worry! It’s actually much easier than it seems. In fact, in this tutorial, we’re going to make an app that shows just how easy it is to use the various SMS APIs on RapidAPI to perform all of these tasks, in only a few easy lines of JavaScript.
At the end of this blog post, we’ll have a modern JavaScript app that can:
- Lookup a phone number’s name using Twilio Name Lookup
- Lookup a phone number’s carrier using Twilio Carrier Lookup
- Send a verification code to a phone number using Telesign SMS Verify
- Send arbitrary text content to a phone number using Quick Easy SMS
- Send SMS messages with more flexibility and control using Twilio SMS API
Layout the code foundation
To get started, all we need is a simple HTML file.
Since we’re using modern JavaScript features, make sure you’re using a modern browser, such as Google Chrome or Microsoft Chromium Edge, which are both available for Windows and macOS for free.
All our HTML file needs is a little CSS styling to make sure that our app looks respectable. Thanks to modern CSS features such as CSS Grids, we can do a lot with very little code.
So let’s start by creating index.html
and pasting the following code into it:
<!DOCTYPE html> <html lang="en"> <head> <title>JavaScript SMS API example</title> <style> * { margin: 0; padding: 0; } body { display: grid; grid-template-columns: auto auto; gap: 1em; align-items: baseline; padding: 2em; justify-content: start; background: #f7f7f7; font-family: sans-serif; } section { display: inline-grid; gap: 2em; border-radius: 5px; background-color: #fff; padding: 1em; box-shadow: 0px 2px 6px 2px #0002; } form { display: grid; grid-template-columns: auto auto; gap: 1em; align-items: baseline; } button { background: #17f; color: #fff; font: inherit; border: none; border-radius: 3px; outline: none; padding: 0.5em 1.5em; } button:active { background-color: #05b; } :read-write { border: 1px solid #999; border-radius: 3px; font: inherit; padding: 0.5em; outline: none; } :read-write:focus { outline: auto #17f; } </style> </head> <body> </body> </html>
Example 1: Name Lookup via JavaScript SMS API
Sometimes we need to look up the name associated with an SMS capable phone number. For example, this could be used to provide a nicer user interface by showing a greeting to a user who has not yet filled out their own name, but who has signed up for text updates via SMS. We can get this information by making APIs requests from JavaScript.
Tip: If you’re not familiar with making API Requests, or just need a refresher, check out What is an API Request?
Step 1: Subscribe to the API Endpoint
So the first SMS API we will use is Twilio Name Lookup. It’s an excellent API for reducing undeliverable messages, resolving caller names, and finding carriers. Just what we need. However, this SMS API comes with a small fee per use. But the sheer amount of convenience it provides makes it worth the price.
Before you can test this endpoint in RapidAPI, make sure to subscribe to this test in the “Pricing” tab. You’ll need to provide payment details, so make sure you understand how this API’s pricing works.
Note: If you don’t already have a RapidAPI account, this is a good time to sign up first, it’s free!
Step 2: Find the JavaScript code snippet
On the right side of the page, you’ll find the Code Snippets section. Select the Language drop-down, find the JavaScript menu, and choose the fetch option. This will give us the code we need.
Step 3: Add our HTML form and JavaScript function
The Code Snippet in the previous step shows us how to use the API using the fetch function call. We can make this even simpler and more convenient by using async syntax.
So let’s paste the following code into the <body>
tag:
<section> <h2>Twilio Name Lookup</h2> <form onsubmit="TwilioNameLookup()"> <label>Phone Number</label> <input name="to" value="15551231234" autofocus> <span></span> <button>Make API Request</button> </form> </section> <script> async function TwilioNameLookup() { event.preventDefault(); const form = event.target; const to = form.querySelector('[name=to]').value; const result = await fetch("https://twilio-lookup.p.rapidapi.com/PhoneNumbers/caller-name?phoneNumber=" + to, { "method": "GET", "headers": { "x-rapidapi-host": "twilio-lookup.p.rapidapi.com", "x-rapidapi-key": YOUR_RAPID_API_KEY_GOES_HERE } }); const body = await result.json(); console.log(body); if (body.callerName) { const name = body.callerName.caller_name; const kind = body.callerName.caller_type; alert(`Name: ${name}n` + `Kind: ${kind}`); } else { alert('Something went wrong!nn' + body.message); } } </script>
This code is very straightforward:
- We create a form containing a phone number field.
- We hijack its
onsubmit
callback to make our SMS API call. - When we get a response, we show the result in an
alert()
function call.- If the API request succeeded, then we show the information.
- If the API request failed, we show the API’s error response to the user.
Note: make sure your RapidAPI key is included here! It’s automatically included in the Code Snippet on the RapidAPI Endpoint page, but you can just paste it into this code sample for convenience.
Step 4: Try it out
Now you should have a working form:
Try the form with your own SMS capable number, and you’ll see something like this:
Example 2: Carrier Lookup via JavaScript SMS API
It can sometimes be useful to know which carrier provides service to an SMS capable phone number. This information could be used in business making decisions, customer analytics, and in knowing when to use alternate means for customer communications due to a carrier being temporarily out of service.
Tip: for a more detailed look at using APIs with JavaScript, check out How To Use an API with JavaScript (The Complete Beginner’s Guide).
Step 1: Subscribe to the API Endpoint
So let’s go to the Twilio Carrier Lookup API Endpoint page. This link is similar to the last one, but using a different Endpoint for the same API. So you can skip the Subscribe step, which we already did when we created the last form.
Just make sure to click the “Lookup a Phone Number Include Carrier” endpoint, on the left of the page.
Step 2: Find the JavaScript code snippet
Just like before, find the JavaScript -> fetch code snippet on the right, as a reference. Make sure to fill out the required parameter fields first, otherwise the code snippet won’t contain all the parameters we need.
But just like in the last form that we made, that step has been incorporated into the following JavaScript code for your convenience.
Step 3: Add our HTML form and JavaScript function
Now let’s paste the following code into the end of the <body>
tag:
<section> <h2>Twilio Carrier Lookup</h2> <form onsubmit="TwilioCarrierLookup()"> <label>Phone Number</label> <input name="to" value="15551231234" autofocus> <span></span> <button>Make API Request</button> </form> </section> <script> async function TwilioCarrierLookup() { event.preventDefault(); const form = event.target; const to = form.querySelector('[name=to]').value; const result = await fetch("https://twilio-lookup.p.rapidapi.com/PhoneNumbers/carrier?phoneNumber=" + to, { "method": "GET", "headers": { "x-rapidapi-host": "twilio-lookup.p.rapidapi.com", "x-rapidapi-key": YOUR_RAPID_API_KEY_GOES_HERE } }); const body = await result.json(); console.log(body); if (body.carrier) { const name = body.carrier.name; const kind = body.carrier.type; alert(`Name: ${name}n` + `Kind: ${kind}`); } else { alert('Something went wrong!nn' + body.message); } } </script>
This code is almost identical to the code we used in the last form. The main difference is the API Endpoint’s URL that changed, and the JavaScript JSON keys we’re accessing in the response data. Easy!
Step 4: Try it out
Now we have this convenient form, similar to the last one:
Give it a try on your own SMS number:
Example 3: SMS-based Verification via JavaScript SMS API
Many websites use SMS-based verification for new user sign-ups or password resets. This convenient SMS capability is easy to use from JavaScript, as long as you have the right API.
Using SMS for verification usually works like this:
- Create a unique code that can’t be easily guessed
- Send that code to the user via SMS text message
- Ask the user to enter that code into your web form
Let’s look at how to do that second step, sending an arbitrary code via an SMS text message.
Step 1: Subscribe to the API Endpoint
Visit the Telesign SMS Verify page and subscribe to this Endpoint API. Once you subscribe to it, you’ll be able to send your own custom verify codes to any SMS capable phone number.
This Telesign API has a basic pricing plan that’s very affordable, and well worth the price for the benefit it can give your JavaScript web app. So check out the “Pricing” page of this API, and sign up for the “Basic” plan.
Step 2: Find the JavaScript code snippet
Check out the details of this Endpoint, and you’ll notice that it requires two parameters:
- phoneNumber: The phone number that should receive the code.
- verifyCode: Any code that you generate and want to send to a user.
Once you fill these out, you’ll see the fetch code snippet filled in with the parameters in place.
Step 3: Add our HTML form and JavaScript function
Because there’s two parameters here, we’ll need a slightly different form than the previous API examples used, since we’ll need two <input>
fields. But the basic code flow is the same. We create a form, make an API request when submitted, and show the result in an alert.
Here’s the code we need. Let’s it inside the <body>
tag near the end:
<section> <h2>Telesign SMS Verify</h2> <form onsubmit="TelesignSMSVerify()"> <label>Phone Number</label> <input name="to" value="15551231234"> <label>Code</label> <input name="code" value="123456"> <span></span> <button>Make API Request</button> </form> </section> <script> async function TelesignSMSVerify() { event.preventDefault(); const form = event.target; const to = form.querySelector('[name=to]').value; const code = form.querySelector('[name=code]').value; const result = await fetch("https://telesign-telesign-send-sms-verification-code-v1.p.rapidapi.com/sms-verification-code?phoneNumber=" + to + "&verifyCode=" + code, { "method": "POST", "headers": { "x-rapidapi-host": "telesign-telesign-send-sms-verification-code-v1.p.rapidapi.com", "x-rapidapi-key": YOUR_RAPID_API_KEY_GOES_HERE, }, }); const body = await result.json(); console.log(body); alert(body.message); } </script>
Step 4: Try it out
Our new form looks similar to the other two, but with two fields instead of one:
Try the form with your own number, and you’ll see something like this:
Example 4: Sending SMS texts via JavaScript SMS API
Sometimes it’s not enough to just send a verification code to a user via SMS. Instead, we may need to send instructions, a link, or just a general message.
The Quick Easy SMS API is perfect in this situation. It lets you send an arbitrary message to any SMS capable number, with just a few short lines of JavaScript. So we’ll explore how you can use that API from ordinary JavaScript functions.
Step 1: Subscribe to the API Endpoint
This API also has a free tier, which is suitable for testing with a small number of API calls. Make sure to subscribe to this API before moving forward.
Otherwise, this is the same as the other examples:
- Take note of the pricing schemes.
- Choose a pricing plan that fits your needs.
- Fill in your payment details.
- Subscribe and start using the Endpoint!
Step 2: Find the JavaScript code snippet
Notice the three parameters that this API comes with:
- message: The content you want to send to the SMS number.
- toNumber: The number to send the message to. Note the restrictions.
- ipnUrl: This URL will get a callback from replies. You can ignore this for now.
Tip: Even though we’re not going to use the ipnUrl field here, it can be very useful for those situations where you need to handle replies from the user.
Step 3: Add our HTML form and JavaScript function
Just as in the other examples, we’ll take a modified version of the fetch code snippet.
So let’s paste this into the end of our <body>
tag:
<section> <h2>Quick Easy SMS</h2> <form onsubmit="QuickEasySMS()"> <label>Phone Number</label> <input name="to" value="15551231234"> <label>Message</label> <textarea name="msg">Testing from JavaScript using RapidAPI!</textarea> <span></span> <button>Make API Request</button> </form> </section> <script> async function QuickEasySMS() { event.preventDefault(); const form = event.target; const to = form.querySelector('[name=to]').value; const msg = form.querySelector('[name=msg]').value; const result = await fetch("https://quick-easy-sms.p.rapidapi.com/send", { "method": "POST", "headers": { "x-rapidapi-host": "quick-easy-sms.p.rapidapi.com", "x-rapidapi-key": YOUR_RAPID_API_KEY_GOES_HERE, "content-type": "application/json" }, "body": JSON.stringify({ "message": msg, "toNumber": to, }) }); const body = await result.json(); console.log(body); alert(body.StatusCode === 0 ? 'Code sent!' : 'Something went wrong. Check dev console.'); } </script>
This code is almost identical to some of the other examples.
Since we’re sending a message, all the API can tell us is whether it was successfully sent to the carrier. So all we can say in our alert is whether it succeeded or failed.
Step 4: Try it out
Now we have a form that looks like this:
If you put your own SMS capable number in here, you’ll see a text like this:
Example 5: Sending SMS in JavaScript via Twilio SMS API
We’ve seen how easy it can be to send SMS messages from JavaScript using one API. But sometimes we need a little more control. For example, the ability to choose which number to send one or more SMS messages from, or to purchase specific types of phone numbers from a particular region of the world in order to send the SMS message. The Twilio SMS API provides exactly that.
Step 1: Subscribe to the API Endpoint
Since the Twilio SMS API provides much more control over how to send SMS messages, there are more API endpoints to explore.
Take a look around this page to get a feel for what kinds of things you can do with the various Twilio SMS API endpoints.
Step 2: Find the JavaScript code snippet
Because it is more involved, we’re going to borrow a little work from another article, Using Twilio API with SMS in React. Head over to that article for more information on how to use the Twilio SMS API.
In particular, that blog post describes five functions that we’ll need:
getAccountId
getAvailableNumbers
buyPhoneNumber
sendSMS
deletePhoneNumber
Make sure to copy and paste these functions into the code in the next step.
Step 3: Add our HTML form and JavaScript function
<section> <h2>Twilio SMS</h2> <form onsubmit="TwilioSMS()"> <label>Phone Number</label> <input name="to" value="15551231234"> <label>Message</label> <textarea name="msg">Testing from JavaScript using RapidAPI!</textarea> <span></span> <button>Make API Request</button> </form> </section> <script> async function getAccountId() { /* ... */ } async function getAvailableNumbers(accountId) { /* ... */ } async function buyPhoneNumber(accountId, number) { /* ... */ } async function sendSMS(accountId, phoneId, to, msg) { /* ... */ } async function deletePhoneNumber(accountId, phoneNumberId) { /* ... */ } async function TwilioSMS() { event.preventDefault(); const form = event.target; const to = form.querySelector('[name=to]').value; const msg = form.querySelector('[name=msg]').value; const accountId = await getAccountId(); const numbers = await getAvailableNumbers(accountId); let phone; for await (const { number } of numbers) { const phoneId = await buyPhoneNumber(accountId, number); if (phoneId) { phone = { id: phoneId, number }; break; } } const status = await sendSMS(accountId, phone.number, to, msg); await deletePhoneNumber(accountId, phone.id); alert(`Delivery status: ${status}`); } </script>
Here we’re using all the functions gathered from the other article, to use Twilio SMS API one step at a time. Thanks to async function syntax, our code is straightforward, avoiding difficult to read callback pyramids. It runs through 5 simple steps:
- Get the Twilio account ID for use in the next steps.
- Fetch a list of numbers available for purchasing.
- Try purchasing each phone number until one succeeds.
- Send the actual SMS using our purchased phone number.
- Delete the phone number to clean up and release resources.
Step 4: Try it out
Our form looks similar to the last one, since it does the same thing, although using different APIs:
Give it a try and check your text messages!
Conclusion
Using SMS APIs in JavaScript doesn’t have to be difficult. With the right APIs, you can easily use JavaScript to:
- Verify phone numbers
- Send text messages
- Get a caller’s name
- Get a number’s carrier
- And more!
Leave a Reply