Get Started with Python using Django Framework

    Sign up for a Plivo Account

    When you sign up with Plivo, you will start with a free trial account to experiment with and learn about our services. This free trial account comes with free credits. If you wish to continue with our service, you can add more credits and purchase a number by clicking here. Add a number and credits to your account to start testing the full range of our voice and SMS service features.

    Sign up here to get your free Plivo account today.

    Follow these steps to successfully sign up for a free trial account:

    1. Sign up with your work email address
    2. Check your inbox for an activation email from Plivo. Click on the link in the email to activate your account.
    3. Enter your mobile number to complete the phone verification step.

    Sign up with your work email address

    Sign up with email addres

    If you have any issues creating a Plivo account, please reach out to our Support Team for assistance.

    Install Django and Plivo Python SDK

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

    • To create a project directory, run the following command:
      $ mkdir mydjangoapp
      
    • Change the directory to our project directory in the command line:
      $ cd mydjangoapp
      
    • Install the SDK using pip
      $ pip3 install django==3.1.1 plivo==4.10.0
      

    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!

      credentials

    • Plivo Phone Number(Optional): You can 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 New 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.

    Create a Django Project

    As we have Django and Plivo Python dependencies installed, we can use them to create a new Django project. As the initial step, using Django-admin we can auto-generate code in the Django folder structure. Use the below command to start your Django project.

    $ django-admin startproject VoiceProj
    

    This will create a VoiceProj directory in your mydjangoapp directory.

    Create a Django app

    Change the directory to our newly created project directory, i.e, VoiceProj directory and run the below command to create a Django app for outbound call.

    $ python3 manage.py startapp outboundcall
    

    This will create a outboundcall directory in your VoiceProj directory. You have to open the outboundcall/views.py file and add the following code:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    
    from django.conf import settings                                                                                                                                                      
    from django.http import HttpResponse
    from django.views.decorators.csrf import csrf_exempt
    import plivo
    
    @csrf_exempt
    def outboundcall_response(request):
    
       client = plivo.RestClient(settings.PLIVO_AUTH_ID, settings.PLIVO_AUTH_TOKEN)
       response = client.calls.create(
           from_=settings.PLIVO_NUMBER,
           to_='the_destination_number',
           answer_url='http://s3.amazonaws.com/static.plivo.com/answer.xml',
           answer_method='GET', )
       return HttpResponse(response)
    
    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 have to store `PLIVO_AUTH_ID`, `PLIVO_AUTH_TOKEN`,` `and `PLIVO_NUMBER` as environment variables.
    • Open settings.py in the Django project and use os module to add `PLIVO_AUTH_ID`, `PLIVO_AUTH_TOKEN`, and `PLIVO_NUMBER` as environment variables. For example, `PLIVO_AUTH_ID = os.getenv("PLIVO_AUTH_ID")`.
    • Replace the placeholder the_destination_number</mark> with the phone number you will be making calls to.
    • Both PLIVO_NUMBER and the_destination_number should be in E.164 format, for example +15671234567.

    Add a Route

    Now, you need to add a route to the above view. Create a file outboundcall/urls.py and paste the below code:

    1
    2
    3
    4
    5
    
    from django.conf.urls import url
    from . import views
    urlpatterns = [
       url(r'^$', views.outboundcall_response, name='outboundcall'),
    ]
    

    Next is to add a route for the outboundcall app into the urls.py of your project, VoiceProj. Navigate to VoiceProj/urls.py and add this code:

    1
    2
    3
    4
    5
    6
    7
    
    from django.conf.urls import include, url
    from django.contrib import admin
    
    urlpatterns = [
       url(r'^outboundcall/', include('outboundcall.urls')),
       url(r'^admin/', admin.site.urls),
       ]
    

    Test & Validate

    Now the outboundcall Django app is ready, you can use the below command to initiate your first outbound using Django and Plivo Python SDK.

    $ python3 manage.py runserver
    

    Your local development server will be started and you can test the outboundcall app via the URL http://127.0.0.1:8000/outboundcall/.

    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 Django Server for incoming calls & callbacks

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

    Create a Django app

    Change the directory to our project directory, i.e, VoiceProj directory and run the below command to create a Django app to handle incoming calls.

    $ python3 manage.py startapp receivecall
    

    This will create a receivecall directory in your VoiceProj directory. You have to open the receivecall/views.py file and add the following code:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
    from django.conf import settings                                                                                                                                                      
    from django.http import HttpResponse
    from django.views.decorators.csrf import csrf_exempt
    from plivo import plivoxml
    
    @csrf_exempt
    def receivecall_response(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 HttpResponse(response.to_string(), content_type='text/xml')
    

    Add a Route

    Now, you need to add a route to the above view. Create a file receivecall/urls.py and paste the below code:

    1
    2
    3
    4
    5
    
    from django.conf.urls import url
    from . import views
    urlpatterns = [
       url(r'^$', views.receivecall_response, name='receivecall'),
    ]
    

    Next is to add a route for the receivecall app into the urls.py of your project, VoiceProj. Navigate to VoiceProj/urls.py and add this code:

    1
    2
    3
    4
    5
    6
    7
    8
    
    from django.conf.urls import include, url
    from django.contrib import admin
    
    urlpatterns = [
       url(r'^outboundcall/', include('outboundcall.urls')),
       url(r'^receivecall/', include('receivecall.urls')),
       url(r'^admin/', admin.site.urls),
       ]
    

    Run the App

    Now the receivecall Django app is ready, you can use the below command to basic server app in action on http://127.0.0.1:8000/receivecall/.

    $ python3 manage.py runserver
    

    Exposing your local server to the internet

    To receive Incoming Calls and to handle callbacks, your local server should be able to connect with the 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 the Plivo server.

    ngrok block diagram

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

    Note: Before starting Ngrok service, you need to add ngrok in the allowed hosts list in settings.py file in your project.
    ALLOWED_HOSTS = ['.ngrok.io']
    

    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://6ea358b0f703.ngrok.io/receivecall/ and check the XML response as shown below:

    Sample XML response

    Create an Application on Plivo Console

    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 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

    Create a Django app

    Change the directory to our project directory, i.e, VoiceProj directory and run the below command to create a Django app to forward incoming calls.

    $ python3 manage.py startapp forwardcall
    

    This will create a forwardcall directory in your VoiceProj directory. You have to open the forwardcall/views.py file and add the following code:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    
    from django.conf import settings                                                                                                                                                      
    from django.http import HttpResponse
    from django.views.decorators.csrf import csrf_exempt
    from plivo import plivoxml
    
    @csrf_exempt
    def forwardcall_response(request):
    
       # Generate a Dial XML forward the incoming call.
       response = plivoxml.ResponseElement()
        response.add(
            plivoxml.DialElement().add(
                plivoxml.NumberElement('15671234567')))
       return HttpResponse(response.to_string(), content_type='text/xml')
    

    Add a Route

    Now, you need to add a route to the above view. Create a file forwardcall/urls.py and paste the below code:

    1
    2
    3
    4
    5
    
    from django.conf.urls import url
    from . import views
    urlpatterns = [
       url(r'^$', views.forwardcall_response, name='forwardcall'),
    ]
    

    Next is to add a route for the forwardcall app into the urls.py of your project, VoiceProj. Navigate to VoiceProj/urls.py and add this code:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    from django.conf.urls import include, url
    from django.contrib import admin
    
    urlpatterns = [
       url(r'^outboundcall/', include('outboundcall.urls')),
       url(r'^receivecall/', include('receivecall.urls')),
       url(r'^forwardcall/', include('forwardcall.urls')),
       url(r'^admin/', admin.site.urls),
       ]
    

    Run the App

    Now the forwardcall Django app is ready, you can use the below command to basic server app in action on http://127.0.0.1:8000/forwardcall/.

    $ python3 manage.py runserver
    

    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

    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.