V-Spark Online Help

Using the /stats API with Python

The sample code on this page shows a generic Python application that can be used to call any V‑Spark API. While you will probably want to develop more specialized Python applications to use specific V‑Spark APIs directly, this sample code shows the basic mechanisms that make it easy to interact with the /stats API from Python. This sample application enables you to pass both the API that you want to call and the parameters that you want to provide. In this case, the parameter is the date or the date range that you want to retrieve statistics for, based on the folder that is specified in the previous argument.

The arguments to the sample application are the following:


The name of the host that is running V‑Spark


The V‑Spark authorization token that you are using to establish permission to retrieve information. You can either use the root token for the target V‑Spark installation (located in the file /opt/voci/state/vspark/apitoken) or the authorization token for the company that is associated with the application that you are working with. Locating a company's authorization token is shown in V‑Spark API Permission Requirements.


The API that you want to call, along with the CO_SHORT, ORG_SHORT, and FOLDER about which you want to retrieve statistics


the parameters that you want to pass to your call to the stats API. For this sample application, the parameters that you pass should be enclosed within single quotation marks so that the command shell does not attempt to interpret them.

Figure 1. Sample Python Code for Retrieving Folder Statistics from the /stats API
#!/usr/bin/env python

import sys
import json
import urllib2
import string

# default values
PROTOCOL =  "http://"
PORT =  "3000"

if ( len(sys.argv) != 5 ):
    print "  Usage:", sys.argv[0], "HOST ROOT_TOKEN API_TO_CALL PARAMS"
    # get cmdline params
    HOST, ROOT_TOKEN, API_TO_CALL, PARAMS = sys.argv[1:] 1

# Define the URL in a single variable for JSON load 2
url =  "%s%s:%s%s?token=%s&%s" % (PROTOCOL, HOST, PORT, API_TO_CALL, ROOT_TOKEN, PARAMS)

# To get output data, return a Python object and dump it to a string that is a
#   JSON representation of that object. Complain and exit if the call fails.
try:   3
    data = json.load(urllib2.urlopen(url))
except urllib2.HTTPError, error:
    print '  Error: HTTP message: ', error.msg, ' HTTP return code: ', str(error.code)

# Sanitize URL and params for use in creating output file name
tmp_str = string.replace( 4
            string.replace(API_TO_CALL+"_"+PARAMS+".json", '/', '_'), '&', '_'), '?', '_'), '%20', '_')
target = open(tmp_str[1:], 'w')

target.write(json.dumps(data, indent=4, sort_keys=True)) 5
print "  Output written to: "+tmp_str[1:]          

The core functionality of this application is the following:


If the previous test showed that the correct number of command-line arguments were provided, assign the command-line arguments to the relevant variables


Assemble the URL that you want to call from the parameters that were supplied on the command line and a few internal default settings


Make the API call using the URL that you assembled, convert the object that it returned into JSON, and catch any exception that is returned. If an exception was raised, display the associated HTTP error message and status code that was returned before exiting.


Build the name of the output file to which you want to write the JSON that was returned by the API call. This code is present to avoid constructing filenames which contain special characters that have other implications on a Linux system. Note that when this output file name is used in the following open() statement, the first character in its name is skipped because that character is a safe conversion of the leading '/' in the name of the API.


Write the JSON object to the output file to which you want to write the JSON that was returned by the API call, using standard formatting parameters like indenting each entry by four spaces and sorting the entries by key. These enable a Python application to produce output that is already formatted for human legibility.

An example of executing this application is the following:

statistics-get-info.py HOSTTOKEN /stats/DocTestCo/DocTestCo-DocTesting/Test01 \

This call to the example function would retrieve statistics about activity in the folder DocTestCo/DocTestCo-DocTesting/Test01, for the date range 20170901-20171011 and write it to an output file named stats_DocTestCo_DocTestCo-DocTesting_Test01_daterange=20170901-20171011.json.

Sample output from this call would look like the following:

        "agent": {
            "avgcalls": "4.0",
            "emotion": {
                "improving": 4,
                "negative": 0,
                "positive": 0,
                "worsening": 0
            "talk": {
                "avg": "0:02:11",
                "max": {
                    "duration": "0:08:44",
                    "id": "105"
                "min": {
                    "duration": "0:08:44",
                    "id": "105"
        "avgduration": "0:05:25",
        "avgsilence": "0:02:16",
        "avgwords": "643.0",
        "calls": 4,
        "client": {
            "emotion": {
                "improving": 0,
                "negative": 4,
                "positive": 0,
                "worsening": 0
            "talk": {
                "avg": "0:00:58"
        "date": "20170925"

This sample output has been abbreviated to save space.