Search for and buy Twilio phone numbers with Ruby

March 02, 2017
Written by
Phil Nash
Twilion

You’re in a hurry and you need a new phone number! All you have is your Twilio Account SID, Auth Token and a command line with Ruby installed. What do you do?

Don’t worry, just grab your keyboard, open your terminal and you’ll have that new number in no time.

Let’s buy a phone number

Make sure you have the twilio-ruby gem installed. This will make things a lot easier to call the REST API (though there are many ways to make an HTTP call with Ruby).

Install the Twilio gem

If you don’t have the gem yet, get it installed now. On the command line type:

$ gem install twilio-ruby

Now that the gem is installed, we can get to work. For maximum speed we’re going to write all of our code in irb, Ruby’s REPL. If you prefer, you can use pry instead.

Prepare your API client

Open up irb and require the twilio-ruby gem. You can do this in one step with this line:

$ irb -r twilio-ruby

We need to create an API client that is authenticated to use the API with our credentials. You’ll need your Account SID and Auth Token (found in your Twilio console) for this bit.

Your Account SID and Auth Token can be found on your dashboard in the Twilio Console under the section titled Account Summary.

Create the client like so:

client = Twilio::REST::Client.new("ACCOUNT_SID", "AUTH_TOKEN")
=> <Twilio::REST::Client @account_sid=ACCOUNT_SID>

Search for the perfect number

Now that we have the authenticated client we can start searching for numbers to buy. We need to pick a country in which to search for numbers. Since I’m in the UK, I’m going to search for a nice local British number. If you want to search in a different country, substitute “GB” with the two letter country code that you want.

numbers = client.available_phone_numbers("GB").local.list
=> [<Twilio::REST::Api::V2010::AccountContext::AvailablePhoneNumberCountryContext::LocalInstance>, … ]

This has given us a list of AvailablePhoneNumberCountryContext::LocalInstance objects, but we want to see the numbers themselves.

numbers.map { |number| number.phone_number } 
=> ["+4429...", ...]

I got a list of numbers from Cardiff when I performed this search. I’m in London though, so let’s try to find some London numbers. We’ll do so by searching for numbers that contain “4420”.

numbers = client.available_phone_numbers("GB").local.list(contains: "4420")
irb(main):005:0> numbers.map { |number| number.phone_number }
=> ["+4420...", ...]

There we go, some London numbers. You can search for any subset of numbers or for mobile or toll-free numbers if you’d prefer those.

Buying the number

We’ve found a number we want so next we need to make a request to create a new incoming phone number for our account.

number = numbers.first.phone_number
phone_number = client.incoming_phone_numbers.create(phone_number: number)
=> <Twilio::REST::IncomingPhoneNumber @path=/2010-04-01/Accounts/ACCOUNT_SID/IncomingPhoneNumbers/PHONE_NUMBER_SID>

We have bought our phone number!

The only thing is, it doesn’t do anything interesting yet. It’s going to need some URLs that Twilio will make requests to when the number receives an incoming call or SMS. The URLs need to return TwiML, a subset of XML, that tells Twilio what to do with the call or message.

Adding behaviour to the number with TwiML Bins

You can generate TwiML however you like, but for the purposes of this phone number I’m going to use TwiML Bins which let you edit and then host TwiML from your Twilio console. TwiML Bins are more powerful than hosting plain XML too as they support Mustache templates.

Open your console and create two TwiML Bins, one for voice and one for SMS. Here’s an example you can use for voice that uses TwiML’s <Say> to read out a message to the caller:

<?xml version="1.0" encoding="UTF-8"?>
<Response>
  <Say>Hello from your new number!</Say>
</Response>

Here’s an example for SMS that echoes back the message you send to the number:

<?xml version="1.0" encoding="UTF-8"?>
<Response>
  <Message>Echo: {{ Body }}</Message>
</Response>

Save those TwiML Bins and grab the URLs. Update the phone number, adding a voice_url and sms_url parameter:

phone_number.update(voice_url: "https://handler.twilio.com/twiml/...", sms_url: "https://handler.twilio.com/twiml/...")
=> <Twilio::REST::IncomingPhoneNumber @path=/2010-04-01/Accounts/ACCOUNT_SID/IncomingPhoneNumbers/PHONE_NUMBER_SID>

You have bought and configured a new number! Give it a call and you’ll hear the message from the TwiML Bin. Send it an SMS message and it will echo that message back to you.

Success! High five with the Teenage Mutant Ninja Turtles!

Numbers bought

That’s all you have to do to buy yourself a new Twilio number. It took us only 8 lines of Ruby!

Now you can use this in your applications to provide numbers for your users. This is particularly useful when you are doing phone number masking. You could also use this code to create local phone numbers in a call tracking campaign.

Let me know what you get up to with your new found ability to buy phone numbers whenever you want. Shoot me an email at @philnash or leave a comment below.