Creating an UbiFunction
To create an UbiFunction:
  1. 1.
    In your Ubidots account, go to the "Devices" tab and select "Functions".
2. Click the blue "+" icon to create your first UbiFunction
3. Give the function a name. Keep in mind this name will later become part of the function’s URL.
The name of your function will become part of the function’s URL.

Coding your UbiFunction

UbiFunctions accept NodeJS or Python, which means you can use Javascript or Python code to extract, transform, and analyze data. Your function receives "args" as a dictionary, which you can then access in your code to perform the desired data transformation.
By default, every new UbiFunction has a sample code that uses input data (TOKEN, Device, and temperature value) to make a request to Ubidots API.
Here are the welcome 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:
Copy link