Filter results by

Your first Web app

This sample application authenticates with ARTIK Cloud, sends data messages on behalf of a sample device, and retrieves the data messages from ARTIK Cloud.

This app uses ARTIK Cloud's Javascript SDK and the sample code is available on GitHub.

In this tutorial, you will learn how to:

We recommend reviewing ARTIK Cloud's REST APIs and Authentication documentation. You should also have a basic understanding of Node.js, Express, and JavaScript.

Prerequisites

  • Node.js (Version >= 6.5.0)
  • npm (Version >= 3.10.0)

Initial setup

If this is your first time using ARTIK Cloud, first create an ARTIK Cloud Account. You will also use these web tools:

  • For developers building apps, services, and devices using ARTIK Cloud, we created the Developer Dashboard.
  • Regular users of ARTIK Cloud (and your apps) can manage permissions, connect devices, and review their data at My ARTIK Cloud.

Create an application

Follow these instructions to create an ARTIK Cloud application using the Developer Dashboard. For this tutorial, select the following:

  • Set "Auth Redirect URL" to http://localhost:3000/callback/artikcloud.
  • Choose "Authorization Code (with secret)" for Authentication.
  • Under "Profile Permissions", check "READ".
  • Click the "Set permissions for a specific device" link.
  • Choose "Example Activity Tracker" as the device type (unique name: cloud.artik.example.activitytracker).
  • Enable "READ" and "WRITE" permissions for this device type.

After creating the application, note the client ID and client secret, which you will need for the configuration file.

Project setup

  • Before running the sample, fill out config.json with the client ID and client secret.
1
2
3
4
{  
   "client_id": "your client id",   
   "client_secret": "your client secret"
}
  • Install dependencies by running the following command.

    $ npm install

  • Run the project.

    $ npm start

Load the web application at http://localhost:3000 in your browser, and learn more in the Demo section.

Demo

Here's a preview of how our simple web app will work.

  • Load http://localhost:3000 in your browser.
    ARTIK Cloud first Web app

  • Log in and grant permissions (the permission screen is only shown once).
    ARTIK Cloud first Web app

  • You are redirected back to the app with your name shown.
    ARTIK Cloud first Web app

  • Click "Create Device" to add the Example Activity Tracker to your account.
    ARTIK Cloud first Web app

  • Click "Send a message" to send a message.
    ARTIK Cloud first Web app

  • Click "Get a message" to get the latest message sent by your device.
    ARTIK Cloud first Web app

  • After running the sample, clean up by deleting any Example Activity Tracker devices you added to your account. You can do this in the Devices menu at https://my.artik.cloud.

Implementation details

Below are the files of interest:

File Description
config.json Configuration; specify the client ID, client secret, redirect URI, etc.
package.json Configuration; include ARTIK Cloud library
routes/index.js Server-side code; define routes, make API calls
public/javascript/apps.js Client-side javascript code
views/index.pug View template; renders HTML to your browser

Login and obtain access token

Login is implemented using the OAuth2 Authorization Code method.

  • Use the GET /signin endpoint for users to log into ARTIK Cloud and initiate the OAuth2 login flow.
1
https://accounts.artik.cloud/signin?client_id=YOUR-CLIENT_ID&response_type=code&redirect_uri=https://localhost:3000/callback/artikcloud&state=abcdefgh
  • Upon successful user login, the browser will be redirected to the defined redirect_uri (http://localhost:3000/callback/artikcloud) as below:
1
http://localhost:3000/callback/artikcloud?code=0ee7fcd0abed470182b02cd649ec1c98&state=abcdefgh 
  • The server extracts the authorization code from the above query parameters. Use the POST /token endpoint to exchange the authorization code for a user token (one of the three types of access tokens).

The code exchange is demonstrated in the following server code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
router.get("/callback/artikcloud", function(req, res, next) {
  
  //verify state to prevent XSRF
  //https://tools.ietf.org/html/rfc6749#section-10.12
  if(req.query.state !== req.session.state) {
    return res.redirect('/');
  };
  
  exchangeCode(req, res, next);

});

function exchangeCode(req, res, next) {
    console.log("exchanging code ...");
    var data = {
        'grant_type': 'authorization_code',
        'client_id': Config.client_id,
        'client_secret': Config.client_secret,
        'redirect_uri': Config.redirect_uri,
        'code': req.query.code
    };
  
  var headers = {
      'Content-Type': 'application/x-www-form-urlencoded'
  };
  
  var host = 'accounts.artik.cloud';
  var path = '/token';

  //api call to exchange code
  postRequest(host, path, headers, data, function(result){
    
    console.log('exchanged code with result:', result);
    req.session.token = JSON.parse(result);
    req.session.save();
    return res.redirect('/');
  
  });
};
  • After successfully exchanging the code, we store the access token in the session. This simplifies our sample code for easy retrieval of the access token later in the application.

In a production environment, redirect_uri must use an "https" (secure) address to protect the authorization code from eavesdropping. This sample is intended as a tutorial. Be sure to follow best security practices in your organization for all implementations.

Prepare API calls

  • First import the ARTIK Cloud SDK library.
1
2
//import artikcloud library
var ArtikCloud = require('artikcloud-js');
  • Initialize the SDK using the access token (user token) from earlier. The token will be added to the HTTP Request Header for each API call made with the SDK.
1
2
3
4
5
6
7
8
9
10
11
12
13
router.use(function(req, res, next){
  //...
  setTokenARTIKCloud(req.session.token.access_token);
  next();
});

function setTokenARTIKCloud(access_token) {
  var defaultClient = ArtikCloud.ApiClient.instance;
  
  // Configure OAuth2 access token for authorization: artikcloud_oauth
  var artikcloud_oauth = defaultClient.authentications['artikcloud_oauth'];
  artikcloud_oauth.accessToken = access_token;
};

Get user info

The following code snippet uses the UsersAPI() to get information about the currently signed-in user. The user ID has been stored in the session object for easy retrieval.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
router.get("/user/self", function(req, res, next) {
  
  //Get reference to UsersApi()
  var apiInstance = new ArtikCloud.UsersApi();
  var callback = function(error, data, response) {
    
    //handle response
    if (error) {
      res.send(error, error.status);
    } else {
      console.log('API called successfully. Returned data: ' + data);
      req.session.userId = data.data.id;
      res.send(data);
    }
  };
  
  //api call - get details of logged in user 
  apiInstance.getSelf(callback);
};

Visit the REST documentation for more information about this API call.

Create a device

The following code snippet uses the DevicesApi() to create a new device in the user's ARTIK Cloud Account. The newly created device ID has been stored in the session object for easy retrieval.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
router.get("/device/create", function(req, res, next) {
  
  //Get reference to DevicesApi()
  var apiInstance = new ArtikCloud.DevicesApi();
  
  var device = {
    'uid': req.session.userId,    //user
    'dtid': Config.deviceTypeId,  //deviceTypeId
    'name': "Sample Activity Tracker " + randomIntegerBetween(1000,10000);
  };
  
  var callback = function(error, data, response) {
    if (error) {
      res.send(error, error.status);
    } else {
      console.log('API called successfully. Returned data: ' + data);
      req.session.deviceId = data.data.id;
      res.send(data);
    }
  };
  
  //api call - add device
  apiInstance.addDevice(device, callback);
 
});

Visit the REST documentation for more information about this API call.

Send a message

The following code snippet uses the MessagesApi() to send a message on behalf of the device. We can send random heartRate and stepCount values, as shown below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
router.get("/message/send", function(req, res, next) {
  
  //Get reference to MessagesApi()
  var apiInstance = new ArtikCloud.MessagesApi();
  var messageObject = new ArtikCloud.Message();
  
  // data to send to Example Activity Tracker
  var messageData = {
    "heartRate": randomIntegerBetween(70,80),
    "stepCount": randomIntegerBetween(5,10)
  };
  
  messageObject.data = messageData;
  messageObject.sdid = req.session.deviceId;
  
  var callback = function(error, data, response) {
    if (error) {
      res.send(error, error.status);
    } else {
      console.log('API called successfully. Returned data: ' + data);
      res.send(data);
    }
  };
  
  //api call - send message to device
  apiInstance.sendMessage(messageObject, callback);
  
});

Visit the REST documentation for more information about this API call.

Get a message

The following code snippet uses the MessagesApi() to get the last message that was sent by the device.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
router.get("/message/get", function(req, res, next) {
  
  //Get reference to MessagesApi()
  var apiInstance = new ArtikCloud.MessagesApi();
  
  var opts = {
    'sdids': req.session.deviceId, 
    'count': 1
  };
  
  var callback = function(error, data, response) {
    if (error) {
      res.send(error, error.status);
    } else {
      console.log('API called successfully. Returned data: ' + data);
      res.send(data);
    }
  };
  
  //sample api call - get last message sent to device
  apiInstance.getLastNormalizedMessages(opts, callback);
  
});

Visit the REST documentation for more information about this API call.