TDS REST API For Phoenix Contact Proficloud

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

TSD REST Tutorial

Alexander von Birgelen, [email protected], 12.10.2018

This document shortly describes how to connect to the TSD Kairos database from external applications. The example is in Python but can be transferred to any other
language which supports REST or HTTP.

Set-up
In Python, we need the following packages:

requests is the package which handles the communication with the REST API
json this library handles conversion from python to json and vice versa
base64 this library handles the calculation of the authentication token for the PROFICLOUD API.

Import libraries:

In [2]: import requests


import json
import base64

The url of the REST API is different for the production and staging environments.

Production: https://tsd.proficloud.net/ds/v1/kairos/api/v1/datapoints/query/ (https://tsd.proficloud.net/ds/v1/kairos/api/v1/datapoints/query/)

Staging: https://tsd.proficloud-staging.net/ds/v1/kairos/api/v1/datapoints/query/ (https://tsd.proficloud-staging.net/ds/v1/kairos/api/v1/datapoints/query/)

In [16]: url="https://tsd.proficloud.net/ds/v1/kairos/api/v1/datapoints/query/"
#url="https://tsd.proficloud-staging.net/ds/v1/kairos/api/v1/datapoints/query/"

1 of 4
The Authentication
The user has to authenticate with the PROFICLOUD IDM to gain access to the REST API.

Login to PROFICLOUD and go to the TSD Device Manager. Click on the username and select Manage Account.

Two things are required for authentication: The Account Identifier and the API Password. The password can be created by clicking the Credentials button. Note that
the API Password is different from your normal user password.

When the credentials button is not shown, your account lacks the permission to use the API. The REST API is currently not available by default and the user has to get
the permission to use the TSD REST API. The verlinked support can grant permission to the API.

Now, we have to create the headers for the REST API. The User-Authentication requrires the Authentication header.

We need to generate an API-token for the authorization. The token is generated by creating a string, consiting of the Account Identifier and the API Password,
separated by a colon (:) withput spaces. This string has to be base64 encoded and incorporated into the authentication header:

"Authorization" : "Basic BASE-64-ENCODED-API-TOKEN"

We also need to prepare a second header to set the content-type to json:

"Content-Type" : "application/json"

In Python, this would look like this:

In [3]: password="PASSWORD"
token="ACCOUNTIDENTIFIER:"+password
tokenb64 = base64.b64encode(token.encode())
headers = { "Content-Type" : "application/json", "Authorization" : "Basic "+tokenb64.decode('utf-8')}
print(headers)

{'Content-Type': 'application/json', 'Authorization': 'Basic QUNDT1VOVElERU5USUZJRVI6UEFTU1dPUkQ='}

Using the API


The database behind TSD is the KairodDB, a database for time-series data. The API provides direct access to the DB. The official documentation can be found here:
https://kairosdb.github.io/docs/build/html/restapi/QueryMetrics.html (https://kairosdb.github.io/docs/build/html/restapi/QueryMetrics.html)

Now we connect to the API by creating a session. Note that this does not work through the Phoenix Contact proxy, and a direct internet connection is required. To
connect, create a new requests-session and set trust_env to false to ignore the proxy settings of the operating system:

2 of 4
In [18]: session = requests.Session()
session.trust_env = False #(disable proxy, as it is always sourced from /etc/environment)

We now create a payload to query metrics from the database. In this example we will read the metric avbirgelen.Analog_IN_Cloud. We will read the first 1000 entries
starting at the unix-timestamp 1525241361.

Please refer to the official Kairos documentation which is linked above for more information on working with this database.

In [19]: #avbirgelen.Analog_IN_Cloud
payload= {
"start_absolute": 1525241361,
"metrics": [
{
"name": [ "avbirgelen.Analog_IN_Cloud" ],
"limit": 100
}
]
}

The payload has to be encoded as json. You can directly write json-code as a string or juse a json-serializer. Now we query the database and get our result:

In [20]: r = session.post(url=url, headers=headers, data=json.dumps(payload))

The variable r now contains our result.

If everything worked, we get the response code 200! Code 500 indicates an internal server error and occurs for example is the Content-Type header is not set correctly.
Code 403 is the permission denied error and points toward errors in your credentials or authentication header. For more HTTP-response codes refer to
https://en.wikipedia.org/wiki/List_of_HTTP_status_codes (https://en.wikipedia.org/wiki/List_of_HTTP_status_codes)

In [21]: r.status_code

Out[21]: 200

The result of our query is now found in the content-property of our response as json. Here we will only print the first 300 characters of the response:

In [22]: r.content[:300]

Out[22]: b'{"queries":[{"sample_size":300,"results":[{"name":"avbirgelen.Analog_IN_Cloud","tags":{"appliance":["115929d
4-c303-4355-8e30-2db45a4ecf3e"]},"values":[[1536311303000,18247],[1536311304000,18248],[1536311305000,18246],[
1536311306000,18244],[1536311307000,18246],[1536311308000,18249],[1536311309000,18'

We can also convert the json back to a Python object through deserialization:

In [23]: content = json.loads(r.content)


#content

Example: Plotting the data


Below we will show how to acces the values and plot them using the Bokeh plotting library. The deserialized response is a dictionary and we can navigate through it. For
this example we can get to the values as follows:

In [24]: values = content['queries'][0]['results'][0]['values']

We can convert this into a numpy array as follows:

In [25]: import numpy as np


npvalues = np.asarray(values)
#npvalues

Now we can plot the data:

3 of 4
In [26]: from bokeh.plotting import figure, show
from bokeh.io import output_notebook
output_notebook()
p = figure()
p.line(npvalues[:,0], npvalues[:,1], line_width=2)
show(p)

BokehJS 0.13.0 successfully loaded.


(https://bokeh.pydata.org)

(https://bokeh.pydata.org/

4 of 4

You might also like