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:
constaxios=require('axios');// Main function - runs every time the function is executed.// "args" is a dictionary containing both the URL params and the HTTP body (for POST requests).asyncfunctionmain(args) {// Grab the token and device label from URL parameters, then erase them from the args dictionaryvar ubidots_token =args.token;var device_label =args.device;delete args['token'];delete args['device'];// Use the remaining parameters as payloadvar payload = args;// Log the payload to the console, for debugging purposes. You may access the function's logs using// the option in the above header.console.log(payload);// Send the payload to Ubidotsvar response =awaitubidots_request(ubidots_token, device_label, payload);// Log Ubidots response to the consoleconsole.log(response);// Pass Ubidots' API response as the function's reponsereturn response;}// This function builds an HTTP POST request to Ubidotsasyncfunctionubidots_request(token, label, body) {let config = { method:'post', url:'https://industrial.api.ubidots.com/api/v1.6/devices/'+ label, data: body, headers: {'Content-Type':'application/json','X-Auth-Token': token } }constresponse=awaitaxios.request(config);returnresponse.data;}
import requestsimport timeBASE_URL ="https://industrial.api.ubidots.com"REQUESTS_FUNCTIONS ={"get": requests.get,"post": requests.post}defmain(args):''' Main function - runs every time the function is executed. "args" is a dictionary containing both the URL params and the HTTP body (for POST requests). ''' token = args.get('token', None) device = args.get('device', None)if token isNoneor device isNone:print("[ERROR] Please send your Ubidots Token and device label to update in your args")return{"status":"error"}del args['token']del args['device']# Log the payload to the console, for debugging purposes. You may access the function's logs using# the option in the above header.print("[INFO] Payload to send: {}".format(args))# Use the remaining parameters as payload req =update_device(device, args, token)# Prints the request resultprint("[INFO] Request result:")print(req.text)return{"status":"Ok","result": req.json()}defupdate_device(device,payload,token):""" updates a variable with a single dot """ url ="{}/api/v1.6/devices/{}".format(BASE_URL, device) headers ={"X-Auth-Token": token,"Content-Type":"application/json"} req =create_request(url, headers, payload, attempts=5, request_type="post")return reqdefcreate_request(url,headers,data,attempts,request_type):""" Function to create a request to the server """ request_func = REQUESTS_FUNCTIONS.get(request_type) kwargs ={"url": url,"headers": headers}if request_type =="post": kwargs["json"]= datatry: req =request_func(**kwargs)print("[INFO] Request result: {}".format(req.text)) status_code = req.status_code time.sleep(1)while status_code >=400and attempts <5: req =request_func(**kwargs)print("[INFO] Request result: {}".format(req.text)) status_code = req.status_code attempts +=1 time.sleep(1)return reqexceptExceptionas e:print("[ERROR] There was an error with the request, details:")print(e)returnNone
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: