Menu

Rate this page:

Thanks for rating this page!

We are always striving to improve our documentation quality, and your feedback is valuable to us. How could this documentation serve you better?

Click To Call with Python and Flask

Wish your users could get in touch as easily as they can surf? It's your lucky day!

Let's go over the steps necessary to implement click-to-call in a Python and Flask application.

Click to Call

  1. A website visitor submits a web form with a phone number.
  2. Your web application receives the submission and initiates an HTTP request to Twilio asking to initiate an outbound call.
  3. Twilio receives the request and initiates a call to the user's phone number.
  4. The user picks up the call.
  5. After the call connects, we provide TwiML instructions to connect the user to our sales or support teams.

What We Will Learn

This tutorial demonstrates how to initialize a call using the Twilio REST API and how to create a call using the TwiML Say verb.

Let's get started! Click the button below to move to the next step of the tutorial.

Next

Set up your environment

Before we create our click-to-call application, we need to set up our environment first.

Let's put our Twilio credentials in a place where our application can access them. We'll store them as environment variables that our application can read.

# Twilio API credentials
# Found at https://www.twilio.com/console
export TWILIO_ACCOUNT_SID=ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
export TWILIO_AUTH_TOKEN=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

# You need to create a TwiML app to use this project.
# Create one at https://www.twilio.com/console/phone-numbers/dev-tools/twiml-apps
# then use its "Sid" value here
export TWILIO_APP_SID=APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

# Get your number at
# https://www.twilio.com/console/phone-numbers/incoming
export TWILIO_CALLER_ID=you_twilio_number

Replace the Account_SID, Auth_Token, and Twilio_Number placeholder values with your unique values, which you can find in the Twilio Console. You can use an existing Twilio phone number or obtain a new number.

Twilio Console Credentials Location

        
        
        
        
        TwilioDevEd/clicktocall-flask/.env.example

        Next, let's look at making a friendly web form.

        Next

        The web form

        For our solution, we'll need a form where the user can enter a phone number.

        No need to overthink this step as the real goal is to POST the user's phone number to your controller.

        What information does this form need?

        • An input for the User's phone number
        • An input for the sales team phone number
        • A submit button
              
              
              
              
              clicktocall/templates/index.html

              A user facing web form

              clicktocall/templates/index.html

              Since the page doesn't need to render new content after clicking on submit, we decided to implement the POST action via Ajax using jQuery. Let's look at that code next.

              Next

              Submit the form

              To make the click to call feature more seamless we used Ajax to send the form asynchronously.

              This code shows one way you could implement this functionality using jQuery.

              • Watch for the user submitting the form
              • Submit the form data to our controller
              • Let the user know if the submission was successful or not

              This is a common implementation of jQuery's $.ajax() method. Notice that we are returning the response message when the call has connected.

                    
                    
                    
                    
                    clicktocall/static/js/app.js

                    'Submit' the web form with jQuery

                    clicktocall/static/js/app.js

                    Now that we have the front end done let's build the back end that will receive this data. We'll start our exploration in the next step.

                    Next

                    Instantiate the client object

                    First, we instantiate a TwilioRestClient object with our Account SID and Auth Token. This is essentially our Python REST API handler, which we could use to send SMSes.

                    But for now, we need it to get access to the object that we're going to use to create phone calls.

                          
                          
                          
                          
                          clicktocall/app.py

                          Application Core Controller

                          clicktocall/app.py

                          Let's look at how to make a phone call.

                          Next

                          Make a phone call

                          Next, we'll use the create method from the calls object to make an outgoing phone call. This requires us to pass a From number, a To number and a URL parameter that tells Twilio what to do after it connects the call to our user. In this case, Twilio needs to dial in the Agent once the call has been placed. We'll discuss this more in the future steps.

                                
                                
                                
                                
                                clicktocall/app.py

                                Next

                                clicktocall/app.py

                                Next, let's take a look at how to define the outbound endpoint.

                                Next

                                The Outbound endpoint

                                Twilio makes a request to our application when the call is created using the REST API. We'll need to create an endpoint that is publicly available for internet requests: we'll walk through a way to make your localhost accessible via ngrok a little later in this tutorial.

                                      
                                      
                                      
                                      
                                      clicktocall/app.py

                                      Application Core Controller

                                      clicktocall/app.py

                                      Next, we will see how to generate the TwiML required for Twilio to take actions on behalf of our application.

                                      Next

                                      Generating TwiML

                                      TwiML is a set of simple verbs and nouns written in XML that Twilio reads as instructions.

                                      In this case, our instructions inform Twilio to simply SAY something to the user. If we wanted to connect the user to a real support agent, we would have to add a Dial verb that specifies the support agent number so the customer can talk to him or her.

                                      To make writing TwiML easy, many of the helper libraries have methods that generate TwiML for you. In this case, we use the twilio Python library to create a TwiML response that will instruct Twilio to say something.

                                            
                                            
                                            
                                            
                                            clicktocall/app.py

                                            Connect an 'agent' to the user

                                            clicktocall/app.py

                                            And with that, you've helped us get a working click-to-call form, ready to be integrated into your own application.

                                            Next

                                            Testing Your App Locally

                                            Now you can run and test your Twilio app.

                                            However, you probably want to test it using a publicly available endpoint without having to go "public" with your app. The best option is to use ngrok.

                                            Note: For more information about running the application, see the Readme file in the app github repository.

                                            About ngrok

                                            ngrok generates a secure URL that forwards traffic to a port, usually 5000, on your localhost server. It allows you to run applications locally but make them a publicly available endpoint via secure tunneling. This allows you to test your application and do all the things you want your app to do but in a secure public space.

                                            In case you are wondering, ngrok is an executable (ngrok.exe) that you run on the command line or terminal.

                                            Setting Up ngrok

                                            ngrok is brilliantly simple to use. You sign up on the ngrok website (ngrok.com), download the ngrok.zip file for your OS of choice, then unzip the file into an easily accessible location.

                                            For example, on Windows, you can place it in your \Users directory in \AppData\Roaming\<ngrok-directory-name>\ngrok.exe. Then, update your PATH environment variables to the location of the ngrok executable. On Linux or OSX, it's much easier (see the instructions on the ngrok site).

                                            And that's it.

                                            Accessing your app from an endpoint using ngrok

                                            So, now you are ready to use ngrok.

                                            Before you start ngrok, it might be a good idea to have your Twilio Console open.

                                            For Mac and Linux, open a terminal and run this command to start ngrok:

                                            $ ./ngrok http 4040

                                            On Windows, open a command prompt and run this command to start ngrok:

                                            $ Path-to-ngrok> ngrok http 4040

                                            Alternately, you can start ngrok using the following command:

                                            $ ngrok http 4040 -host-header="localhost:4040"

                                            The port number "4040" is arbitrary. If your local server is running on another port, replace "4040" in the command with the appropriate port number.

                                            This will start ngrok. A running instance of ngrok will appear in the terminal showing the local web interface (in this case http://127.0.0.1:4040) and the public URL (in this case, https://28dd499b.ngrok.io).

                                            ngrok-running

                                            The forwarding public URL needs to be set in the Twilio Console. In the Console, select the active phone number you set in the configuration file and enter the public URL from ngrok (shown above) in the "A Call Comes In" field under Voice & Fax. Be sure to select Webhook from the dropdown list.

                                            Remember, each time you run ngrok, a new public URL will be generated. You will need to set this new URL in the Console.

                                            Twilio Console Webhook Setting

                                            And that's it. You now have a publicly available endpoint for your app, so now you can take a look at your running app and enter the phone numbers using your ngrok address: https://xxxxxx.ngrok.io

                                            What Else Can I Build?

                                            Where to Next?

                                            Did this help?

                                            Thanks for checking out this tutorial! Tweet to us @twilio and let us know what you're building!

                                            Agustin Camino David Prothero Kevin Whinnery Glenn Lea Kat King Andrew Baker Paul Kamp
                                            Rate this page:

                                            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.