In this example you will learn how to:
Use URL arguments of an HTTP GET request inside a function.
Make an HTTP POST request from a function.
At the end of this example you should be able to paste a URL with this format into your browser to send data to your devices:
https://parse.ubidots.com/prv/YOUR-USERNAME/post-data?&device_label=ABCD&temperature=73&humidity=55&token=YOUR-ACCOUNT-TOKEN
Requirements
An Ubidots account with Industrial plan or higher.
1. Creating a Function
Go to the "devices" tab and select "functions":
Next, create a new function and give it a descriptive name that resembles the parse function you will be executing; in this case we called it "Post data".
In the "HTTPS method" field, select "GET" as the method to trigger the function:
2. Coding your Function
The following code has two functions:
A main function than accepts "args" as an input. This input is a dictionary containing the URL parameters as "key":"value" pairs. For example, if we triggered the function with this URL:
https://parse.ubidots.com/prv/YOUR-USERNAME/parser-name?hello=world¶m1=message1¶m2=message2
Then the main function would receive them like this:
args = {"hello":"world", "param1":"message1", "param2":"message2"}
A ubidotsPost function, which uses the specified token, device_label and a JSON payload as an input, in order to make an HTTP POST request to Ubidots' API.
By using these two functions, we obtain the ability to (1) map the URL parameters to individual variables inside the function (token, device_label, and a JSON payload containing the variables and values to be sent), and (2) run the ubidotsPost function to send the obtained data to Ubidots:
var request = require('request-promise');
async function main(args) {
// Get the device label from the request URL, then erase it from the args payload
var device_label = args.device_label;
delete args['device_label'];
// Get the token from the request URL, then erase it from the args payload
var token = args.token;
delete args['token'];
// Make POST request to Ubidots
var post_response = await ubidotsPost(token, device_label, args);
// Pass Ubidots' API response to the function' response
return post_response;
}
async function ubidotsPost(token, device_label, data) {
var options = {
method: 'POST',
url: 'https://industrial.api.ubidots.com/api/v1.6/devices/' + device_label + '?force=true',
body: data,
json: true,
headers: {
'Content-Type': 'application/json',
'X-Auth-Token': token
}
};
return await request.post(options);
}
3. The result
If we paste the URL below into our browser, we can obtain the {"status_code": "201"} responses from Ubidots' API stating the data was posted successfully!
And then of course, if we go to our Ubidots account, we see a device with label "abdc" with the respective variables and values being updated at the intervals your function is scheduled to run on.