Get Started with Python Using Sanic Framework

    Start by signing up for a free trial account that you can use to experiment with and learn about our services. The free trial account comes with free credits, and you can add more as you go along. You can also add a phone number to your account to start testing the full range of our voice and SMS features. A page in our support portal walks you through the signup process.

    You can start making and receiving calls either by using our PHLO visual workflow builder or our APIs and XML documents. Follow the instructions in one of the tabs below.

    Set up your Python Sanic dev environment

    You must set up and install Python, Sanic, and Plivo’s Python SDK before you make your first call.

    Install Python

    Download and install Python from its official site.

    Install Sanic and the Plivo Python SDK

    Create a projects directory and change into it.

      $ mkdir mypythonapp
      $ cd mypythonapp
    

    Install the latest version of the modules using pip.

      $ pip3 install sanic
      $ pip3 install plivo
    

    We recommend that you use virtualenv to manage and segregate your Python environments, instead of using sudo with your commands and overwriting dependencies.

    Make your first outbound call

    You can create and deploy a PHLO to make an outbound call with a few clicks on the PHLO canvas, and trigger it with some simple code.

    Create the PHLO

    To create a PHLO, visit the PHLO page of the Plivo console. If this is your first PHLO, the PHLO page will be empty.

    Create a PHLO for outbound calls

    • Click Create New PHLO.

    • In the Choose your use case pop-up, click Build my own. The PHLO canvas will appear with the Start node.

      Note: The Start node is the starting point of any PHLO. It lets you trigger a PHLO to start upon one of three actions: incoming SMS message, incoming call, or API request.
    • From the list of components on the left side, drag and drop the Initiate Call component onto the canvas. When a component is placed on the canvas it becomes a node.

    • Draw a line to connect the Start node’s API Request trigger state to the Initiate Call node.

    • In the Configuration pane at the right of the canvas, configure the Initiate Call node with a caller ID in the From field. Enter the destination number you wish to call in the To field.

      Note: You can define a static payload by specifying values when you create the PHLO, or define a dynamic payload by passing values through Liquid templating parameters when you trigger the PHLO from your application.
    • Once you’ve configured the node, click Validate to save the configuration.

    • Similarly, create a node from the Play Audio component. Connect the Initiate Call node to the Play Audio node using the Answered trigger state.

    • Configure the Play Audio node to play a message to the user by entering text in the Speak Text box in the Prompt section of the Configuration pane — for example, “Hello, you just received your first call.”

    • Connect the Initiate Call node’s Answered trigger state to the Play Audio node.

    • After you complete the configuration, give the PHLO a name by clicking in the upper left, then click Save.

    Your PHLO is now ready to test.

    Trigger the PHLO

    You integrate a PHLO into your application workflow by making an API request to trigger the PHLO with the required payload — the set of parameters you pass to the PHLO. You can define a static payload by specifying values when you create the PHLO, or define a dynamic payload by passing values through parameters when you trigger the PHLO from your application.

    In either case, you need your Auth ID and Auth Token, which you can get from the overview page of the Plivo console.

    AUTHID

    You also need the PHLO ID, which you can copy from the PHLO list page.

    PHLO List

    With a static payload

    When you configure values when creating the PHLO, they act as a static payload.

    With Static Payload

    Code

    Create a file called trigger_phlo.py and paste into it this code.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    
    import plivo
    from sanic import Sanic
    from sanic.response import text
    
    app = Sanic('Plivo Voice App')
    
    @app.route('/outbound', methods=['POST', 'GET'])
    async def make_call(request):
      auth_id = '<auth_id>'
      auth_token = '<auth_token>'
      phlo_id = '<phlo_id>'
      phlo_client = plivo.phlo.RestClient(auth_id=auth_id, auth_token=auth_token)
      phlo = phlo_client.phlo.get(phlo_id)
      response = phlo.run()
      return text(response, content_type="text/json")
    
    if __name__ == "__main__":
      app.run(host="0.0.0.0", port=8000)
    

    Replace the auth placeholders with your authentication credentials from the Plivo console. Replace the phlo_id placeholder with your PHLO ID from the Plivo console.

    With a dynamic payload

    To use dynamic values for the parameters, use Liquid templating parameters when you create the PHLO and pass the values from your code when you trigger it.

    With Dynamic Payload

    Code

    Create a file called trigger_phlo.py and paste into it this code.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    
    import plivo
    from sanic import Sanic
    from sanic.response import text
    
    app = Sanic('Plivo Voice App')
    
    @app.route('/outbound', methods=['POST', 'GET'])
    async def make_call(request):
        auth_id = '<auth_id>'
        auth_token = '<auth_token>'
        phlo_id = '<phlo_id>'
        payload = {"from" : "<caller_id>","to" : "<destination_number>"}
        phlo_client = plivo.phlo.RestClient(auth_id=auth_id, auth_token=auth_token)
        phlo = phlo_client.phlo.get(phlo_id)
        response = phlo.run(**payload)
        return text(response, content_type="text/json")
    
    if __name__ == "__main__":
      app.run(host="0.0.0.0", port=8000)
    

    Replace the auth placeholders with your authentication credentials from the Plivo console. Replace the phlo_id placeholder with your PHLO ID from the Plivo console. Replace the phone number placeholders with actual phone numbers in E.164 format (for example, +12025551234).

    Test

    Save the file and run it.

    $ python trigger_phlo.py
    
    Note: If you’re using a Plivo Trial account, you can make calls only to phone numbers that have been verified with Plivo. You can verify (sandbox) a number by going to the console’s Phone Numbers > Sandbox Numbers page.

    Receive your first inbound call

    You can create and deploy a PHLO to receive an inbound call with a few clicks on the PHLO canvas, without writing a single line of code.

    Prerequisite

    To receive incoming calls, you must have a voice-enabled Plivo phone number. You can rent numbers from the Numbers page of the Plivo console, or by using the Numbers API.

    Create the PHLO

    To create a PHLO, visit the PHLO page of the Plivo console. If this is your first PHLO, the PHLO page will be empty.

    Create a PHLO to receive incoming call

    • Click Create New PHLO.
    • In the Choose your use case pop-up, click Build my own. The PHLO canvas will appear with the Start node.
      Note: The Start node is the starting point of any PHLO. It lets you trigger a PHLO to start upon one of three actions: incoming SMS message, incoming call, or API request.
    • From the list of components on the left side, drag and drop the Play Audio component onto the canvas. When a component is placed on the canvas it becomes a node.
    • Draw a line to connect the Start node’s Incoming Call trigger state to the Play Audio node.
    • In the Configuration pane at the right of the canvas, configure the Play Audio node to play a message to the caller.
    • Once you’ve configured the node, click Validate to save the configuration.
    • Give the PHLO a name by clicking in the upper left, then click Save.

    Assign the PHLO to a Plivo number

    Once you’ve created and configured your PHLO, assign it to a Plivo number.

    • On the Numbers page of the console, under Your Numbers, click the phone number you want to use for the PHLO.
    • In the Number Configuration box, select PHLO from the Application Type drop-down.
    • From the PHLO Name drop-down, select the PHLO you want to use with the number, then click Update Number.

    Assign PHLO to a Plivo Number

    Test

    You can now make a call to your Plivo phone number and see how the inbound call is handled.

    For more information about creating a PHLO application, see the PHLO Getting Started guide. For information on components and their variables, see the PHLO Components Library.

    Forward an inbound call

    You can create and deploy a workflow to implement call forwarding with a few clicks on the PHLO canvas.

    Prerequisite

    To receive incoming calls, you must have a voice-enabled Plivo phone number. You can rent numbers from the Numbers page of the Plivo console, or by using the Numbers API.

    Create the PHLO

    To create a PHLO, visit the PHLO page of the Plivo console. If this is your first PHLO, the PHLO page will be empty.

    Create a PHLO to receive incoming call

    • Click Create New PHLO.
    • In the Choose your use case pop-up, click Build my own. The PHLO canvas will appear with the Start node.
      Note: The Start node is the starting point of any PHLO. It lets you trigger a PHLO to start upon one of three actions: incoming SMS message, incoming call, or API request.
    • From the list of components on the left side, drag and drop the Call Forward component onto the canvas. When a component is placed on the canvas it becomes a node.

    • Draw a line to connect the Start node‘s Incoming Call trigger state to the Call Forward node.

    • In the Configuration tab at the right of the canvas, configure the Call Forward node to select the From number using a variable. Enter two curly brackets to view all available variables, and choose the appropriate one. Enter all the numbers you want to call in the To field, separated with commas.

    • Once you’ve configured the node, click Validate to save the configuration.
    • Give the PHLO a name by clicking in the upper left, then click Save.

    Assign the PHLO to a Plivo number

    Once you’ve created and configured your PHLO, assign your PHLO to a Plivo number.

    • On the Numbers page of the console, under Your Numbers, click the phone number you want to use for the PHLO.
    • In the Number Configuration box, select PHLO from the Application Type drop-down.
    • From the PHLO Name drop-down, select the PHLO you want to use with the phone number, then click Update Number.

    Assign PHLO to a Plivo Number

    Test

    You can now call your Plivo phone number and see how the inbound call is forwarded.

    For more information about creating a PHLO application, see the PHLO Getting Started guide. For information on components and their variables, see the PHLO Components Library.

    More use cases

    We illustrate more than 20 use cases with code for both PHLO and API/XML on our documentation pages.

    Install Python, Sanic and the Plivo Python Server SDK

    You must set up and install Python and Plivo’s Python SDK to make your first call. Here’s how.

    Install Python

    Operating SystemInstructions
    macOS & LinuxTo see if you already have Python installed, run the command python --version in the terminal
    WindowsTo install Python on Windows follow the instructions listed here.

    Install Sanic and Plivo Python Package

    • Create a project directory, run the following command:

      $ mkdir mypythonapp
      
    • Change the directory to our project directory in the command line:

      $ cd mypythonapp
      
    • Install Sanic framework using pip

      $ pip install sanic
      
    • Install the SDK using pip

      pip install plivo
      

    We recommend that you use virtualenv to manage and segregate your Python environments, instead of using sudo with your commands and overwriting dependencies.

    Make your first Outbound Call

    Prerequisites

    This section will guide you through how to use Plivo APIs to make voice calls from your application. First, let’s make sure you meet these prerequisites before we dive into the code.

    • Plivo Auth Id and Auth Token: You will find your Plivo Auth Id and Auth Token on the home screen of your Plivo Console. Click here to sign-up for a Plivo account if you haven’t already!

      Find Your Auth Credentials on Plivo Console

    • Plivo Phone Number(Optional): Purchase numbers from the Numbers section of your Plivo Console and use the same as the caller ID for the outbound call. This number will also help you receive incoming calls as you must have a voice-enabled Plivo phone number to do the same. Please note that you can also purchase numbers using the Numbers API.

      Buy a New Plivo Number

    • Answer Url: When a call is answered by the destination_number, you can control the call flow with the help of the answer_url set in the API request. Plivo will invoke the answer_url specified as soon as the call is answered and expect a valid XML response with instructions to handle the call. For example, you can use https://s3.amazonaws.com/static.plivo.com/answer.xml as answer_url to test your first outgoing call. The XML response of this is:

      <Response> 
      <Speak>Congratulations! You've made your first outbound call!</Speak> 
      </Response>
      

      As you can tell, the XML above holds instructions to say ‘Congratulations! You’ve made your first outbound call!’ to the callee. You can find the entire list of Plivo XML verbs and their details in the XML Reference section of the website here.

    Now, create a file called main.py and paste the following code.

    Code

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    
    import plivo
    from plivo import plivoxml
    from sanic import Sanic
    from sanic.response import text
    
    app = Sanic('Plivo Voice App')
    
    
    @app.route('/outbound', methods=['POST', 'GET'])
    async def make_call(request):
      client = plivo.RestClient('<auth_id>','<auth_token>')
      response = client.calls.create(
          from_='+14151234567',
          to_='+14157654321',
          answer_url='http://s3.amazonaws.com/static.plivo.com/answer.xml',
          answer_method='GET', )
      print(response)
      return text(response, content_type="text/json")
    
    if __name__ == "__main__":
      app.run(host="0.0.0.0", port=8000)
    
    Note:
    • Replace the placeholders auth_id & auth_token with your credentials from Plivo Console.
    • We recommend that you store your credentials in the auth_id & auth_token environment variables, so as to avoid the possibility of accidentally committing them to source control. If you do this, you can initialize the client with no arguments and it will automatically fetch them from the environment variables
    • You can use os module(os.environ) to store environment variables and fetch them while initializing the client.
    • Replace the placeholder +14151234567 with the Phone number which you have purchased and +14157654321 with the phone number you will be making calls to.
    • Both +14151234567 and +14157654321 should be in E.164 format

    Save the file and use the below command to run your code.

    $ python main.py
    

    And you should see your basic server app for outbound calls in action on http://localhost:8000/outbound/

    Note: If you are using a Plivo Trial account for this example, you can only make calls to phone numbers that have been verified with Plivo. Phone numbers can be verified at the Sandbox Numbers page.

    Receive Your First Inbound Call

    Prerequisites

    In addition to having at least one voice-enabled Plivo phone number that is needed to receive incoming calls (as was mentioned earlier), you need the following:

    Answer URL & Callback URLs

    When a call is received on a Plivo voice-enabled number, you can control the call flow by declaring an answer URL for your Plivo application associated with that Plivo phone number. Plivo will invoke the answer URL specified and expect a valid XML response to handle the call.

    Notice how the concept of Answer URLs applies to both outbound API calls as well as incoming calls to your Plivo numbers. In the outbound API call example above, we specified the answer URL along with the make call API request, whereas in the case of incoming calls to Plivo numbers, the answer URL is specified in the Plivo application associated with the phone number.

    In addition to requests to the answer URL, Plivo initiates HTTP requests to your application server through the course of a call based on the specific XML elements in your answer XML. Such requests can be broadly classified into two categories:

    Action URL requests: XML instructions to carry forward the call are expected in response to these requests. These requests are typically invoked at the end of an XML element’s execution. For example: when an IVR input is received from the caller during a GetInput XML execution.

    Callback URL requests: No XML instructions are expected in response to these requests. Such requests serve as webhooks to notify your application server of important events through the course of an XML element’s execution. For example: when a conference participant is muted or unmuted.

    Web Server

    To be able to host Answer and Callback URLs and to be able to provide valid XMLs and accept notifications on these URLs respectively, you need to host a webserver at your end.

    Set up a Sanic server for Incoming Calls & Callbacks

    In this section, we’ll walk you through how to set up a Sanic server in under five minutes and start handling incoming calls & callbacks.

    Use the following code snippet to start a local server.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    
    import plivo
    from plivo import plivoxml
    from sanic import Sanic
    from sanic.response import text
    
    app = Sanic('Plivo Voice App')
    
    
    @app.route('/outbound', methods=['POST', 'GET'])
    async def make_call(request):
      .......
      .......
    
    
    @app.route('/inbound', methods=['POST', 'GET'])
    async def receive_call(request):
        # Generate a Speak XML with the details of the text to play on the call.
        response = (plivoxml.ResponseElement()
                    .add(plivoxml.SpeakElement('Hello, you just received your first call')))
        return text(response.to_string(), content_type="text/xml")
    
    if __name__ == "__main__":
      app.run(host="0.0.0.0", port=8000)
    

    Save this code in the main.py file after the make_call function block. To run this file on the server use the following command:

    $ python main.py
    

    And you should see your basic server app for outbound calls in action on http://localhost:8000/inbound/

    Exposing your local server to the internet

    To receive Incoming Calls and to handle callbacks, your local server should be able to connect with Plivo API service, Ngrok is a tunneling software used to expose a web server running on your local machine to the internet. Using Ngrok you can set webhooks which can talk to Plivo server.

    ngrok block diagram

    You can download and install ngrok from here. Follow the detailed configuration instructions to get started.

    Run ngrok on the port which currently hosts your application. For example, if your port number is 8000, run the following command:

    ./ngrok http 8000
    

    This will give you a UI with links that look like ngrok.io/* which you can use to access your local server using the public network.

    Ngrok CLI

    You can check the app in action on https://dc141ed7fbb9.ngrok.io/inbound/ and check the XML response as shown below:

    Sample XML response

    Create a Plivo Application

    1. Create an Application by visiting the Application Page and click on New Application. You can also use Plivo’s Application API.
    2. Give your application a name. Let’s call it Receive_call. Enter your server URL (e.g. http://example.com/receive_call/) in the Answer URL field and set the method as POST. See our Application API docs to learn how to modify your application through our APIs.
    3. Click on Create Application to save your application.

    Create Application

    Assign a Plivo number to your app

    1. Navigate to the Numbers page and select the phone number you want to use for this app.
    2. Select Receive Call (name of the app) from the Plivo App dropdown list.
    3. Click on Update to save.

    Assign Phone Number to Receive Call App

    Test and validate

    Make a call to your Plivo number using a regular mobile phone. Plivo will send a request to your Answer URL requesting for a valid XML response and process the call. Meanwhile, the parameters listed in the XML Request - call status documentation will also be sent to your server.

    Forward an Incoming call

    To forward an incoming call, you need to use Dial XML.

    • You should set up the dial XML document in your server
    • URL of the dial XML in your server has to be set up as the answer_url of the app assigned to the Plivo number.
    • During an incoming call to your Plivo number, Plivo will send a request to the answer_url expecting a valid XML to process the incoming call.
    • As the response would be a dial XML, the call will be forwarded to the number defined in the XML response.
    Note: The phone number must be a Plivo phone number that is voice-enabled. You can purchase a Plivo number from the Buy Numbers tab on your Plivo Console and filter the phone numbers by selecting voice in the features option to buy voice-enabled numbers.

    Code

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    
    import plivo
    from plivo import plivoxml
    from sanic import Sanic
    from sanic.response import text
    
    app = Sanic('Plivo Voice App')
    
    
    @app.route('/outbound', methods=['POST', 'GET'])
    async def make_call(request):
      .......
      .......
    
    
    @app.route('/inbound', methods=['POST', 'GET'])
    async def receive_call(request):
      .......
      .......
    
    
    @app.route('/forward', methods=['POST', 'GET'])
    async def forward_call(request):
        response = plivoxml.ResponseElement()
        response.add(
            plivoxml.DialElement().add(
                plivoxml.NumberElement('15671234567')))
        return text(response.to_string(), content_type="text/xml")
    
    if __name__ == "__main__":
      app.run(host="0.0.0.0", port=8000)
    
    Note: Create an application in the Plivo console with your Server URL in the answer_url field and assign the app to a Plivo number.

    Test and validate

    Save this code in the main.py file after the receive_call function block. To run this file on the server use the following command:

    $ python main.py
    

    And you should see your basic server app for outbound calls in action on http://localhost:8000/forward/

    Make a call to your Plivo number using a regular mobile phone. Plivo will send a request to your Answer URL requesting for a valid XML response and process the call. Once Plivo receives the dial XML response, the call will be forwarded to the number defined in the XML. Meanwhile, the parameters listed in the XML Request - call status documentation will also be sent to your server.