Authentication from NodeJS

Follow

Apprenda's REST API provides a way to build helpful and robust client applications utilizing developer-accessible information such as app resource utilization, workload throttling, app metadata and custom properties, and more.

The first step to use the REST API is, of course, to authenticate. This example does so via Javascript in NodeJS:

First, we'll require a couple of Node modules, which can be installed using npm.

var prompt = require('prompt');
var request = require('request');

Then we'll declare some globals that will help us out:

var rootURL = 'https://apps.private.apprendalabs.com'; // change this to the root apps URL of your target environment
var headers = { 'Content-Type': 'application/json', 'accept': '*/*' }; // common request headers that need to be sent with all requests
var apprendaSessionToken; // this is used to store our session token for future API calls

Then we'll collect information from the user via command line using the prompt module - in this case we're prompting the user for username and password, upon successfully getting this information we call establishSession passing the input data:

function getSessionInformation()
{
   
    var credSchema = 
    {
        properties: {
            username: {
                description: "Enter your username",
                required: true
            },
            password: {
                description: "Enter your password",
                hidden: true, 
                required: true
            }
        }
    }
 
    prompt.start();
    prompt.get(credSchema, function (err, result) {
        establishSession(result);
    });
}

And lastly, we call the API to establish our session.  The API returns to us a unique session token that we'll need to send with future API calls:

Snippet

function establishSession(credentials)
{
    
    var options = {
        url: rootURL + '/authentication/api/v1/sessions/developer',
        headers: headers,
        method: 'POST',
        json: credentials
    };
    
   console.log('Authenticating...');
    
    request(options, function (error, response, body) {
        if (response.statusCode != 201) {
            handleError(body.message);
            return;
        }
        apprendaSessionToken = body.apprendaSessionToken;
        console.log('Success!');
    });
}

 

Have more questions? Submit a request

Comments