Coding an UbiFunction
UbiFunctions accept NodeJS or Python, which means you can use Javascript or Python code to extract, transform, and analyze data.
Before coding a function, you'll need to get familiar with these 3 concepts:
  • Input arguments
  • Code
  • Output response

Input Arguments

Any payload sent to the function will be accesible in the "args" object inside the code.
Object
Description
args
Any payload sent to the function will be contained by the args object.
args.token
When an x-auth-token header is included in an HTTP invokation request, the args.token key will be included.

Code

Your UbiFunction code is a NodeJS or Python snippet that runs when the function is invoked.
As an example, the following code would return the same data received:
1
function main(args) {
2
​
3
return args;
4
​
5
}
Copied!
By default, every new UbiFunction has a sample code that uses input data (token, device, and a variable value) to make a request to Ubidots API. Here are the default examples for your reference:
NodeJS
Python
1
const axios = require('axios');
2
​
3
// Main function - runs every time the function is executed.
4
// "args" is a dictionary containing both the URL params and the HTTP body (for POST requests).
5
async function main(args) {
6
​
7
// Grab the token and device label from URL parameters, then erase them from the args dictionary
8
var ubidots_token = args.token;
9
var device_label = args.device;
10
delete args['token'];
11
delete args['device'];
12
​
13
// Use the remaining parameters as payload
14
var payload = args;
15
​
16
// Log the payload to the console, for debugging purposes. You may access the function's logs using
17
// the option in the above header.
18
console.log(payload);
19
​
20
// Send the payload to Ubidots
21
var response = await ubidots_request(ubidots_token, device_label, payload);
22
​
23
// Log Ubidots response to the console
24
console.log(response);
25
​
26
// Pass Ubidots' API response as the function's reponse
27
return response;
28
}
29
​
30
// This function builds an HTTP POST request to Ubidots
31
async function ubidots_request(token, label, body) {
32
let config = {
33
method: 'post',
34
url: 'https://industrial.api.ubidots.com/api/v1.6/devices/' + label,
35
data: body,
36
headers: {
37
'Content-Type': 'application/json',
38
'X-Auth-Token': token
39
}
40
}
41
const response = await axios.request(config);
42
return response.data;
43
}
44
​
Copied!
1
import requests
2
import time
3
​
4
BASE_URL = "https://industrial.api.ubidots.com"
5
​
6
REQUESTS_FUNCTIONS = {"get": requests.get, "post": requests.post}
7
​
8
def main(args):
9
'''
10
Main function - runs every time the function is executed.
11
"args" is a dictionary containing both the URL params and the HTTP body (for POST requests).
12
'''
13
token = args.get('token', None)
14
device = args.get('device', None)
15
​
16
if token is None or device is None:
17
print("[ERROR] Please send your Ubidots Token and device label to update in your args")
18
return {"status": "error"}
19
20
del args['token']
21
del args['device']
22
​
23
# Log the payload to the console, for debugging purposes. You may access the function's logs using
24
# the option in the above header.
25
​
26
print("[INFO] Payload to send: {}".format(args))
27
​
28
# Use the remaining parameters as payload
29
req = update_device(device, args, token)
30
​
31
# Prints the request result
32
​
33
print("[INFO] Request result:")
34
print(req.text)
35
​
36
return {"status": "Ok", "result": req.json()}
37
​
38
def update_device(device, payload, token):
39
"""
40
updates a variable with a single dot
41
"""
42
​
43
url = "{}/api/v1.6/devices/{}".format(BASE_URL, device)
44
headers = {"X-Auth-Token": token, "Content-Type": "application/json"}
45
​
46
req = create_request(url, headers, payload, attempts=5, request_type="post")
47
48
return req
49
​
50
def create_request(url, headers, data, attempts, request_type):
51
"""
52
Function to create a request to the server
53
"""
54
​
55
request_func = REQUESTS_FUNCTIONS.get(request_type)
56
​
57
kwargs = {"url": url, "headers": headers}
58
​
59
if request_type == "post":
60
kwargs["json"] = data
61
​
62
try:
63
req = request_func(**kwargs)
64
print("[INFO] Request result: {}".format(req.text))
65
status_code = req.status_code
66
time.sleep(1)
67
​
68
while status_code >= 400 and attempts < 5:
69
req = request_func(**kwargs)
70
print("[INFO] Request result: {}".format(req.text))
71
status_code = req.status_code
72
attempts += 1
73
time.sleep(1)
74
​
75
return req
76
except Exception as e:
77
print("[ERROR] There was an error with the request, details:")
78
print(e)
79
return None
80
​
Copied!
To test the function you can click on the button Run Function. This will open up a modal requesting the input data to test with, you need only to enter a valid JSON payload. You may leave this blank if your code does not require any input.
In the case of Ubidots default sample function, enter the JSON payload below to run a test:
1
{
2
"token":"your-token",
3
"Device":"sample-function",
4
"Temperature":"45"
5
}
Copied!
After clicking on Run with this input a console window will emerge with both the output and the console of the results:

Output Response

The output of every UbiFunction must be a JSON object. By default, the status code will be 200, but this could be changed using Raw Functions.
For example:
1
function main(args) {
2
​
3
return {"Hello":"World"};
4
​
5
}
Copied!