- Overview
- Features
- Supported entities
- Supported field filters
- Installation
- Importing the library
- Usage
- Examples
- Ubidots API
This JS Library provides an intuitive and easy-to-use interface to interact with Ubidots' API. It allows sending data to devices and/or perform CRUD (Create, Read, Update, Delete) operations over the library supported entities.
- Pre-defined request to Ubidots API via the library's methods.
- Custom request building taking advantage of Ubidots Field filters via filtering methods.
For the time being, the library supports the following entities from the API:
The library supports all of Ubidots Field filters on each corresponding entity.
- Initialize with Yarn or npm:
yarn init
# or
npm init
- Add the library to the project
npm i @ubidots/ubidots-javascript-library --save-dev
# or
yarn add @ubidots/ubidots-javascript-library -D
Go to the project's root directory and run:
npm i @ubidots/ubidots-javascript-library --save-dev
# or
yarn add @ubidots/ubidots-javascript-library -D
Depending on whether your project uses CommonJS or ES Modules, import the library as follows:
const { Ubidots } = require('@ubidots/ubidots-javascript-library');
import { Ubidots } from '@ubidots/ubidots-javascript-library';
// Uncomment to import the library using the correct syntax as outlined above
// const { Ubidots } = require('@ubidots/ubidots-javascript-library');
// or
// import { Ubidots } from '@ubidots/ubidots-javascript-library';
// Authenticate with the API
Ubidots.authenticate('<ubidots-token>');
// Get first 100 devices from the account
ubidots.devices.get().then(devices => {
// Prints an array of Device objects
console.log(devices);
// YOUR LOGIC OVER THESE 100 DEVICES
});
-
const allDevices = await Ubidots.devices.all();
-
const firstDevice = await Ubidots.devices.first(); // This is equivalent to const firstDevice = (await Ubidots.devices.all())[0];
-
const devicesPaginated = (await Ubidots.devices.paginate(1, 1000)).results;
-
const allDevicesLastActivity = await Ubidots.devices.addRawParam('fields', 'lastActivity').get();
-
const device = await Ubidots.devices .addRawParams({ fields: 'lastActivity,variablesCount', }) .get();
-
const device = await Ubidots.devices .addRawParams({ label: 'temperature_sensor', //label of the device fields: 'lastActivity,variablesCount', }) .get();
-
// By label const temperatureDevice = await Ubidots.devices.where('label').is('temperature_device_1').first(); //By id const temperatureDevice = await Ubidots.devices.where('id').is('some-id').first();
-
const devicesByType = await Ubidots.devices.where('deviceType').exact('temperature-devices').get();
-
const allVariables = await Ubidots.variables.all();
-
const firstVariable = await Ubidots.variables.first(); // This is equivalent to const firstVariable = (await Ubidots.variables.all())[0];
-
const variablesPaginated = (await Ubidots.variables.paginate(1, 100)).results; //Equivalent to const variablesPaginated = (await Ubidots.variables.paginate()).results;
-
const allVariablesLastActivity = await Ubidots.variables.addRawParam('fields', 'lastActivity').get();
-
const variables = await Ubidots.variables .addRawParams({ fields: 'lastActivity,label', }) .get();
-
const variables = await Ubidots.variables .addRawParams({ id: '6452a727df1a8e000c103fce', fields: 'lastActivity,label', }) .get();
-
const variableById = await Ubidots.variables.where('id').exact('6595770b9de79b000dce0eae').first();
-
const variablesByLabel = await Ubidots.variables.where('label').exact('temperature').get();
Get the device object and the variable object:
// Get the device object
const temperatureDevice = await Ubidots.devices.where('label').exact('temperature_device_1').first();
// Get the variable object
const temperatureVariable = await temperatureDevice.variables.where('label').exact('temperature').first();
- Send a value
temperatureVariable.sendDot(34);
- Send a value with timestamp
temperatureVariable.sendDot(40, new Date().getTime());
- Send a value with timestamp and context
temperatureVariable.sendDot(4, new Date().getTime(), { status: 'cold' });
const allUsers = await Ubidots.users.all();
const allOrganizations = await Ubidots.organizations.all();
const org = await Ubidots.organizations.where('id').exact('668fffcd88e37d000da10dd0').first();
const orgDevices = await org.devices.all();
orgDevices.forEach(device => {
// Do something with each device
});
const allDashboards = await Ubidots.dashboards.all();
Access the Ubidots API via the Ubidots class.
The Ubidots
class provides sub-classes for interacting with each particular supported entity.
For example, to use the Devices API you can do:
Ubidots.devices.<methods>
Here, the methods exposed by the devices
sub-class allow consuming the whole
Devices API.
Property | Description |
---|---|
devices | provides access to Devices API |
variables | provides access to Variables API |
dashboards | provides access to Dashboards API |
users | provides access to Users API |
organizations | provides access to Organizations API |
Note: From now on, these properties will be addressed as entity
or entities
to reflect the fact that they enable
interacting with that part of the API. With this in mind, device entity
refers to the property of the Ubidots
class
that allows interacting with the Devices API.
Method | Arguments | Description |
---|---|---|
authenticate | A valid Ubidots token | Authenticates with the Ubidots API. |
Authentication using a valid Ubidots token is mandatory to use the library:
Ubidots.authenticate('BBFF-ubidots-token');
This class is implemented as a Singleton which is instantiated when it is exported, thus, there is no need for creating an instance of it. Instead, you must use it directly:
// Import the class
const { Ubidots } = require('@ubidots/ubidots-javascript-library');
// Call 'authenticate' method with no prior instantatio of 'Ubidots'
Ubidots.authenticate('ubidots-valid-token');
As stated before, the Ubidots class exposes its methods through entities
for a particular
part of the API such as devices or variables, thus providing the following syntax:
Ubidots.<entity>.<getMethod>(, [args]);
Field filtering is available for each
entity
through the following syntax:
Ubidots.<entity>.<filterMethod>(args).<getMethod>(, [args]);
Here:
-
<entity>
is any of the valid entities. -
<filterMethod>
is either of these 2 methods:where()
addRawParams()
-
<getMethod>
Either of the below methods to retrieve entities:
Note: Neither where
nor addRawParams
methods perform the request to the API, they just build the URL with the
corresponding query params. In order to actually perform the request, it is required to concatenate a calling to any of
the <getMethods>
after the filter statements.
These methods are common to all entities
. They are designed to perform requests on the
specified entity
and return the corresponding data.
Method | Description | Usage | Arguments | Response |
---|---|---|---|---|
all |
Returns a list of all entity objects |
Ubidots.<entity>.all(); |
None | <entity-object>[] |
get |
Returns a list of the first 100 entity objects in the account |
Ubidots.<entity>.get(); |
None | <entity-object>[] |
first |
Returns the first entity object in the account |
Ubidots.<entity>.first(); |
None | <entity-object> |
paginate |
Performs a paginated request to retrieve entity objects. |
Ubidots.<entity>.paginate([page, [size]]) |
page: number Page number to retrieve
size: number Max number of results per page
|
paginator |
Just as the Ubidots API supports requests using Field filters as:
GET https://industrial.api.ubidots.com/api/v2.0/devices/?label__startswith=temp
This library also provides a way to construct custom requests that take advantage of said filters.
Filter method | Description | Usage | Arguments | Response |
---|---|---|---|---|
where |
Applies a filter on a single property of the given entity
|
Ubidots.<entity>.where(<entity-property>).<filter>(<filter-value>).<get-method>(, [args]) |
A valid property of the given entity
|
Depends on the <get-method> used |
addRawParams |
Applies filters on multiple properties of the given entity
|
Ubidots.<entity>.addRawParams(<query-object>).<get-method>(, [args]) |
query-object: object An object containing queryparam-value pairs
{ queryParam1: value1 ··· queryParamN: valueN } |
Depends on the <get-method> used |
The example request above can be performed using where
as:
const tempDevices = await Ubidots.devices.where('label').startswith('temp').get();
Here:
<entity> = devices
<entity-property> = 'label'
<filter> = startswith
<filter-value> = 'temp'
<get-method> = get
The example request above can be performed using addRawParams
as:
const filterParameters = {
label__startswith: 'temp',
};
const tempDevices = await Ubidots.devices.addRawParams(filterParameters).get();
Here:
<entity> = devices
<queryObject> = filterParameters
<get-method> = get
<queryParam1> = label__startswith
<value1> = 'temp'
The following are relevant types within the library.
An entityObject
reflects the JSON representation of entities from the API, but it is provided
with 3 methods that allow interacting with that particular instance.
Suppose that you retrieve data from a device as:
const firstDevice = await Ubidots.devices.first();
here, firstDevice
is an object containing all the properties of the dictionary representation from the API:
{
"properties": {
"_color": "#EA6F4C",
"_icon": "cloud-sun",
"_location_fixed": {
"lat": 6.2486,
"lng": 75.5742
}
},
"createdAt": "2019-11-25T19:35:08.975270Z",
"description": "some description",
"id": "6e309da44fc8455a9cceb5aa",
"isActive": true,
"label": "first-device",
"lastActivity": null,
"name": "First Device",
"organization": {
"id": "af92e4c82bf1d39cc21882f5b",
"label": "my-first-customer",
"name": "My First Customer",
"url": "http://industrial.ubidots.com/api/v2.0/organizations/af92e4c82bf1d39cc21882f5b"
},
"tags": ["first"],
"url": "http://industrial.ubidots.com/api/v2.0/devices/6e309da44fc8455a9cceb5aa",
"variables": "http://industrial.ubidots.com/api/v2.0/devices/6e309da44fc8455a9cceb5aa/variables",
"variablesNumber": 1
}
But, not only this object has the properties shown above, you can also invoke the following methods on firstDevice
:
firstDevice.refresh();
firstDevice.update(args);
firstDevice.save(args);
Method | Description | Usage | Arguments | Response |
---|---|---|---|---|
refresh |
Returns the most recent state of the entityObject from the server. |
Ubidots.<entity>.<get-method>(, [args]).refresh() |
None | <entity-object> |
update |
Updates the entityObject fields on the server with the values given in the object passed as argument. |
Ubidots.<entity>.<get-method>(, [args]).update(props) |
props: obbject An object with at least 1 valid property of the given entity
|
<entity-object> |
save |
Updates the entire entityObject on the server with the values given in the object passed as argument. |
Ubidots.<entity>.<get-method>(, [args]).save(props) |
props: oject An object containing all properties of the given entity
|
<entity-object> |
When invoked, the paginate
method returns a paginator
object with the following properties and methods:
{
next(): `paginator`,
previous(): `paginator`,
refresh(): `paginator`,
page: `int`,
results: `entityObject[]`,
size: `int`
}
Properties | Type | Description |
---|---|---|
page |
int |
Represents the current page number in the pagination sequence |
size |
int |
Indicates the count of entity objects in the current. |
results |
entityObject[] |
An array of entity objects present on the current page. |
Methods | Return | Description |
---|---|---|
next |
paginator |
Returns a new paginator instance, with the page property set to the next page (one ahead of the current page). |
previous |
paginator |
Returns a new paginator instance, with the page property set to the previous page (one less than the current page). |
refresh |
paginator |
Re-executes the current request and returns the updated paginator object with refreshed data. |