RingCentral Business Analytics APIs Quick Start

Last updated: 2024-02-29Contributors
Edit this page

Calling the RingCentral API for the first time? We recommend you try out getting started experience.

In this quick start guide, we are going to access call performance data via using Java/C# or Node.JS based command line application.

Create app and obtain credentials

The first thing we need to do is create an app in the RingCentral Developer Console. This can be done quickly by clicking the "Create Call Performance Analytics App" button below. Just click the button, enter a name and description if you choose, and click the "Create" button. If you do not yet have a RingCentral account, you will be prompted to create one.

Create Analytics App

  1. Login or create an account if you have not done so already.
  2. Go to Console/Apps and click 'Create App' button.
  3. Select "REST API App" under "What type of app are you creating?" Click "Next."
  4. Under "Authentication" select "JWT auth flow"
  5. Under "Security" add the following permissions:
    • Analytics
  6. Under "Security" select "This app is private and will only be callable using credentials from the same RingCentral account."

Download and edit a .env file

Follow the instructions found in our guide to running Developer Guide code samples. Or:

  1. Download our env-template and save it as a file named .env.
  2. Edit your newly downloaded .env file, setting its variables with the proper values for the app you created above.
    • RC_CLIENT_ID - set to the Client ID of the app you created above
    • RC_CLIENT_SECRET - set to the Client Secret of the app you created above
    • RC_JWT - set to the JWT credential you created for yourself

Call the Analytics API

Create a Node.JS project

$ npm init

Install RingCentral JS SDK & dotenv library

$ npm install @ringcentral/sdk dotenv

Create and edit 'analytics.js' file

Create a file called analytics.js. Be sure the values in your .env file have been set properly.

const RC_SDK = require('@ringcentral/sdk').SDK
const path = require('path')
// Remember to modify the path of your .env file location!
require('dotenv').config({ path: path.resolve(__dirname, '../.env') })

// Instantiate the SDK and get the platform instance
var rcsdk = new RC_SDK({
    'server':       process.env.RC_SERVER_URL,
    'clientId':     process.env.RC_CLIENT_ID,
    'clientSecret': process.env.RC_CLIENT_SECRET
});
var platform = rcsdk.platform();

/* Authenticate a user using a personal JWT token */
platform.login({ 'jwt':  process.env.RC_JWT })

platform.on(platform.events.loginSuccess, function(e){
    read_analytics_aggregate_data()
});

platform.on(platform.events.loginError, function(e){
    console.log("Unable to authenticate to platform. Check credentials.", e.message)
    process.exit(1)
});

/*
  Read aggregate analytics data for a period of time and grouped by users
*/
async function read_analytics_aggregate_data(){
  try {
    let bodyParams = {
        grouping:{
          groupBy:"Users"
        },
        timeSettings:{
          timeZone: "America/Los_Angeles",
          timeRange:{
            // Change the "timeFrom" value accordingly so that it does not exceed 184 days from the current datetime
            // The specified time is UTC time. If you want the timeFrom and timeTo your local time, you have to convert
            // your local time to UTC time!
            timeFrom: "2023-01-01T00:00:00.000Z",
            timeTo: "2023-02-15T23:59:59.999Z"
          }
        },
        responseOptions:{
          counters:{
            allCalls:{
              aggregationType:"Sum"
            }
          }
        }
      }

    let queryParams = {
      perPage: 100
    }
    let endpoint = '/analytics/calls/v1/accounts/~/aggregation/fetch'
    var resp = await platform.post(endpoint, bodyParams, queryParams)
    var jsonObj = await resp.json()
    console.log(jsonObj)
  }catch(e){
    console.log(e.message)
  }
}

Run your code

You are almost done. Now run your script.

$ node analytics.js

Install RingCentral Python SDK and the dotnet library

$ pip install ringcentral python-dotenv

Create and edit analytics.py

Create a file called analytics.py. Be sure the values in your .env file have been set properly.

from ringcentral import SDK
import os,sys,json
from dotenv import load_dotenv
load_dotenv()

#
#  Read aggregate analytics data for a period of time and grouped by users
#
def read_analytics_aggregate_data():
  try:
    bodyParams = {
      'grouping': {
        'groupBy': "Users"
      },
      'timeSettings': {
        'timeZone': "America/Los_Angeles",
        'timeRange': {
          # Change the "timeFrom" value accordingly so that it does not exceed 184 days from the current datetime
          # The specified time is UTC time. If you want the timeFrom and timeTo your local time, you have to convert
          # your local time to UTC time!
          'timeFrom': "2023-01-01T00:00:00.000Z",
          'timeTo': "2023-02-15T23:59:59.999Z"
        }
      },
      'responseOptions':{
        'counters': {
          'allCalls': {
            'aggregationType': "Sum"
          }
        }
      }
    }

    queryParams = {
      'perPage': 100
    }

    endpoint = '/analytics/calls/v1/accounts/~/aggregation/fetch'
    resp = platform.post(endpoint, bodyParams, queryParams)
    jsonObj = resp.json_dict()
    print(json.dumps(jsonObj, indent=2, sort_keys=True))
  except Exception as err:
    sys.exit("Unable to read analytics aggregation ", err)

# Instantiate the SDK and get the platform instance
rcsdk = SDK( os.environ.get('RC_CLIENT_ID'),
             os.environ.get('RC_CLIENT_SECRET'),
             os.environ.get('RC_SERVER_URL') )
platform = rcsdk.platform()

# Authenticate a user using a personal JWT token
def login():
    try:
      platform.login( jwt=os.environ.get('RC_JWT') )
      read_analytics_aggregate_data()
    except Exception as e:
      sys.exit("Unable to authenticate to platform. Check credentials." + str(e))

login()

Run your code

You are almost done. Now run your script.

$ python analytics.py

Install RingCentral PHP SDK

$ curl -sS https://getcomposer.org/installer | php
$ php composer.phar require ringcentral/ringcentral-php vlucas/phpdotenv

Create and edit analytics.php

Create a file called analytics.php. Be sure the values in your .env file have been set properly.

<?php
// Remember to modify the path ./../ pointing to the location where the RingCentral SDK was installed and the .env file was saved!
require('./../vendor/autoload.php');
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . './../');
$dotenv->load();

# Instantiate the SDK and get the platform instance
$rcsdk = new RingCentral\SDK\SDK( $_ENV['RC_CLIENT_ID'],
                                  $_ENV['RC_CLIENT_SECRET'],
                                  $_ENV['RC_SERVER_URL'] );
$platform = $rcsdk->platform();

// Authenticate a user using a personal JWT token
try {
  $platform->login( [ "jwt" => $_ENV['RC_JWT'] ] );
  read_analytics_aggregate_data();
} catch (\RingCentral\SDK\Http\ApiException $e) {
  exit("Unable to authenticate to platform. Check credentials. " . $e->message . PHP_EOL);
}

/*
  Read aggregate analytics data for a period of time and grouped by users
*/
function read_analytics_aggregate_data() {
  global $platform;
  try{
    $bodyParams = array(
      'grouping' => array ('groupBy' => "Users"),
      'timeSettings' => array (
        'timeZone' => "America/Los_Angeles",
        'timeRange' => array (
          // Change the "timeFrom" value accordingly so that it does not exceed 184 days from the current date and time
          // The specified time is UTC time. If you want the timeFrom and timeTo your local time, you have to convert
          // your local time to UTC time!
          'timeFrom' => "2023-01-01T00:00:00.000Z",
          'timeTo' => "2023-02-15T23:59:59.999Z"
        )
      ),
      'responseOptions' => array (
        'counters' => array (
          'allCalls' => array (
            'aggregationType' => "Sum"
          )
        )
      )
    );

    $queryParams = array (
      'perPage' => 100
    );

    $endpoint = '/analytics/calls/v1/accounts/~/aggregation/fetch';
    $resp = $platform->post($endpoint, $bodyParams, $queryParams);
    print_r (json_encode($resp->json(), JSON_PRETTY_PRINT));
  }catch (\RingCentral\SDK\Http\ApiException $e) {
    print_r ('Error: ' . $e->getMessage() . PHP_EOL);
  }
}
?>

Run your code

You are almost done. Now run your script.

$ php analytics.php

Install RingCentral Ruby SDK

$ gem install ringcentral-sdk dotenv

Create and edit analytics.rb

Create a file called analytics.rb. Be sure the values in your .env file have been set properly.

require 'ringcentral'
require 'dotenv'
# Remember to modify the path of your .env file location!
Dotenv.load("./../.env")

#
#  Read aggregate analytics data for a period of time and grouped by users
#
def read_analytics_aggregate_data()
  begin
    bodyParams = {
        'grouping':{
          'groupBy':"Users"
        },
        'timeSettings':{
          'timeZone': "America/Los_Angeles",
          'timeRange': {
            # Change the "timeFrom" value accordingly so that it does not exceed 184 days from the current date and time
            # The specified time is UTC time. If you want the timeFrom and timeTo your local time, you have to convert
            # your local time to UTC time!
            'timeFrom': "2023-01-01T00:00:00.000Z",
            'timeTo': "2023-02-15T23:59:59.999Z"
          }
        },
        'responseOptions': {
          'counters': {
            'allCalls': {
              'aggregationType': "Sum"
            }
          }
        }
      }

    queryParams = {
      'perPage': 100
    }

    endpoint = '/analytics/calls/v1/accounts/~/aggregation/fetch'
    resp = $platform.post(endpoint, payload: bodyParams, params: queryParams)
    puts JSON.pretty_generate(resp.body)
  rescue StandardError => e
    puts (e)
  end
end

# Instantiate the SDK and get the platform instance
$platform = RingCentral.new( ENV['RC_CLIENT_ID'], ENV['RC_CLIENT_SECRET'], ENV['RC_SERVER_URL'] )

# Authenticate a user using a personal JWT token
def login()
  begin
    $platform.authorize(jwt: ENV['RC_JWT'])
    read_analytics_aggregate_data()
  rescue StandardError => e
    puts ("Unable to authenticate to platform. Check credentials." + e.to_s)
  end
end

login()

Run your code

You are almost done. Now run your script.

$ ruby analytics.rb

Create a C# project using Visual Studio

  • Choose Console Application .Net Core -> App
  • Select Target Framework .NET Core 2.1 or a higher version
  • Enter project name "AnalyticsQuickStart"
  • Add NuGet package RingCentral.Net (6.0.0) SDK
  • Save the .env file under your project folder. E.g. /AnalyticsQuickStart/bin/Debug/netcoreapp2.2/.env

Edit the file 'Program.cs'

using System;
using System.IO;
using System.Threading.Tasks;
using System.Collections.Generic;
using RingCentral;
using Newtonsoft.Json;
using dotenv.net;

namespace AnalyticsQuickStart {
  class Program {
    static RestClient restClient;

    static async Task Main(string[] args){
      try
      {
        DotEnv.Load();
        // Instantiate the SDK
        restClient = new RestClient(
            Environment.GetEnvironmentVariable("RC_CLIENT_ID"),
            Environment.GetEnvironmentVariable("RC_CLIENT_SECRET"),
            Environment.GetEnvironmentVariable("RC_SERVER_URL"));

        // Authenticate a user using a personal JWT token
        await restClient.Authorize( Environment.GetEnvironmentVariable("RC_JWT") );

        await read_analytics_aggregate_data();
      }
      catch (Exception ex)
      {
        Console.WriteLine(ex.Message);
      }
    }
    /*
      Read aggregate analytics data for a period of time and grouped by users
    */
    static private async Task read_analytics_aggregate_data()
    {
      try
      {
        var bodyParams = new AggregationRequest();
        bodyParams.grouping = new Grouping();
        bodyParams.grouping.groupBy = "Users";
        bodyParams.timeSettings = new TimeSettings();
        bodyParams.timeSettings.timeZone = "America/Los_Angeles";
        bodyParams.timeSettings.timeRange = new TimeRange();
        // Change the "timeFrom" value accordingly so that it does not exceed 184 days from the current date and time
        // The specified time is UTC time. If you want the timeFrom and timeTo your local time, you have to convert
        // your local time to UTC time!
        bodyParams.timeSettings.timeRange.timeFrom = "2023-01-01T00:00:00.000Z";
        bodyParams.timeSettings.timeRange.timeTo = "2023-02-15T23:59:59.999Z";
        bodyParams.responseOptions = new AggregationResponseOptions();
        bodyParams.responseOptions.counters = new AggregationResponseOptionsCounters();
        bodyParams.responseOptions.counters.allCalls = new AggregationResponseOptionsCountersAllCalls();
        bodyParams.responseOptions.counters.allCalls.aggregationType = "Sum";

        var queryParams = new AnalyticsCallsAggregationFetchParameters();
        queryParams.perPage = 100;
        var response = await restClient.Analytics().Calls().V1().Accounts("~").Aggregation().Fetch().Post(bodyParams, queryParams);
        Console.WriteLine(JsonConvert.SerializeObject(response, Formatting.Indented));
      }
      catch (Exception ex)
      {
        Console.WriteLine(ex.Message);
      }
    }
  }
}

Run Your Code

You are almost done. Now run your app from Visual Studio.

Create a Java project (using Eclipse IDE)

  • Create a new Java project
  • Select the Gradle Project wizard
  • Enter project name "AnalyticsQuickStart"
  • Open the build.gradle file and add the RingCentral Java SDK to the project as shown below:
dependencies {
    // ...
    implementation 'com.ringcentral:ringcentral:3.0.0'
}
  • On Eclipse menu, select "Run" and choose the "Run Configurations" and in the dialog, select your project and select the "Environments" tab then enter the following variables:

    • RC_CLIENT_ID
    • RC_CLIENT_SECRET
    • RC_SERVER_URL
    • RC_JWT
  • Right-click the project in the Package Explorer and choose "Refresh Gradle Project" under the "Gradle" sub-menu

Edit the file 'AnalyticsQuickStart.java'

package AnalyticsQuickStart;

import java.io.IOException;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;

import com.ringcentral.*;
import com.ringcentral.definitions.*;

public class AnalyticsQuickStart {
    static RestClient restClient;

    public static void main(String[] args) {
      var obj = new AnalyticsQuickStart();
      try {
        // Instantiate the SDK
        restClient = new RestClient(System.getenv("RC_CLIENT_ID"), System.getenv("RC_CLIENT_SECRET"), System.getenv("RC_SERVER_URL"));

        // Authenticate a user using a personal JWT token
        restClient.authorize(System.getenv("RC_JWT"));

        obj.read_analytics_aggregate_data();

      } catch (RestException e) {
        System.out.println(e.getMessage());
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    /*
      Read aggregate analytics data for a period of time and grouped by users
    */
    public void read_analytics_aggregate_data() throws RestException, IOException{
      try {
        var bodyParams = new AggregationRequest();
        bodyParams.grouping = new Grouping();
        bodyParams.grouping.groupBy = "Users";
        bodyParams.timeSettings = new TimeSettings();
        bodyParams.timeSettings.timeZone = "America/Los_Angeles";
        bodyParams.timeSettings.timeRange = new TimeRange();

        // Change the "timeFrom" value accordingly so that it does not exceed 184 days from the current date and time
        // The specified time is UTC time. If you want the timeFrom and timeTo your local time, you have to convert
        // your local time to UTC time!
        bodyParams.timeSettings.timeRange.timeFrom = "2023-01-01T00:00:00.000Z";
        bodyParams.timeSettings.timeRange.timeTo = "2023-02-15T23:59:59.999Z";

        bodyParams.responseOptions = new AggregationResponseOptions();
        bodyParams.responseOptions.counters = new AggregationResponseOptionsCounters();
        bodyParams.responseOptions.counters.allCalls = new AggregationResponseOptionsCountersAllCalls();
        bodyParams.responseOptions.counters.allCalls.aggregationType = "Sum";

        var queryParams = new AnalyticsCallsAggregationFetchParameters();
        queryParams.perPage = 100l;

        var resp = restClient.analytics().calls().v1().accounts("~").aggregation().fetch().post(bodyParams, queryParams);
        String jsonStr = new Gson().toJson(resp, new TypeToken<Object>(){}.getType());
        System.out.println(jsonStr);
      }catch (RestException e){
        System.out.println(e.getMessage());
      }
    }
}

Build & Run Your Code

You are almost done. Now run your app from Eclipse.

Sample Applications on GitHub

You can reference the following sample applications from GitHub in case you're looking for a completed project or run into any errors: