Difference between revisions of "Docs/API Reference Guide"

From Userful Support
Jump to: navigation, search
Line 23: Line 23:
  
 
===Running your first few commands using the API===
 
===Running your first few commands using the API===
* Step 1: Ensure that REST API Client is installed.
+
* Step 1: Ensure that any REST API Client is installed for the purpose of testing.
 
: This will aid in quick debugging and testing REST API commands.
 
: This will aid in quick debugging and testing REST API commands.
  
Line 31: Line 31:
 
* Step 3: Setup video wall zones and sources and remember their names. For the purpose of this example assume that the names are: zone_1, source_1, and source_2.
 
* Step 3: Setup video wall zones and sources and remember their names. For the purpose of this example assume that the names are: zone_1, source_1, and source_2.
  
* Step 4: Paste the following command into Postman and click "Enter". This will switch zone_1 to play source_2.
+
* Step 4: 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 <pre> http://123.168.120.199/api/zones/byname/zone_1/switch?destinationSourceName=source_2 </pre>  
 
:* ''Assign'' zone_1 to source_2 <pre> http://123.168.120.199/api/zones/byname/zone_1/switch?destinationSourceName=source_2 </pre>  
 
::Choose PUT method and click "Send".
 
::Choose PUT method and click "Send".
 
:* ''Play'' source_2 on zone_1 <pre> http://123.168.120.199./api/zones/byname/zone_1/playAssignedSource </pre>  
 
:* ''Play'' source_2 on zone_1 <pre> http://123.168.120.199./api/zones/byname/zone_1/playAssignedSource </pre>  
::Choose PUT method and press "Send". This will ply source_2 on zone_1.
+
::Choose PUT method and press "Send". This will play source_2 on zone_1.
  
 
==Communicating with API==
 
==Communicating with API==
Line 47: Line 47:
  
 
* login -> POST /api/session  
 
* login -> POST /api/session  
(Login to the system with username and password)
+
:(Login to the system with username and password)
 
* play -> PUT /api/zones/byname/{zoneName}/playAssignedSource  
 
* play -> PUT /api/zones/byname/{zoneName}/playAssignedSource  
(Play the assigned source on the zone by given its zone name)
+
:(Play the assigned source on the zone by given its zone name)
  
 
<pre>
 
<pre>
Line 203: Line 203:
  
 
====Get the session ID value====
 
====Get the session ID value====
The flowing code snippet will send user name and password strings to the server and retrieve the session ID from the cookie in the response from server
+
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.
 
<pre>
 
<pre>
 
string getSessionId() {
 
string getSessionId() {
Line 247: Line 247:
  
  
:'''''Please visit this [https://www.userful.com/userful-video-wall-api link] to watch video and learn more about Userful REST API.'''''
+
'''''Please visit this [https://www.userful.com/userful-video-wall-api link] to watch video and learn more about Userful REST API.'''''
  
  

Revision as of 17:41, 26 February 2018


Copyright © 2019 Userful Corporation. All rights reserved.
(Updated 2018.02.26)


To return to the main documentation page, Click Here.



Introduction

Userful REST API enables users to programmatically interact with the video walls and displays to have a better control over them. Any programming language that supports http protocol 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.


User Authentication

Please ensure that a valid user name and password is required to use Userful REST API. The API POST /session allows to send user name and password to log in. If the authentication is successful you will get a response from the server with your unique session ID. For example the ID would look like this:
JSESSIONID=52B9DEF0-4C86-4D67-ABF3-89243ABC4D86

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


Getting started with REST API

Running your first few commands using the API

  • Step 1: Ensure that any REST API Client is installed for the purpose of testing.
This will aid in quick debugging and testing REST API commands.
  • Step 2: Find the IP address of your server.
For example:
 http://123.168.120.199 
  • Step 3: Setup video wall zones and sources and remember their names. For the purpose of this example assume that the names are: zone_1, source_1, and source_2.
  • Step 4: 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 press "Send". This will play source_2 on zone_1.

Communicating with 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

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

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 the broadcast is successful or not, In this example you will get different message boxes. Most of AJAX functions are similar to this example.

Play the profile assigned to 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 other 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);  
}


Please visit this link to watch video and learn more about Userful REST API.


Related Links