Twilio Lookup is a simple REST API with a ton of utility. You can use Lookup to check whether a number exists, format international numbers to local standards, determine whether a phone is a landline or can receive text messages, and even discover information about the carrier associated with that phone number.
In this post, we’re going to learn how to deal with valid and invalid numbers using the Twilio Python library. This code could work in any context whether you use it to look up customer numbers in your production Django app or just have a basic script you want to run to check numbers in a local database. This should also work regardless of whether you are using Python 2 or 3.
Head over to your terminal and install the Twilio Python module:
pip install twilio
You will also need to have your Account SID and Auth Token handy, which you can grab from your Twilio account dashboard.
Now take those values and set them as environment variables:
export TWILIO_ACCOUNT_SID='Replace this with your Twilio Account SID*' export TWILIO_AUTH_TOKEN='*Replace this with your Twilio Auth Token*'
With these set as environment variables, the Twilio Python module will be able to access them so you don’t have the problem of accidentally committing your account credentials to version control. You can also check out this guide on managing your environment variables.
You can check out the Lookup page if you want to play around with the API and see what type of data a request will return. Try entering a phone number and take a look at the JSON response object.
Here’s a quick code sample for that type of lookup without getting the carrier information:
from twilio.rest import Client client = Client() number = client.lookups.phone_numbers("+15108675309").fetch() print(number.national_format) # => (510) 867-5309
This basic functionality is free, but you can get more information by doing a carrier lookup, which will not cost much. Carrier lookups are commonly used to determine if a number is capable of receiving SMS/MMS messages.
Carrier lookups contain much more useful information, but require an extra parameter:
from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/user/account # Store them in the environment variables: # "TWILIO_ACCOUNT_SID" and "TWILIO_AUTH_TOKEN" client = Client() number = client.lookups.phone_numbers("+15108675309").fetch(type="carrier") print(number.carrier['name']) # => Sprint Spectrum, L.P.
You can think about Twilio Lookup as a phonebook REST API. In this “online phonebook” the phone numbers serve as a unique ID. When you try to look up a phone number that does not exist you will get a 404 response.
Head over to the Lookup homepage again to see this in action when you check a number that doesn’t exist:
When the Twilio Python library encounters a 404 it will throw a “TwilioRestException”. If you change our current code to look up an incorrect phone number you will see this in action:
The error code for this is 20404, so if we want to write a function that validates phone numbers we can check to see if an exception was raised with code 20404.
Create a file called “lookup.py” and try this code out:
from twilio.rest import Client from twilio.base.exceptions import TwilioRestException # Your Account Sid and Auth Token from twilio.com/user/account # Store them in the environment variables: # "TWILIO_ACCOUNT_SID" and "TWILIO_AUTH_TOKEN" client = Client() def is_valid_number(number): try: response = client.lookups.phone_numbers(number).fetch(type="carrier") return True except TwilioRestException as e: if e.code == 20404: return False else: raise e print(is_valid_number('19999999999')) # False print(is_valid_number('15108675309')) # True
You now have a function you could use anywhere in your code for validating phone numbers.
So now you know how to use the REST API phone book that is Twilio Lookup. You’ve used it for validating phone numbers, but you can also do cool things like phone number formatting and checking to see whether a number can receive text messages or not.
You might want to use one of these more common cases, but I’m always excited to see what other crazy ideas people think of with new APIs. I cannot wait to see what you build with Twilio Lookup.
If you have any questions or want to show off what you built, feel free to reach out: