RingCentral Line of Business Analytics APIs Quick Start

Last updated: 2022-09-27Contributors
Edit this page

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 "Password-based 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.

Call the Analytics API

Create a Node.JS project

$ npm init

Install RingCentral Node.JS SDK & DOTENV Module

$ 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, including the FROM_DATE and TO_DATE variables.

const RC_SDK = require('@ringcentral/sdk').SDK
require('dotenv').config();

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();
platform.login({
      'jwt':  process.env.RC_JWT
})

let FROM_DATE = '2022-04-12T07:00:00.000Z'
let TO_DATE   = '2022-05-11T07:00:00.000Z'

platform.on(platform.events.loginSuccess, function(e){
    run_report( FROM_DATE, TO_DATE )
});

async function run_report( from_time, to_time ) {
    try {
        let options = {
                "grouping":{
                    "groupBy":"Users"
                },
                "timeSettings":{
                    "timeZone": "US/Pacific",
                    "timeRange":{
                        "timeFrom": from_time,
                        "timeTo": to_time
            }
                },
                "responseOptions":{
                    "counters":{
                        "allCalls":{
                            "aggregationType":"Sum"
                    }
            }
                }
        }
        let result = await platform.post("/analytics/calls/v1/accounts/~/aggregation/fetch", options);
        let response = await result.json();
        console.dir(response, {depth: null});
    } catch (e) {
            console.log(e.message);
    }
}

Run your code

You are almost done. Now run your script.

$ node analytics.js

Install RingCentral Python SDK

$ 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, including the FROM_DATE and TO_DATE variables.

#!/usr/bin/env python
from ringcentral import SDK
import os,sys,json
from dotenv import load_dotenv
load_dotenv()

FROM_DATE = '2022-04-12T07:00:00.000Z'
TO_DATE   = '2022-05-11T07:00:00.000Z'

rcsdk = SDK( os.environ.get('RC_CLIENT_ID'),
             os.environ.get('RC_CLIENT_SECRET'),
             os.environ.get('RC_SERVER_URL') )
platform = rcsdk.platform()

try:
  platform.login(jwt=os.environ.get('RC_JWT'))
except:
  sys.exit("Unable to authenticate to platform. Check credentials.")

def fetch_aggregate_report( from_time, to_time ):
  try:
    options = {
      "grouping":{
        "groupBy":"Users"
      },
      "timeSettings":{
        "timeZone": "US/Pacific",
        "timeRange":{
          "timeFrom": from_time,
          "timeTo": to_time
        }
      },
      "responseOptions":{
        "counters":{
          "allCalls":{
            "aggregationType":"Sum"
          }
        }
      }
    }
    resp = platform.post('/analytics/calls/v1/accounts/~/aggregation/fetch', options)
    jsonObj = resp.json_dict()
  except Exception as err:
    sys.exit("Unable to fetch analytics", err)

  print(json.dumps(jsonObj, indent=2, sort_keys=True))

fetch_aggregate_report( FROM_DATE, TO_DATE )

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, including the FROM_DATE and TO_DATE variables.

<?php
require('vendor/autoload.php');
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . '/');
$dotenv->load();

$FROM_DATE = '2022-04-12T07:00:00.000Z';
$TO_DATE   = '2022-05-11T07:00:00.000Z';

$rcsdk = new RingCentral\SDK\SDK( $_ENV['RC_CLIENT_ID'],
                                  $_ENV['RC_CLIENT_SECRET'],
                                  $_ENV['RC_SERVER_URL'] );
$platform = $rcsdk->platform();
$platform->login( [ "jwt" => $_ENV['RC_JWT'] ] );

run_report( $FROM_DATE, $TO_DATE );

function run_report( $from_date, $to_date ){
  global $platform;
  $options = array(
    'grouping' => array(
      'groupBy' => "Users"
    ),
    'timeSettings' => array(
      'timeZone' => "US/Pacific",
      'timeRange' => array(
        'timeFrom' => $from_date,
        'timeTo' => $to_date
      )
    ),
    'responseOptions' => array(
      'counters' => array(
        'allCalls' => array(
          'aggregationType' => "Sum"
        )
      )
    )
  );

  $resp = $platform->post('/analytics/calls/v1/accounts/~/aggregation/fetch',
                          $options);
  $jsonObj = $resp->json();
  print_r( json_encode($jsonObj, JSON_PRETTY_PRINT) );
}
?>

Run your code

You are almost done. Now run your script.

$ php analytics.php

Create a C# project

  • Choose Console Application .Net or .Net Core
  • Select Target Framework Version
  • Enter project name "WebAPIClient"
  • Add NuGet package RingCentral.Net SDK version 5.9.0 or newer
  • Create a JSON file "aggregate-request-body.json" that can be referenced in "JSON Request Body". Refer to the content of this sample JSON file.
  • Create a JSON file "timeline-request-body.json" that can be referenced in "JSON Request Body". Refer to the content of this sample JSON file.

Edit the file 'Program.cs'

Be sure to edit the variables in ALL CAPS with your app and user credentials.

using System;
using System.IO;

using RingCentral;
using Newtonsoft.Json.Linq;

namespace WebAPIClient {
  class Program {

    private static string RINGCENTRAL_CLIENTID = "";
    private static string RINGCENTRAL_CLIENTSECRET = "";
    // Set this boolean value to true if you wish to use Production Credentials
    private static bool RINGCENTRAL_PRODUCTION = false;
    private static string RINGCENTRAL_USERNAME = "";
    private static string RINGCENTRAL_PASSWORD = "";
    private static string RINGCENTRAL_EXTENSION = "";

    static RingCentral.RestClient rcClient;

    static void Main(string[] args){
      rcClient = new RingCentral.RestClient(RINGCENTRAL_CLIENTID, RINGCENTRAL_CLIENTSECRET, RINGCENTRAL_PRODUCTION);
      rcClient.Authorize(RINGCENTRAL_USERNAME, RINGCENTRAL_EXTENSION, RINGCENTRAL_PASSWORD).Wait();
      getAggregateData(rcClient);
      getTimelineData(rcClient);
    }   
    private static async void getAggregateData(RingCentral.RestClient restClient) {
      var jsonRequestObject = loadJson("aggregate-data-request.json");
      var response = await rcClient.Post("/analytics/calls/v1/accounts/~/aggregation/fetch", jsonRequestObject);
      Console.WriteLine("---- Aggregate Data ----");
      Console.WriteLine(await response.Content.ReadAsStringAsync());
    }
    private static async void getTimelineData(RingCentral.RestClient rcClient) {     
      var jsonRequestObject = loadJson("timeline-data-request.json");
      var response = await rcClient.Post("/analytics/calls/v1/accounts/~/timeline/fetch?interval=Day", jsonRequestObject);
      Console.WriteLine("---- TimeLine Data ----");
      Console.WriteLine(await response.Content.ReadAsStringAsync());
    }

    // Helper function to load the JSON file, make sure to edit this based on your requirements
    private static JObject loadJson(string filePath) {
      string result = string.Empty;
      using (StreamReader r = new StreamReader(filePath)) {
        var jsonString = r.ReadToEnd();
        JObject jsonObject = JObject.Parse(jsonString);
        return jsonObject;
      }
    }
  }
}

Run Your Code

You are almost done. Now run your app by typing in the command line

$ cd WebAPIClient
$ dotnet run

Create a Java Gradle/Maven project

  • Make sure you have JDK 11 or newer installed in our machine
  • Install RC Java SDK 2.2.0 or latest from GitHub or Maven Central
  • Create a new Java Class called "App.java"
  • Create a JSON file in the following path inside your project "src/main/resources/aggregate-request-body.json". Refer to the contents of this sample JSON file.
  • Create a JSON file in the following path inside your project "src/main/resources/timeline-request-body.json". Refer to the contents of this sample JSON file.

Edit the file 'App.java'

Be sure to edit the variables in ALL CAPS with your app and user credentials.

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Paths;

import com.ringcentral.RestClient;
import com.ringcentral.definitions.TokenInfo;

public class App {

  static String RINGCENTRAL_CLIENT_ID = "";
  static String RINGCENTRAL_CLIENT_SECRET = "";
  static String RINGCENTRAL_USERNAME = "";
  static String RINGCENTRAL_PASSWORD = "";
  static String RINGCENTRAL_EXTENSION = "";

  private static final String AGGREGATE_API_PATH = "/analytics/calls/v1/accounts/~/aggregation/fetch";
  private static final String TIMELINE_API_PATH = "/analytics/calls/v1/accounts/~/timeline/fetch?interval=Week";
  // Update the URL based on if you're running using RingCentral Sandbox or Production Credentials. Currently set for sandbox
  private static String RINGCENTRAL_SERVER_URL = "https://platform.devtest.ringcentral.com";

  public static void main(String[] args) throws Exception {

    RestClient rc = new RestClient(RINGCENTRAL_CLIENT_ID, RINGCENTRAL_CLIENT_SECRET, RINGCENTRAL_SERVER_URL);
    TokenInfo token = rc.authorize(RINGCENTRAL_USERNAME, RINGCENTRAL_EXTENSION, RINGCENTRAL_PASSWORD);
    String accessToken = token.access_token;

    String aggregate_json_file_path = "src/main/resources/aggregate-request-body.json";
    String timeline_json_file_path = "src/main/resources/timeline-request-body.json";
    String aggregateJsonStr = App.readFileAsString(aggregate_json_file_path);
    String timelineJsonStr = App.readFileAsString(timeline_json_file_path);

    try {
      HttpResponse<String> aggreageteHttpResponse = getData(aggregateJsonStr, AGGREGATE_API_PATH, accessToken);
      System.out.println("---AGGREGATE API RESPONSE---");
      System.out.println(aggreageteHttpResponse.statusCode());
      System.out.println(aggreageteHttpResponse.body());
      HttpResponse<String> timelineHttpResponse = getData(timelineJsonStr, TIMELINE_API_PATH, accessToken);
      System.out.println("---TIMELINE API RESPONSE---");
      System.out.println(timelineHttpResponse.statusCode());
      System.out.println(timelineHttpResponse.body());
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }

  static HttpResponse<String> getData(String jsonStr, String endpoint, String accessToken) throws Exception {
    HttpClient httpClient = HttpClient.newHttpClient();
    HttpRequest httpRequest = HttpRequest.newBuilder()
      .header("Content-Type", "application/json")
      .header("Authorization", "Bearer " + accessToken)
      .uri(URI.create(RINGCENTRAL_SERVER_URL + endpoint))
      .POST(HttpRequest.BodyPublishers.ofString(jsonStr))
      .build();

    HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
    return httpResponse;
  }

  static String readFileAsString(String file) throws Exception {
    return new String(Files.readAllBytes(Paths.get(file)));
  }
}

Build & Run Your Code

You are almost done. Now run your app by typing in the command line

$ javac App.java
$ java App

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, including the FROM_DATE and TO_DATE variables.

require 'ringcentral'
require 'dotenv/load'

FROM_DATE = '2022-04-12T07:00:00.000Z'
TO_DATE   = '2022-05-11T07:00:00.000Z'

$rc = RingCentral.new( ENV['RC_CLIENT_ID'],
                       ENV['RC_CLIENT_SECRET'],
                       ENV['RC_SERVER_URL'] )

$rc.authorize(jwt: ENV['RC_JWT'])       

def run_report(from_date, to_date)
  resp = $rc.post('/analytics/calls/v1/accounts/~/aggregation/fetch', payload: {
    "grouping":{ 
      "groupBy": "Users" 
    },
    "timeSettings":{
      "timeZone": "US/Pacific",
        "timeRange":{
          "timeFrom": from_date,
          "timeTo": to_date
        }
    },
    "responseOptions":{
        "counters":{ 
        "allCalls":{ 
          "aggregationType": "Sum" 
        } 
      }
    }
  })
  puts "Response: " + JSON.pretty_generate(resp.body)
end

run_report( FROM_DATE, TO_DATE )

Run your code

You are almost done. Now run your script.

$ ruby analytics.rb

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: