Record a call using API

The Record API can record live calls at any time during the call and returns the URL of a file containing the audio recording. This API also lets you stop the recording at any point. The ability to initiate and stop recordings can be useful support and sales calls where reviews can help improve business processes.

POST https://api.plivo.com/v1/Account/{auth_id}/Call/{call_uuid}/Record/

In this tutorial, you will learn to build an app that when called, prompts the caller to “Press 1 to record this call”. Once the caller presses 1, the Record API will begin recording. Once the call is hung up, the Record API will return a URL of the recorded audio file. This app is preset to wait 7 seconds for the user to input “1” or the call will be hung up. In the event of an incorrect input, the app will return “Wrong Input”.

Prerequisites

  1. Sign up for a free Plivo trial account.
  2. Check out our Helper Libraries page and install the right helper based on the programming language you want to use.
  3. A phone number is required to receive calls. You can buy a Plivo phone number in over 20+ countries through the Buy Numbers tab on your Plivo account UI. Check the Voice API coverage page for all the supported countries.
  4. Use a web hosting service to host your web application. There are many inexpensive cloud hosting providers that you can use for just a few dollars a month. Follow the instructions of your hosting provider to host your web application.

Set up a Web Server

Let’s assume your web server is located at myvoiceapp.com. Below is a snippet to set up a route on your webserver. Lets call it, record_api. Now when we send an HTTP request to myvoiceapp.com/record_api this route will be invoked. This route will then return an XML that will read out a message for the caller and when 1 is pressed, which will invoke the record_api_action route and initiate the Record API. You will now have to configure this URL in your Plivo application.

Note: For PHP, the route will be myvoiceapp.com/record_api.php
  1. Copy the relevant code below into a text file and save it. Lets call it, record_api.
    Note: Make sure to use the appropriate file extention for your code (e.g., record_api.py for Python).
  2. Now that you have the code, you will need to expose your server to the public Internet. This way, Plivo will know where to find your app when a particular phone number is dialed. Moving forward, we will assume that your app is available at myvoiceapp.com.

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import plivo, plivoxml
from flask import Flask, Response, request, url_for

app = Flask(__name__)

# When the call is answered, a text is played which prompts the user to press 1 to record the call.
# Once the digit is pressed, the Record API request is made and the recording starts.

@app.route('/record_api/', methods=['POST', 'GET'])
def record_api():

    response = plivoxml.Response()
    getdigits_action_url = url_for('record_action', _external=True)
    getDigits = plivoxml.GetDigits(action=getdigits_action_url,
            method='GET', timeout=7, numDigits=1,
            retries=1, redirect='false')
    getDigits.addSpeak("Press 1 to record this call")
    response.add(getDigits)
    params = {'length' : "30"}
    response.addWait(**params)
    print response.to_xml()
    return Response(str(response), mimetype='text/xml')

# The Record API is invoked by the Get Digits action URL

@app.route('/record_api_action/', methods=['POST', 'GET'])
def record_action():
    digit = request.args.get('Digits')
    call_uuid = request.args.get('CallUUID')
    auth_id = "Your AUTH_ID"
    auth_token = "Your AUTH_TOKEN"
    print "Call UUID is : %s " % (call_uuid)
    print "Digit pressed is : %s " % (digit)
    p = plivo.RestAPI(auth_id, auth_token)
    if digit == "1":
        params = {'call_uuid' : call_uuid} # ID of the call
        response = p.record(params)
    else :
        print "Wrong Input"
        response = "Error"
    print str(response)
    return Response(str(response), mimetype='text/plain')

if __name__=='__main__':
    app.run(host='0.0.0.0',debug='True')
 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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
require 'rubygems'
require 'sinatra'
require 'plivo'
include Plivo

get '/record_api/' do
    r = Response.new()
    getdigits_action_url = "http://www.myvoiceapp.com/record_api_action/"
    params = {
        'action' => getdigits_action_url, # The URL to which the digits are sent.
        'method' => 'GET', # Submit to action URL using GET or POST.
        'timeout' => '7', # Time in seconds to wait to receive the first digit.
        'numDigits' => '1', # Maximum number of digits to be processed in the current operation.
        'retries' => '1', # Indicates the number of attempts the user is allowed to input digits
        'redirect' => 'false' # Redirect to action URL if true. If false,only request the URL and continue to next element.
    }
    getDigits = r.GetDigits(params)
    getDigits.addSpeak("Press 1 to record this call")

    # Time to wait in seconds
    params = {'length' => "30"}
    r.addWait(params)

    puts r.to_xml()
    content_type 'text/xml'
    return r.to_s()
end

get '/record_api_action/' do
    digit = params[:Digits]
    call_uuid = params[:CallUUID]

    AUTH_ID = "Your AUTH_ID"
    AUTH_TOKEN = "Your AUTH_TOKEN"

    p = RestAPI.new(AUTH_ID, AUTH_TOKEN)

    if (digit == "1")
        params = {'call_uuid' => call_uuid} # ID of the call
        response = p.record(params)
        print response
    else
        print "Wrong Input"
    end
end
 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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
var util = require('util');
var express = require('express');
var app = express();
var plivo = require('plivo');

app.set('port', (process.env.PORT || 5000));

app.all('/record_api/', function (req, res) {
    var getdigits_action_url = util.format("http://%s/record_api_action/", req.get('host'));
    var params = {
        'action': getdigits_action_url, // The URL to which the digits are sent.
        'method': 'GET', // Submit to action URL using GET or POST.
        'timeout': '7', // Time in seconds to wait to receive the first digit.
        'numDigits': '1', // Maximum number of digits to be processed in the current operation.
        'retries': '1', // Indicates the number of attempts the user is allowed to input digits
        'redirect': 'false' // Redirect to action URL if true. If false, only request the URL and continue to next element.
    };
    var response = plivo.Response();
    var getDigits = response.addGetDigits(params);
    getDigits.addSpeak("Press 1 to record this call");

    // Time to wait in seconds
    params = {'length': "30"};
    response.addWait(params);

    console.log(response.toXML());
    res.set({'Content-Type': 'text/xml'});
    res.send(response.toXML());
});

app.all('/record_api_action/', function (req, res) {
    // Plivo passes the digit captured by the xml produced by /record_api/ function as the parameter Digits
    var digit = req.param('Digits');
    // CallUUID parameter is automatically added by Plivo when processing the xml produced by /record_api/ function
    var call_uuid = req.param('CallUUID');

    var p = plivo.RestAPI({
        "authId": "Your AUTH_ID",
        "authToken": "Your AUTH_TOKEN"
    });

    if (digit === "1") {
        // ID of the call
        var params = {'call_uuid':call_uuid};
        // Here we make the actual API call and store the response
        var response = p.record(params);
        console.log(response);
    } else
        console.log("Wrong Input");
});

app.listen(app.get('port'), function() {
    console.log('Node app is running on port', app.get('port'));
});
 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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<!-- record_api.php -->

<?php
    require 'vendor/autoload.php';
    use Plivo\Response;
    $r = new Response();
    $getdigits_action_url = "http://www.myvoiceapp.com/record_api_action.php";
    $params = array(
        'action' => $getdigits_action_url, # The URL to which the digits are sent.
        'method' => 'GET', # Submit to action URL using GET or POST.
        'timeout' => '7', # Time in seconds to wait to receive the first digit.
        'numDigits' =>  '1', # Maximum number of digits to be processed in the current operation.
        'retries' => '1', # Indicates the number of attempts the user is allowed to input digits
        'redirect' => 'false' # Redirect to action URL if true. If false,only request the URL and continue to next element.
    );
    $getDigits = $r->addGetDigits($params);
    $getDigits->addSpeak("Press 1 to record this call");

    $waitparam = array('length' => '10');
    $r->addWait($waitparam);
    Header('Content-type: text/xml');
    echo($r->toXML());
?>

<!--record_api_action.php-->

<?php
    require 'vendor/autoload.php';
    use Plivo\RestAPI;
    $digit = $_REQUEST['Digits'];
    $uuid = $_REQUEST['CallUUID'];
    print("Digit : $digit");
    print("Call UUID : $uuid");
    $auth_id = "Your AUTH_ID";
    $auth_token = "Your AUTH_TOKEN";
    $p = new RestAPI($auth_id, $auth_token);
    if($digit == "1") {
        $params = array('call_uuid' => $uuid); # ID of the call
        $response = $p->record($params);
        print("URL : {$response['response']['url']}");
        print("Recording ID : {$response['response']['recording_id']}");
        print("API ID : {$response['response']['api_id']}");
        print("Message : {$response['response']['message']}");
    } else {
        print("Wrong Input");
    }

?>
  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
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
// recordApi.java
package plivoexample;

import java.io.IOException;
import com.plivo.helper.exception.PlivoException;
import com.plivo.helper.xml.elements.GetDigits;
import com.plivo.helper.xml.elements.PlivoResponse;
import com.plivo.helper.xml.elements.Speak;
import com.plivo.helper.xml.elements.Wait;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class recordUsingApi extends HttpServlet {
    private static final long serialVersionUID = 1L;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        PlivoResponse response = new PlivoResponse();
        GetDigits gd = new GetDigits();
        gd.setAction("http://www.myvoiceapp.com/record_api_action/"); // The URL to which the digits are sent
        gd.setMethod("GET"); // Submit to action URL using GET or POST.
        gd.setTimeout(7); // Time in seconds to wait to receive the first digit.
        gd.setNumDigits(1); // Maximum number of digits to be processed in the current operation.
        gd.setRetries(1); // Indicates the number of attempts the user is allowed to input the digits
        gd.setRedirect(false); // Redirect to action URL if true. If false,only request the URL and continue to next element.

        Speak spk = new Speak("Press 1 to record this call");
        Wait wait = new Wait();
        wait.setLength(30); // Time to wait in seconds

        try {
            gd.append(spk);
            response.append(gd);
            response.append(wait);
            System.out.println(response.toXML());
            resp.addHeader("Content-Type", "text/xml");
            resp.getWriter().print(response.toXML());;
        } catch (PlivoException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        String port = System.getenv("PORT");
        if(port==null) port = "8000";
        Server server = new Server(Integer.valueOf(port));
        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        server.setHandler(context);
        context.addServlet(new ServletHolder(new recordUsingApi()),"/record_api/");
        context.addServlet(new ServletHolder(new recordApiAction()),"/record_api_action/");
        server.start();
        server.join();
    }
}

//recordApiAction.java
package plivoexample;

import java.io.IOException;
import java.util.LinkedHashMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.plivo.helper.api.client.RestAPI;
import com.plivo.helper.api.response.response.Record;
import com.plivo.helper.exception.PlivoException;

public class recordApiAction extends HttpServlet {
    private static final long serialVersionUID = 1L;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        String digit = req.getParameter("Digits");
        String call_uuid = req.getParameter("CallUUID");
        System.out.println("Digit : " + digit + " Call UUID : " + call_uuid);
        resp.getWriter().print("Digit : " + digit + " Call UUID : " + call_uuid);

        String auth_id = "Your AUTH_ID";
        String auth_token = "Your AUTH_TOKEN";
        RestAPI api = new RestAPI(auth_Id, auth_Token, "v1");

        if(digit.equals("1")) {
            LinkedHashMap<String, String> parameters = new LinkedHashMap<String, String>();
            parameters.put("call_uuid",call_uuid);
            try {
                Record record = api.record(parameters);
                System.out.println(record);
            } catch (PlivoException e) {
                System.out.println(e.getLocalizedMessage());
            }
        } else {
            System.out.println("Wrong Input");
        }
    }
}
 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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
using System;
using System.Collections.Generic;
using System.Diagnostics;
using RestSharp;
using Plivo.XML;
using Plivo.API;
using Nancy;

namespace record_using_api
{
    public class Program : NancyModule
    {
        public Program()
        {
            Get["/record_api/"] = x =>
            {
                Plivo.XML.Response resp = new Plivo.XML.Response();
                String getdigits_action_url = "http://www.myvoiceapp.com/record_api_action/";
                GetDigits gd = new GetDigits("", new Dictionary<string, string>()
                {
                    {"action",getdigits_action_url}, // The URL to which the digits are sent
                    {"method","GET"}, // Submit to action URL using GET or POST.
                    {"timeout","7"}, // Time in seconds to wait to receive the first digit.
                    {"numDigits","1"}, // Maximum number of digits to be processed in the current operation.
                    {"retries","1"}, // Indicates the number of attempts the user is allowed to input the digits
                    {"redirect","false"} // Redirect to action URL if true. If false,only request the URL and continue to next element.
                });

                gd.AddSpeak("Press 1 to record this call", new Dictionary<string, string>());
                resp.Add(gd);
                resp.AddWait(new Dictionary<string, string>()
                {
                    {"length","30"} // Time to wait in seconds
                });

                Debug.WriteLine(resp.ToString());

                var output = resp.ToString();
                var res = (Nancy.Response)output;
                res.ContentType = "text/xml";
                return res;
            };

            Get["/record_api_action/"] = x =>
            {
                String digits = Request.Query["Digits"];
                String uuid = Request.Query["CallUUID"];
                Debug.WriteLine("Digit pressed : {0}, Call UUID : {1}", digits, uuid);

                if (digits == "1") {
                    string auth_id = "Your AUTH_ID";
                    string auth_token = "Your AUTH_TOKEN";
                    RestAPI plivo = new RestAPI(auth_id, auth_token);

                    IRestResponse<Plivo.API.Record> resp = plivo.record(new Dictionary<string, string>()
                    {
                        { "call_uuid", uuid } // ID of the call
                    });

                    Debug.WriteLine(resp.Content);
                } else {
                    Debug.WriteLine("Invalid");
                }

                return "OK";
            };
        }
    }
}

Create an Application

  1. Create an Application by visiting the Application Page and click on New Application or by using Plivo’s Application API.
  2. Give your application a name. Lets call it Record API. Enter your server URL (e.g., http://www.myvoiceapp.com/record_api) 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 Record Call 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 Record API (name of the app) from the Plivo App dropdown list.
  3. Click on Update to save.

Create Text to Speech Application

If you don’t have a number, go to the Buy Number page to purchase a Plivo phone number.

SMS Phone Number Search

Test it out

When you call the Plivo phone number you assigned to this app, Plivo will answer and say “Press 1 to record this call”. Plivo will then wait a maximum of 7 seconds for the user to press 1. Once the caller presses 1, the Record API will begin recording. Once the call is hung up, the Record API will return a URL of the recorded audio file.

Sample XML

<Response>
    <GetDigits redirect="false" retries="1" method="GET" numDigits="1" action="http://myvoiceapp.com/record_api_action" timeout="7">
        <Speak>Press 1 to record this call</Speak>
    </GetDigits>
    <Wait length="10"/>
</Response>

Sample Response

Digit : 1 Call UUID is : 2a2875b6-9592-11e4-8b35-cd90edc77fa9

(202, {
        u'url': u'http://s3.amazonaws.com/recordings_2013/67673232-9594-11e4-baad-842b2b17453e.mp3',
        u'recording_id': u'16963644-9594-11e4-baad-842b2b17453e',
        u'message': u'call recording started',
        u'api_id': u'16847e54-9594-11e4-b423-22000ac8a2f8'
    }
)

Next Step

Learn how to screen an incoming call.

  1. Make an Outbound Call
  2. Play a Text-to-speech Message
  3. Connect Call to a Second Person
  4. Greet Caller by Name
  5. Play MP3/WAV Audio to Caller
  6. Hangup Using API
  7. Receive Incoming Call
  8. Forward Incoming Call
  9. Record Using API
  10. Screen Incoming Call
  11. Reject incoming call
  12. Get Details of all Calls
  13. Get Details of a single Call
  14. Get Details of Live Calls
  15. Build an IVR Phone Menu
  16. Conference Call
  17. Call Forward
  18. SIP Endpoint (Direct-Dial)
  19. Inbound Trunk
  20. Outbound Trunk