Use Voice Add-ons in Python

In this guide we’ll cover how to combine Twilio Add-ons with Programmable Voice to use data from Twilio's partners in your Python web application. The sample code in this guide will use the Twilio Python SDK and the Flask web framework. Let's get started!

What's an Add-on?

Twilio Add-ons are pre-integrated third party services that you can use with your Twilio application. Add-ons enhance the responses your application receives from Twilio by including additional data from Twilio’s partners.

Loading Code Samples...
Language
{
    "status": "successful",
    "message": null,
    "code": null,
    "results": {
        "whitepages_pro_caller_id": {
            "code": null,
            "message": null,
            "request_sid": "XRb57cab3a3c0cfe0bb50f093d9bd3b0a3",
            "result": {
                "alternate_phones": [
                    "8003361327"
                ],
                "associated_people": [],
                "belongs_to": [
                    {
                        "age_range": null,
                        "firstname": null,
                        "gender": null,
                        "id": "Business.7e29cf66-8bf2-4812-829d-356654b5b3d3.Durable",
                        "lastname": null,
                        "link_to_phone_start_date": null,
                        "middlename": null,
                        "name": "Twilio Inc",
                        "type": "Business"
                    }
                ],
                "carrier": "Twilio",
                "country_calling_code": "1",
                "current_addresses": [
                    {
                        "city": "San Francisco",
                        "country_code": "US",
                        "delivery_point": "MultiUnit",
                        "id": "Location.88e44955-805c-455a-99da-d7444ca5c484.Durable",
                        "is_active": true,
                        "lat_long": {
                            "latitude": 37.783382,
                            "longitude": -122.395714,
                            "accuracy": "RoofTop"
                        },
                        "link_to_person_start_date": null,
                        "location_type": "Address",
                        "postal_code": "94107",
                        "state_code": "CA",
                        "street_line_1": "Address",
                        "street_line_2": null,
                        "zip4": "3624"
                    }
                ],
                "error": null,
                "historical_addresses": [],
                "id": "Phone.4d796fef-a2df-4b08-cfe3-bc7128b6f6bb.Durable",
                "is_commercial": true,
                "is_prepaid": false,
                "is_valid": true,
                "line_type": "NonFixedVOIP",
                "phone_number": "5558675309",
                "warnings": []
            },
            "status": "successful"
        }
    }
}
This is a sample of the payload your application would receive when using the WhitePages Pro add-on
Sample data from the Whitepages Pro add-on

This is a sample of the payload your application would receive when using the WhitePages Pro add-on

Here’s an example that uses the Whitepages Pro Caller Identification add-on. When you enable this add-on in your Twilio Console, Twilio will include this data with its requests to your application for incoming phone calls.

The Whitepages Pro Caller Identification add-on gives your application more detailed information about the caller, like their name and address. But that’s just one add-on — there are more you can use from Twilio partners like IBM Watson and Wolfram Alpha, among others.

See the Add-ons Catalog for the complete list of available add-ons.

Enabling Add-ons in the Twilio Console

The first stop in using an add-on is your Twilio Console. Log in and navigate to the Add-ons page within the Marketplace section.

Add-ons catalog

Then choose on the add-on you want to enable and click the “Install” button. In this example, we’ll use the Whitepages Pro Caller Identification add-on.

Install an Add-on

Once installed, be sure to check the box for “Incoming Voice Call” and click save. This will tell Twilio to use the add-on with incoming calls to your Twilio phone numbers.

Now we’re ready to use the extra data from our add-on in our Python application.

Using Add-on data in your application

Twilio will include data from all of your add-ons in an “AddOns” field on requests it makes to your application.

Loading Code Samples...
Language
from flask import Flask, request
from twilio import twiml

import json


app = Flask(__name__)

@app.route("/voice", methods=['GET', 'POST'])
def call():
    """Responds to incoming calls using Twilio Add-ons"""
    # Start our TwiML response
    response = twiml.Response()

    # Decode the JSON included in the 'AddOns' field
    add_ons = json.loads(request.values['AddOns'])

    # If the Whitepages add-on found nothing, return immediately
    if 'whitepages_pro_caller_id' not in add_ons['results']:
        response.say('Sorry, I could not learn anything about you.')
        response.hangup()

        return str(response)

    # Otherwise, extract the Whitepages data
    whitepages = add_ons['results']['whitepages_pro_caller_id']

    # Grab the result Whitepages gave us
    # (see the "Documentation" tab on the Whitepages add-on for more details)
    caller_id = whitepages['result']

    # See if we can get the caller's name
    try:
        first_name = caller_id['belongs_to'][0]['firstname']
    except (IndexError, KeyError):
        first_name = 'a mystery'

    # And what city the caller lives in
    try:
        city = caller_id['current_addresses'][0]['city']
    except (IndexError, KeyError):
        city = 'a mystery'

    # Tell the caller what we think their name and city are
    response.say('Hello. Your name is {}.'.format(first_name))
    response.say('And I think you live in {}.'.format(city))

    # Then end the call
    response.hangup()

    return str(response)

if __name__ == "__main__":
    app.run(debug=True)
Use the Whitepages Pro Caller ID add-on to tell a caller their name and where they live
Use the Whitepages Pro add-on to respond to an incoming phone call

Use the Whitepages Pro Caller ID add-on to tell a caller their name and where they live

This Flask application uses the data from the Whitepages Pro Caller ID add-on we configured above to tell the caller their name and what city we think they live in.

You can find a detailed specification of the data structure for an individual add-on within that add-on's page in the catalog.

And that’s it! Try giving your application a call to see your add-on in action. If you've never received a Twilio phone call with Python before, check out our guide on that topic.

Where to next?

We focused on the Whitepages add-on in this guide, but you can just as easily use any of the add-ons available in the catalog in your Twilio Console.

Check out the full Add-Ons API Reference documentation if you want to learn more about how add-ons work, or even how to publish your own.

Andrew Baker
Ricky Robinett
Rob Spectre
Kevin Whinnery
David Prothero

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.

1 / 1
Loading Code Samples...
{
    "status": "successful",
    "message": null,
    "code": null,
    "results": {
        "whitepages_pro_caller_id": {
            "code": null,
            "message": null,
            "request_sid": "XRb57cab3a3c0cfe0bb50f093d9bd3b0a3",
            "result": {
                "alternate_phones": [
                    "8003361327"
                ],
                "associated_people": [],
                "belongs_to": [
                    {
                        "age_range": null,
                        "firstname": null,
                        "gender": null,
                        "id": "Business.7e29cf66-8bf2-4812-829d-356654b5b3d3.Durable",
                        "lastname": null,
                        "link_to_phone_start_date": null,
                        "middlename": null,
                        "name": "Twilio Inc",
                        "type": "Business"
                    }
                ],
                "carrier": "Twilio",
                "country_calling_code": "1",
                "current_addresses": [
                    {
                        "city": "San Francisco",
                        "country_code": "US",
                        "delivery_point": "MultiUnit",
                        "id": "Location.88e44955-805c-455a-99da-d7444ca5c484.Durable",
                        "is_active": true,
                        "lat_long": {
                            "latitude": 37.783382,
                            "longitude": -122.395714,
                            "accuracy": "RoofTop"
                        },
                        "link_to_person_start_date": null,
                        "location_type": "Address",
                        "postal_code": "94107",
                        "state_code": "CA",
                        "street_line_1": "Address",
                        "street_line_2": null,
                        "zip4": "3624"
                    }
                ],
                "error": null,
                "historical_addresses": [],
                "id": "Phone.4d796fef-a2df-4b08-cfe3-bc7128b6f6bb.Durable",
                "is_commercial": true,
                "is_prepaid": false,
                "is_valid": true,
                "line_type": "NonFixedVOIP",
                "phone_number": "5558675309",
                "warnings": []
            },
            "status": "successful"
        }
    }
}
from flask import Flask, request
from twilio import twiml

import json


app = Flask(__name__)

@app.route("/voice", methods=['GET', 'POST'])
def call():
    """Responds to incoming calls using Twilio Add-ons"""
    # Start our TwiML response
    response = twiml.Response()

    # Decode the JSON included in the 'AddOns' field
    add_ons = json.loads(request.values['AddOns'])

    # If the Whitepages add-on found nothing, return immediately
    if 'whitepages_pro_caller_id' not in add_ons['results']:
        response.say('Sorry, I could not learn anything about you.')
        response.hangup()

        return str(response)

    # Otherwise, extract the Whitepages data
    whitepages = add_ons['results']['whitepages_pro_caller_id']

    # Grab the result Whitepages gave us
    # (see the "Documentation" tab on the Whitepages add-on for more details)
    caller_id = whitepages['result']

    # See if we can get the caller's name
    try:
        first_name = caller_id['belongs_to'][0]['firstname']
    except (IndexError, KeyError):
        first_name = 'a mystery'

    # And what city the caller lives in
    try:
        city = caller_id['current_addresses'][0]['city']
    except (IndexError, KeyError):
        city = 'a mystery'

    # Tell the caller what we think their name and city are
    response.say('Hello. Your name is {}.'.format(first_name))
    response.say('And I think you live in {}.'.format(city))

    # Then end the call
    response.hangup()

    return str(response)

if __name__ == "__main__":
    app.run(debug=True)