API Reference Guide

API Introduction

The Userful REST API enables users to programmatically interact with the video walls and displays to have better control over them. Any programming language that supports HTTP such as Java, Python, C#, JavaScript etc. can be used for communicating via REST API. You can use a REST API Client for quick debugging and testing of REST API commands.

This document assumes that user is aware of the programming language used for building REST API code and will walk you through the steps and some examples that will help you getting started with Userful REST API.

For the list of REST API commands, see api.userful.com.

API User Authentication

Please ensure that a valid user name and password is required to use Userful REST API. The API POST /session allows you to send a username and password to log in. If the authentication is successful you will get a response from the server with your unique session ID. An example session ID looks like this:

JSESSIONID=52B9DEF0-4C86-4D67-ABF3-89243ABC4D86

Once the ID is available, send it as a cookie parameter together with every other API command. With Javascript or HTML you don't have to do this, as the browser will manage the cookie for you.

Getting Started with the REST API

Running your first few commands

Ensure that any REST API Client is installed for the purpose of testing. This will aid in quick debugging and testing of REST API commands.

Find the IP address of your server. If you normally access the Control Center with a URL of, for example, http://192.168.120.199/ucc.html, Then you will use http://192.168.120.199 to access the server.

Configure all necessary Zones and Sources, using naming conventions you will remember. For the purpose of this example, we will assume that the names are: zone_1, source_1, and source_2.

Paste the following command into REST API Client and test it. This will switch zone_1 to play source_2.

Assign zone_1 to source_2:

 http://123.168.120.199/api/zones/byname/zone_1/switch?destinationSourceName=source_2 

Choose PUT method and click "Send".

Play source_2 on zone_1:

http://123.168.120.199./api/zones/byname/zone_1/playAssignedSource 

Choose PUT method and click "Send". This will play source_2 on zone_1.

Communicating with the API

To communicate with API, write a client program in the programming language that you are familiar with. Here are some code samples written in Python, JavaScript and C#.

Python

In the following example,two API calls are demonstrated by constructing two functions respectively:

  • login -> POST /api/session

(Login to the system with username and password)

  • play -> PUT /api/zones/byname/{zoneName}/playAssignedSource

(Play the assigned source on the zone by given its zone name)

from httplib import *
from urllib import quote
import json

host = "http://localhost:9000"

def login():
    conn = HTTPConnection(host)
    method = "POST"
    url = "/api/session"
    body = """
            {
              "user" : "user",
              "password" : "password"
            }
            """
    conn.request(method, url, body)
    response = conn.getresponse()
    status = response.status
    session_header = None
    if status == 200:
        data = response.read()
        print status, data
        session = json.loads(data)["session"]
        session_str = session["name"] + "=" + session["value"]
        session_header = {"cookie":session_str}
    print session_header
    conn.close()
    return session_header

def play(session_header, zone_name):
    conn = HTTPConnection(host)
    method = "PUT"
    url = "/api/zones/byname/%s/playAssignedSource" % quote(zone_name)
    url = quote(url)
    body = ""
    conn.request(method, url, body, session_header)
    print "Playing %s " % zone_name

if __name__ == '__main__':
    session_header = login()
    play(session_header, "Zone-0")

JavaScript

For security, AJAX requests must be made from the same domain. This feature is known as Cross-origin resource sharing. When developing, disable it on Google Chrome or Chromium as follows:

chromium-browser --disable-web-security --user-data-dir

Sending a Broadcast Alert:

ROOTURL = 'http://192.168.120.199:9000/api';
function startBroadcast(_message, _alertLevel, _duration) {
  $.ajax({
    type: 'PUT',
    url: ROOTURL + '/system/broadcast/start',
    data: JSON.stringify({
      message: _message,
      alertLevel: _alertLevel,
      lengthMillisec: _duration
    }),
    success: function(result, textStatus, jqXHR){
      alert('Broadcasting now');
    },
    error: function(jqXHR, textStatus, errorThrown){
      alert('Broadcast error: ' + textStatus);
    }
  });
}

Explanation

This js function will make an AJAX call to the server to broadcast a message on the screen. The url for this rest command is

http://192.168.120.199:9000/api/system/broadcast/start

The HTTP method is PUT.

The parameters are: message ("Hello World"), alertLevel ("RED_LEVEL") and duration in milliseconds (6000). The function call will be simple as

startBroadcast("Hello World", "RED_LEVEL", 6000)

You have options to handle the cases where the broadcast is successful or not. In this example you will get different message boxes. Most AJAX functions are similar to this example.

Play the profile assigned to the zone

function playAssignedProfile(zoneId) {
  $.ajax({
    type: 'PUT',
    url: 'example.com/api/zones/' + zoneId + '/playAssignedProfile'   
  });
}

This function takes the zone ID and plays it, for example

playAssignedProfile('178DA782-E721-11E5-9730-9A79F06E9478');

Stop playing a zone

function stopZone(zoneId) {
  $.ajax({
    type: 'PUT',
    url: 'example.com/api/zones/' + zoneId + '/stop'   
  });
}

Switch a zone to another source

function switchZone(zoneId) {
  $.ajax({
    type: 'PUT',
    url: 'example.com/api/zones/' + zoneId + '/switch'   
  });
}

Make a playlist and play it on a zone

function playVideoList(zoneId) {
  $.ajax({
    type: 'PUT',
    data: JSON.stringify({   
       "videolist": [
         "/video/1.mp4",
         "/video/2.mp4"
        ],
        "queue": false,
        "repeat": false,
        "slideshowInterval": 10
    }),
    url: 'example.com/api/zones/' + zoneId + '/playVideoList'   
  });
}

C#

You may need namespaces such as Newtonsoft.Json for JSON manipulation, System.Net.Http and System.Net.Sockets for networking.

Get the session ID value

The following code snippet will send user name and password strings to the server and retrieve the session ID from the cookie, in response from the server.

string getSessionId() {
  using (var httpClient = new HttpClient())
  {
      httpClient.BaseAddress = "http://localhost:9000";
      dynamic loginInfo = new ExpandoObject();
      loginInfo.user = "user";
      loginInfo.password = "your password";
      var auth = JsonConvert.SerializeObject(loginInfo);
      var buffer = System.Text.Encoding.UTF8.GetBytes(auth);
      var byteContent = new ByteArrayContent(buffer);
      var ret = httpClient.PostAsync("/api/session", byteContent);
      IEnumerable<string> retval;
      ret.Result.Headers.TryGetValues("Set-Cookie", out retval);
      if (retval != null)
          return retval.FirstOrDefault();
      else
          return null;
  }
}

Get source information

Use API GET /sources to get the list of sources available on the server. This code snippet will first authenticate with the sever and then send the request to get the source list.

// get the session id first
string cookie = getSessionId();
object GetSourceList() {
  using (var httpClient = new HttpClient())
  httpClient.BaseAddress = "http://localhost:9000";  
  var message = new HttpRequestMessage(HttpMethod.Get, "/api/sources");
  // add cookie value to the message header
  message.Headers.Add("cookie", cookie);
  // send to server
  var result = httpClient.SendAsync(message);
  result.Result.EnsureSuccessStatusCode();
  // get json response
  var s = result.Result.Content.ReadAsStringAsync().Result;  
  return JsonConvert.DeserializeObject(s);  
}

Last updated