In this tutorial, we describe step by step process of application creation for LaMetric that will use OAuth2 authorization and display GitHub followers.

Requirements:

As a result, we should get something like this:


Creating LaMetric App

Steps:

  1. Go to developer.lametric.com
  2. Create indicator app with single frame:

  3. Fill in fields:
    1. Communication type should be “Poll”.
    2. Field “Enter URL for your data” should contain URL of your local or public Web Service (or alias) that returns JSON object in format described in “Data Format” field. We are going to create Web Service a little later.
    3. Сhoose 1 minute for Poll frequency. Many APIs have access rate limits. LaMetric application has exponential backoff algorithm in place to handle access rate limit errors. It will start increasing polling interval exponentially on errors.
  1. Now add options to your app:
    1. In order to access GitHub’s APIs we need to authorise your app’s user on GitHub using OAuth2. We will need to register our LaMetric application on github.com and get Client ID, Client Secret, Redirect URI and Scope (permissions).

    2. Go to www.github.com/settings/developers and press “Register new application” button:

    3. You should get something like this:
    4. Copy Client ID and Client Secret to your LaMetric App’s settings. Also, copy “Authorization callback URL” value to “Redirect URI” field of your LaMetric App’s settings.
    5. Also, fill “Scope” field with the correct scope from the GitHub documentation https://developer.github.com/v3/oauth/#scopes. In our case, it should be “repo,user”.


Creating LaMetric GitHub Web Service

LaMetric poll application requires Web service to translate response from 3rd party Web services to the one LaMetric app understands. 

You can create Web Service using any technology you are familiar with such as NodeJS, Python, PHP, etc.

In this tutorial, we will use NodeJS and SailsJS as MVC framework.

Requirements:

Steps:

  1. Install NodeJS and SailsJS
  2. Create new project. Go to terminal and execute these commands:
    1. $ sails new github
    2. $ cd github
    3. $ sails generate api github
      As a result this file structure should have been created: 
    4. $ sails lift

Now check if you have your Web Service up and running – open http://localhost:1337/github. You should get an empty JSON array.

Now it is time to create our REST API implementation. It consists of 4 files – GithubController.js, GitHubService.js, RequestService.js and config/github.js. When source files are created file structure should look like this: 


api/controllers/GithubController.js

/**
 * GithubController
 *
 * @description :: Server-side logic for managing githubs
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */
module.exports = {
        followers : function(req, res) {                
                console.log("Headers: ", req.headers);
                console.log("Query Parameters: ", req.query);
                GitHubService.getMyInfo(req.headers, req.query, function(err, response, data) {
                        if (err) {
                                return res.send(err)
                        };
                        var responseObj={};
                        responseObj.frames=[];
                        var frame = {
                                'index':0,
                                'text': data.followers,
                                'icon':'i305',
                        };
                        responseObj.frames.push(frame);
                        if (!data) {
                                console.log("Error: ", response.statusCode);
                                res.status(response.statusCode).send(response.body);
                        }else{
                                console.log("Response: ", responseObj);
                                return res.status(200).json(responseObj);
                        }
                })
        },
};

 

api/services/GitHubService.js 

module.exports = {
        /**
         * Method: getMyInfo
         * @return json
         * returns Gets authenticated user profile
         */
        getMyInfo: function(headers, parameters, callback) {
                var url = sails.config.github.baseUrl+'/user';
                var postHeader={
                                'User-Agent': headers.host,
                                'Accept':"application/vnd.github.v3+json",
                                'Authorization':headers.authorization // pass authorization header received in request
                        };
                RequestService.getData(url, postHeader, callback);
        },
}

  

api/services/RequestService.js

var request = require('request');
module.exports = {
        /**
         * Method: getData
         * @return json
         * returns Response called API method
         */
        getData: function(url, header, callback) {
                request.get({
                        url: url,
                        headers: header,
                        rejectUnauthorized: true,
                }, function(error, response, body) {
                        if (error) {
                                callback(error, response, null);
                        } else {
                                try {
                                        callback(null, response, JSON.parse(body));
                                } catch (err) {
                                        callback(err, response);
                                }
                        }
                });
        }
}

 

config/github.js

// config/github.js
module.exports.github = {
  baseUrl: 'https://api.github.com',
};

 

When all files are in place and ready – it is time to start Sails again with command
$ sails lift

Your rest service should be available at http://localhost:1337/github/followers.

Final Steps

Now look for your server IP address and update your LaMetric App data with URL in form http://<ip address or domain>:1337/github/followers, save and publish.

 


Open your LaMetric mobile application, go to Store and install your app. 


 

And finally the result! The number of your GitHub followers on the screen! 

Have fun experimenting and creating more awesome and useful apps for LaMetric!


The entire Web service project can be found on GitHub