@ubidots/ubidots-javascript-library
TypeScript icon, indicating that this package has built-in type declarations

1.1.1 • Public • Published

Table of contents

Overview

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.

Features

Supported entities

For the time being, the library supports the following entities from the API:

Supported field filters

The library supports all of Ubidots Field filters on each corresponding entity.

Installation

For a new project

  1. Initialize with Yarn or npm:
yarn init
# or
npm init
  1. Add the library to the project
npm i @ubidots/ubidots-javascript-library --save-dev
# or
yarn add @ubidots/ubidots-javascript-library -D

For existing projects

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

Importing the library

Depending on whether your project uses CommonJS or ES Modules, import the library as follows:

CommonJS

const { Ubidots } = require('@ubidots/ubidots-javascript-library');

ES Modules

import { Ubidots } from '@ubidots/ubidots-javascript-library';

Usage

// 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
});

Examples

Get devices

  • Get all devices in the account:

    const allDevices = await Ubidots.devices.all();
  • Get the first device in the account:

    const firstDevice = await Ubidots.devices.first();
    // This is equivalent to
    const firstDevice = (await Ubidots.devices.all())[0];
  • Get the first 1000 devices in the account:

    const devicesPaginated = (await Ubidots.devices.paginate(1, 1000)).results;
  • Get lastActivity field from devices

    const allDevicesLastActivity = await Ubidots.devices.addRawParam('fields', 'lastActivity').get();
  • Get lastActivity and variablesCount fields from all devices

    const device = await Ubidots.devices
      .addRawParams({
        fields: 'lastActivity,variablesCount',
      })
      .get();
  • Get lastActivity and variablesCount fields from a specific device using its label

    const device = await Ubidots.devices
      .addRawParams({
        label: 'temperature_sensor', //label of the device
        fields: 'lastActivity,variablesCount',
      })
      .get();
  • Get a device by label or id:

    // 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();
  • Get a set of devices based on their type:

    const devicesByType = await Ubidots.devices.where('deviceType').exact('temperature-devices').get();

Get variables

  • Get all variables in the account:

    const allVariables = await Ubidots.variables.all();
  • Get the first variable in the account:

    const firstVariable = await Ubidots.variables.first();
    // This is equivalent to
    const firstVariable = (await Ubidots.variables.all())[0];
  • Get the first 100 variables in the account:

    const variablesPaginated = (await Ubidots.variables.paginate(1, 100)).results;
    //Equivalent to
    const variablesPaginated = (await Ubidots.variables.paginate()).results;
  • Get lastActivity field from all variables

    const allVariablesLastActivity = await Ubidots.variables.addRawParam('fields', 'lastActivity').get();
  • Get lastActivity and label fields from all variables

    const variables = await Ubidots.variables
      .addRawParams({
        fields: 'lastActivity,label',
      })
      .get();
  • Get lastActivity and label fields from a specific variable

    const variables = await Ubidots.variables
      .addRawParams({
        id: '6452a727df1a8e000c103fce',
        fields: 'lastActivity,label',
      })
      .get();
  • Get a variable by id:

    const variableById = await Ubidots.variables.where('id').exact('6595770b9de79b000dce0eae').first();
  • Get a set of variables based on their label:

    const variablesByLabel = await Ubidots.variables.where('label').exact('temperature').get();

Send data to a variable

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' });

Get all users in the account

const allUsers = await Ubidots.users.all();

Get all organizations in the account

const allOrganizations = await Ubidots.organizations.all();

Get all devices asigned to an organization

const org = await Ubidots.organizations.where('id').exact('668fffcd88e37d000da10dd0').first();
const orgDevices = await org.devices.all();
orgDevices.forEach(device => {
  // Do something with each device
});

Get all dashboards in the account

const allDashboards = await Ubidots.dashboards.all();

Ubidots API

Access the Ubidots API via the Ubidots class.

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.

Ubidots class properties

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.

Ubidots class methods

Method Arguments Description
authenticate A valid Ubidots token Authenticates with the Ubidots API.

Usage

Authentication

Authentication using a valid Ubidots token is mandatory to use the library:

Ubidots.authenticate('BBFF-ubidots-token');

Instantiation

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');

General syntax

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]);

Filters syntax

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.

getMethods

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

Field filters

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

Using where method

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

Using addRawParams method

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'

Ubidots objects

The following are relevant types within the library.

Entity objects

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);

Entity object methods

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>

Paginator 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.

Readme

Keywords

none

Package Sidebar

Install

npm i @ubidots/ubidots-javascript-library

Weekly Downloads

2

Version

1.1.1

License

ISC

Unpacked Size

240 kB

Total Files

8

Last publish

Collaborators

  • juandavidtangarifehernandez
  • angelozdev
  • woakas
  • ubidevel