What is Twilio?
Twilio is a company founded in 2008. The company’s first public service was Twilio Voice, which allows developers to make and receive phone calls programmatically. Only in 2010, the Twilio SMS API was launched. Growing ever since, more and more services have been added, with the most recent launch of Twilio Flex, a programmable contact center platform.
How does it work?
Twilio has taken steps to build infrastructure around communication services. Before Twilio, if you wanted to send text messages or place phone calls from your web application, you would have had to get in touch with different carriers and operators and pay hefty sums of money. Twilio takes care of this so you can focus on building your product. Their offering even includes email delivery, fax sending and receiving, and a programmable chat.
Twilio SMS
Programmable SMS is a platform that allows you to use SMS in any way your application needs. You can send and receive text messages, buy shortcodes and even alphanumeric identifiers, so your clients can easily recognize who sent the message.
In terms of coverage, they support sending messages to more than 200 different countries. You can also buy phone numbers in almost 50 countries to customize the sender. Getting an SMS from a local number can give your customers more confidence in your service.
The use cases are endless. SMS allows reaching customers faster than email in some circumstances. For example, if your customer doesn’t have your app (if you happen to have one), or they have a bad internet connection, SMS APIs can save the day. You can increase engagement by simply sending order confirmations or appointment reminders.
Which APIs can I use at RapidAPI?
Twilio currently offers three of their APIs at RapidAPI:
Twilio Lookup allows you to get more information about a phone number. You can ask about the phone number’s nature and carrier: whether it’s a mobile or a landline. You can also query the caller information, so you can identify who the owner of the number is. Since you can’t send text messages to a landline, knowing the nature of the phone number is a big plus.
Twilio Phone Number Verification offers precisely what you’d expect: verification of phone numbers. By sending either an SMS or calling the number, you can effortlessly confirm a user’s contact information.
Twilio SMS is, as we explained above, exactly what you’d expect: it enables you to send and receive messages to and from mobile phones.
Browse Twilio APIs
Twilio API Pricing
Below you’ll find a table showing the different prices for each of Twilio’s services offered at RapidAPI. Each offering has different pricing, so be sure to check them out using the link in the previous section.
Lookup | Phone Number Verification | SMS |
$0.005 for carrier lookups $0.01 for caller lookups | $0.05 for each request | $0.0075 per message (in the United States) |
SMS costs are calculated depending on the destination. For this reason, we recommend you check Twilio’s pricing page. As an example, an SMS to the United States costs $0.0075 to send.
Let’s build something!
To illustrate how easy it is to use Twilio’s SMS API, we’ll be building a Rails Application. Here, users will receive an SMS when their orders have been shipped. This will give us the chance to use the Lookup API to check if a phone is a mobile phone. We’ll also explore sending text messages using the SMS API.
For this project, you will need:
- Ruby 2.6
- Ruby on Rails 5
- Postgres, MySQL or some database engine compatible with Rails
- A RapidAPI account
Don’t despair: the contents of this tutorial will easily apply to other versions of Ruby and Rails. If you’ve never used Rails before, check out some tutorials on the framework before. Even though we won’t go very deep into all features, some basic knowledge is recommended.
If you haven’t already, sign up for an account at rapidapi.com. RapidAPI integrates several APIs, saving you time and effort.
1. Create the app
Let’s begin by creating a new application. Rails is an open-source project, so documentation on the commands we’ll use in this article is easy to find online if you happen to get lost.
rails new my-store -d postgresql
We will use Postgres for this tutorial, but any of the supported database engines will work. We’ll also need to add bcrypt
and unirest
to the Gemfile. bcrypt
enables hashed storage of passwords, while unirest
lets us use the APIs. You can get a quick reference on the Unirest gem here.
# Gemfile gem 'bcrypt' gem 'unirest'
Remember to run bundle install
in your terminal to install the gems.
2. The User model and looking up a phone number
When a user signs up on our website, we’ll ask them to provide us with their phone number. After the form is submitted, we’ll check if the phone number is valid and capable of receiving SMS
First, let’s create a User model. Run this in your terminal:
rails generate model User email:string password_digest:string phone:string mobile:boolean
In the generated user model, we’ll add some validation and password storage support:
# app/models/user.rb class User < ApplicationRecord # Enables password storage has_secure_password # Validate that both email and phone are always there validates :email, :phone, presence: true end
Let’s create a new controller to sign up a user:
class UsersController < ApplicationController # GET /users/new def new @user = User.new end # POST /users def create @user = User.new(user_params) respond_to do |f| if @user.save # Redirect to our (hypothetical) store front f.html { redirect_to store_front_path } else f.html { render action: :new } end end end private def user_params params .require(:user) .permit(:email, :password, :password_confirmation, :phone) end end
And the routes:
# config/routes.rb Rails.application.routes.draw do resources :users, only: %i[new create] end
So far we have created a controller where a user can sign up. For the sake of simplicity, we’re omitting the views in this tutorial. Next, to look up some information about the user’s phone, we’ll create a new class. This will determine if the phone is a mobile or something else:
# lib/twilio/lookup.rb module Twilio class Lookup ENDPOINT = 'https://twilio-lookup.p.rapidapi.com/PhoneNumbers/carrier?phoneNumber=' # Return true if the phone number is a mobile phone, false otherwise def self.check_mobile(phone) response = Unirest.get( ENDPOINT + phone, headers: { 'X-RapidAPI-Host' => ENV.fetch('RAPID_API_HOST'), 'X-RapidAPI-Key' => ENV.fetch('RAPID_API_KEY') } ) return false unless response.code == 200 response.body['carrier']['type'] == 'mobile' end end end
Our new class is sending a GET request to our lookup endpoint, and parsing if a phone is mobile or not. If our request fails for any reason, we’ll just assume the phone is not SMS-capable. Before we can use this, however, we’ll need to tell Rails to load these files:
# config/application.rb class Application < Rails::Application config.eager_load_paths << Rails.root.join('lib') end
This tells Rails it should load all the files in the lib folder. Now, to integrate our Lookup class into the sign-up flow, we’ll need to change our controller a bit:
# app/controllers/users_controller.rb respond_to do |f| if @user.valid? # Only check if validation passes @user.mobile = Twilio::Lookup.check_mobile(@user.phone) @user.save f.html { redirect_to home_path } else f.html { render action: :new } end end
Notice how we’re checking if the model is valid, then making the phone lookup and storing the result in the user model. There’s no use in looking up the phone number if the form isn’t valid, so we’ll only make the request after we know we have everything we need. Later, when we process a user’s order, we’ll check this to make sure we can actually send them an SMS.
3. Sending an SMS when an order is shipped
Before our app can start sending text messages, we need to buy an SMS-capable phone number. You can do this via the Twilio Console or by making an API call. The easiest way is to use RapidAPI’s endpoint tester. Type mobile
in the phoneNumberType
field, US
in countryCode
and simply write a
for the AccountSid
. The AccountSid
will get populated behind the scenes by RapidAPI.
Note down the phone number you get in response. If you ever forget it, you can always fetch your available phone numbers using the Fetch Multiple Phone Numbers endpoint. Having a phone number to send messages from, we can now create our SMS sending class in our Rails app:
# lib/twilio/sms.rb module Twilio class SMS ENDPOINT = 'https://twilio-sms.p.rapidapi.com/2010-04-01/Accounts/a/Messages.json?' def self.send_sms(message, phone) query = { from: ENV.fetch('RAPID_API_PHONE'), to: phone, body: message }.to_query response = Unirest.post( ENDPOINT + query, headers: { 'X-RapidAPI-Host' => ENV.fetch('RAPID_API_HOST'), 'X-RapidAPI-Key' => ENV.fetch('RAPID_API_KEY') } ) response.code == 200 # return true if message is sent correctly end end end
Here, we’re creating a URL querystring containing the phone number we just purchased, the phone number to send the message to, and the actual message. Our method will return true if the message is correctly sent.
With this, we can integrate our method in our application, when we confirm the order has been sent. We’ll just assume such a method exists in our app, and we’ll insert some extra code to send the SMS notification:
class ShippingController < ApplicationController def create @order = Order.find(params[:order_id]) @user = @order.user @shipping = Shipping.new(shipping_params) respond_to do |f| if @shipping.save message = 'Your order has been shipped!' "Use code #{@shipping.tracking} to track." Twilio::SMS.send_sms(message, @user.phone) if @user.mobile f.html { redirect_to dashboard_path } else f.html { render action: :new } end end end end
So, what’s happening here? First, we find the user and their order and create a new shipping entry for it. Once it’s saved, we check if the user signed up with an SMS-capable phone number. If so, we send an SMS confirmation to his mobile.
Connect to Twilio SMS API
Where to go from here
We hope this small tutorial gave you a quick overview of what you can achieve in your Rails applications. There’s much more to Twilio than meets the eye, so we highly recommend taking a closer look at the services they provide. For example, you can also send messages via WhatsApp, using Twilio’s official integration. This is a great solution if your customers live in an area where WhatsApp is preferred over SMS. Or enable two-factor authentication to secure your users’ accounts.
You should also know that Twilio rate-limits their API. A concurrency limit of 100 is applied to their SMS services. Moreover, carriers apply different rate limits on SMS sending. This changes from carrier to carrier and country to country. The good news is that Twilio handles this for you. Your messages will be queued up and sent at a rate that will keep you compliant. If you want more information about this, be sure to check out their Rate Limits and Message Queues guide.
How to Use Twilio on RapidAPI
Check out this video explaining how to use the Twilio API on RapidAPI:
Leave a Reply