Voice API

The Nexmo Voice API is the easiest way to build high-quality voice applications in the Cloud. With the Voice API you:

  • Build apps that scale easily with the web technologies that you are already using
  • Manage outbound and inbound calls in JSON with Nexmo Call Control Objects (NCCO)
  • Control the flow of your calls with a powerful set of call control features
  • Record and store inbound or outbound calls
  • Create simple conference or powerful enterprise features
  • Send text-to-speech messages in 23 languages with different genders and accents

A Voice app is associated with a virtual phone number, it contains the configuration and authentication information you need to securely communicate with Voice API. You authenticate requests to the Voice API with JSON Web Tokens that you generate from the private_key associated with your app.

Each Voice app represents the business logic you want to implement. For example, you create one app for your Interactive Voice Response system, and another to send text-to-speech messages to your users.

The following scripts show you how to create a Voice app. Once the voice app is created you can implement any Voice API functionality. To illustrate this, the script also sends a text-to-speech message to a phone number using a static NCCO.

The following code example shows you how to create a Voice app and send yourself a text-to-speech message:

  1. If you don't already have one, setup a Nexmo account.
  2. Use npm to install and setup the Nexmo CLI:
    #Install the Nexmo CLI:
    sudo npm install nexmo-cli -g
      #Nexmo CLI requires NodeJS 4 or above. If you do not have Node,
      #download the installer from https://nodejs.org/en/download/.
    #Configure the Nexmo CLI
    nexmo setup <api_key> <api_secret>
  3. Change phone_number, then run this script to make a text-to-speech Call:
    #This script assumes you have already installed Nexmo CLI
    #1. Set the phone number to call and the virtual number to call from
    #2. Set a Generic file name for the file holding the private key for this Application.
    #3. Check if you have an existing Voice API application. If not, create it.
      if [ -f "./application_id" ];
        application_id=`cat ./application_id`
        echo "  Ah, using the existing application: " $application_id
        application_info=`nexmo app:create "VoiceTTSCall" \
          https://example.com/ncco https://example.com/call_status \
          --type=voice \
        echo "  Ok, created a new application:" $application_info
        application_id=`echo ${application_info%%$'\n'*} | cut -d ' ' -f 3`
        echo $application_id > ./application_id
    #4. Generate a JWT to authenticate your request to the Voice API.
      APP_JWT="$(nexmo jwt:generate $private_key_file iat=`date +%s` application_id=$application_id)"
    #5. Set the payload for a text-to-speech Call to $phone_number.
              "type": "phone",
              "number": '$phone_number'
          "from": {
              "type": "phone",
              "number": '$virtual_number'
          "answer_url": ["https://www.example.com/call_sales.json"]
    #6. Make the Call.
      curl -X POST "https://api.nexmo.com/v1/calls" \
        -H "Authorization: Bearer $JWT" \
        -H "Content-Type: application/json" \
        -d "$payload"

The following code example shows you how to create a Voice app and send yourself a text-to-speech message:

  1. If you don't already have one, setup a Nexmo account.
  2. Depending on the language you want to use, copy *voice_api_first_tts_call* to a local directory, <NEXMO_DIR>:
  3. In <NEXMO_DIR>, install the libraries used to generate a jwt:
    • PHP
      • lcobucci/jwt - composer require lcobucci/jwt
    • Python
      • Crypto - pip install pycrypto
      • Jose - pip install python-jose
      • Requests - pip install requests
    • Ruby
      • Ruby-jwt sudo gem install jwt
  4. In voice_api_first_tts_call, set the following parameters:
    $nexmo_key = "API_KEY";
    $nexmo_secret = "API_SECRET";
    //Leave $application_id blank unless you have already created an application
    $application_id = "";
    //If you add an application ID here, add the private key in a file with the
    //same name as the application ID in  the same directory as this script.
    //Change this to the phone number to call
    $phone_number_to_call = "";
  5. Run voice_api_first_tts_call:
    • PHP - php voice_api_first_tts_call.php
    • Python - python voice_api_first_tts_call.py
    • Ruby - ruby voice_api_first_tts_call.rb
  6. The following PHP code samples show the workflow followed by the scripts:
    1. Set the base URL for the Voice API endpoints:
       * The base URL for Nexmo endpoints.
      $base_url = 'https://api.nexmo.com' ;
      $version = '/v1';
      $action = '';
    2. Create a Voice app:
       echo ("Can't see an application, let's create one for you.\n\n");
          $action = '/applications/?';
          $url = $base_url . $version . $action . http_build_query([
                  'api_key' =>  $nexmo_key,
                  'api_secret' => $nexmo_secret,
                  'name' => 'First Voice API Call',
                  'type' => 'voice',
                  'answer_url' => 'https://example.com/ncco',
                  'event_url' => 'https://example.com/call_status'
    3. Saves the private_key associated with your app to a local file.
          if (strpos($header, '201')){
              $application = json_decode($body, true);
              echo ("Saving your private key to a local file.\n\n");
              $private_key = preg_replace( "/RSA PRIVATE KEY/", "PRIVATE KEY", $application['keys']['private_key']);
              file_put_contents($application_id, $private_key );
    4. Uses the private key to generate a JWT:
       date_default_timezone_set('UTC');    //Set the time for UTC + 0
          $key = file_get_contents($keyfile);  //Retrieve your private key
          $signer = new Sha256();
          $privateKey = new Key($key);
          $jwt = (new Builder())->setIssuedAt(time() - date('Z')) // Time token was generated in UTC+0
          ->set('application_id', $application_id) // ID for the application you are working with
          ->setId( base64_encode( mt_rand (  )), true)
          ->sign($signer,  $privateKey) // Create a signature using your private key
          ->getToken(); // Retrieves the JWT
    5. Adds the JWT to the request headers:
      $headers =  array('Content-Type: application/json', "Authorization: Bearer " . $jwt ) ;
    6. Creates the payload to create the call:
      $payload = "{
              \"type\": \"phone\",
              \"number\": \"$phone_number_to_call\"
          \"from\": {
              \"type\": \"phone\",
              \"number\": \"$virtual_number\"
          \"answer_url\": [\"https://nexmo-community.github.io/ncco-examples/first_call_talk.json\"]
      The NCCO requested in the payload looks like:
              "action": "talk",
              "voiceName": "Russell",
              "text": "Hi, this is Russell. You are listening to a text-to-speech Call made with Nexmo's Voice API"
    7. Makes a request to the Voice API call endpoint:
      $action = '/calls';
      //Create the request
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $base_url . $version . $action);
  7. You receive a text-to-speech call at phone_number_to_call.

After you have run this script, try streaming an audio file to a phone number. To do this:

  1. Set application_id to the ID of the application you have just created.
  2. change the value of answer_url to https://nexmo-community.github.io/ncco-examples/first_call_speech.json and run the script again.

The following code example shows you how to create a Voice app and send yourself a text-to-speech message:

  1. If you don't already have one, setup a Nexmo account.
  2. Install the Nexmo Client Library for Node.js:
    $ npm install nexmo
  3. Include the library and create a new instance of the Nexmo client:
    var Nexmo = require('nexmo');
    var nexmo = new Nexmo({
      apiKey: API_KEY,
      apiSecret: API_SECRET
  4. Create a new Application and save the private key returned by Nexmo in the file appId:
      'First Voice App',
      function(err, res) {
        var appId = res.id;
        var privateKey = res.keys.private_key;
        var privateKeyFile = __dirname + '/' + appId;
        require('fs').writeFileSync(privateKeyFile, privateKey);
        console.log('Private key written to', privateKeyFile)
  5. Create a new Nexmo client instance for the Application you just created:
    var Nexmo = require('nexmo');
    var appId = “The ID of the Application you just created” ;
    var privateKey = require('fs').readFileSync(__dirname + '/' + appId);
    var nexmo = new Nexmo({
        apiKey: API_KEY,
        apiSecret: API_SECRET,
        applicationId: appId,
        privateKey: privateKey
  6. Make your first Call using the Voice API. For this example use a predefined NCCO which sends a text-to-speech message:
            to: [{
              type: 'phone',
              number: 441632960960
            from: {
              type: 'phone',
              number: 441632960961
            answer_url: ['https://nexmo-community.github.io/ncco-examples/first_call_talk.json']
          function(err, res) {
            if(err) { console.error(err); }
            else { console.log(res); }

Note: You can use this application ID and private key for all the Voice API code examples in the documentation.

Previous   Next