Developing a Node.js REST API on IBM Bluemix

On our latest series of post we develop a JEE application using IBM Bluemix.

For this post we are using Node.js SDK with the same CRUD services for a People Administrator API. In general you can use the same testing approaches we review on our post Testing a REST API just review and modify the URL you are using.

Node.js is a platform build on Chrome┬┤s JavaScript runtime. Its non-blocking event driven model allows it to be efficient. Also it allows easily to provide two-ways connections between client and server.

On this tutorialWhy The Hell Would I Use Node.js? A Case-by-Case Tutorial is presented in detail the advantages and disadvantages of using Node.js over other platforms.

We will divide the development on two posts, 1)Develop the base REST services and 2) Connect the services to the database.

This post is divided on three(3) sections: 1)Setup Bluemix instances and services, 2)Setup the Node.js application and 3)Develop the REST services

Setup Bluemix

– Login into Bluemix or create a free trial account
– Select + Create An App
– On Runtimes Select SDK for Node.js
sdk nodejs
– Set a name and a host
On the last step you can connect your project and connected to IBM DevOps Services

Create SQL Service

– After the app is created select the app from the dashboard
– Select add a new Service
– Go to Data Management and select SQL Database
SQL Database
– Add a name a finalize

Develop the base application

On this section we will show you briefly how to develop a simple app

Setup App.js

– First add the required libraries, Express.js will run your REST services, we will not use the full features on this project since Express.js is better suite for web GUI applications.
– Second setup the database connector plugging ibmdb
– Third where the REST services will actually be implemented

var express = require('express');
var ibmdb = require('ibm_db');
var people = require('./routes/people');

– Now set the variables we get from VCAP, this will provide all the connection to the DB information
var appInfo = JSON.parse(process.env.VCAP_APPLICATION || "{}");
var services = JSON.parse(process.env.VCAP_SERVICES || "{}");
var host = (process.env.VCAP_APP_HOST || 'localhost');
var port = (process.env.VCAP_APP_PORT || 3000);

if (process.env.VCAP_SERVICES) {
    var env = JSON.parse(process.env.VCAP_SERVICES);
    db2 = env['sqldb'][0].credentials;
}
else{
        console.error("INFORMATION FOR DB CONNECTION NOT FOUND");
}
var dbConnection = "DRIVER={DB2};DATABASE=" + db2.db + ";UID=" + db2.username + ";PWD=" + db2.password + ";HOSTNAME=" + db2.hostname + ";port=" + db2.port;
console.log("Connection String: " + dbConnection)

– Now set the REST HTTP methods, previously we setup the variable var people = require(‘./routes/people’) that uses the file /routes/people.js
app.get('/find/:id',people.find(ibmdb,dbConnection));
app.get('/create',people.createDB(ibmdb,dbConnection));
app.get('/delete',people.deleteDB(ibmdb,dbConnection));
app.get('/',people.list(ibmdb,dbConnection));
app.post('/',people.create(ibmdb,dbConnection));
app.put('/',people.update(ibmdb,dbConnection));
app.delete('/:id',people.remove(ibmdb,dbConnection));

– Finally start the server
app.listen(port, host);
console.log('App started on port ' + port);

Setup Dependencies

We must define on the package.json the libraries the project will use

{
	"name": "NodePeopleAdmin",
	"version": "0.0.1",
	"description": "Developing a Node.js REST API on IBM Bluemix",
	"dependencies": {
		"express": "3.4.7",
		"ibm_db":"0.0.1",
		"body-parser":"1.5.2"
	},
	"engines": {
		"node": "0.10.26"
	},
	"repository": {}
}

– You can search for the versions locally using the npm search command

Deployment File

Finally you can create a manifest.yml file so you don’t have to explicitly use the information when pushing into the Bluemix server

applications:
- services:
- PeopleDB
disk_quota: 1024M
host: at3node
name: NodePeopleAdmin
command: node app.js
path: .
domain: mybluemix.net
instances: 1
memory: 128M

Implement Base REST Project

On this section we will implement the base code we define on the routes/people.js file to provide the REST services
– The normal services that do not receive anything will be as follows

exports.createDB = function(ibmdb, dbConnection) {
	return function(req, res) {
		res.send('createDB');
	}
}

exports.deleteDB = function(ibmdb, dbConnection) {
	return function(req, res) {
		res.send('deleteDB');
	}
}

exports.list = function(ibmdb, dbConnection) {
	return function(req, res) {
		res.send('list');
	}
}

– The services that receive a path param are defined before using ‘:’ on the app.js file i.e. app.get('/find/:id',people.find(ibmdb,dbConnection)); and are read using var id = req.param('id');
exports.remove = function(ibmdb, dbConnection) {
	return function(req, res) {
		var id = req.param('id');
		res.send(id);
	}
}

– Finally to read the Json objects we read the body data using var data = req.body; as follows:
exports.update = function(ibmdb, dbConnection) {
	return function(req, res) {
		var data = req.body;
		res.send(data);
		
	}
}
exports.create = function(ibmdb, dbConnection) {
	return function(req, res) {
		var data = req.body;
		res.send(data);
	}
}

– Thats it your app is ready to be deploy

Deploy app

To deploy your app you need to install the cf command line tool, you can find more info at Installing the cf command line interface documentation
– First install the tool
– Then login into the service using cf login provide your username and password
– For this step you should be on the route of the project where the manifest.yml is located
– Finally upload your code using cf push, the manifest.yml file need to have the app name you set on Bluemix
– If there are any issues you can review them using cf logs with the App Name which will present the console of the instance, this will keep showing changes on the server
– however if you just want to see the log file use the –recent flag as cf logs --recent

Now test the url and you should see the word list or whatever you use for the default get HTTP command.

On our next post we will show you how to actually connect to the database and store the data

For more information follow us at Facebook or in our Twitter @AdvTeknology

Code
Here is the complete code of the app running
https://hub.jazz.net/project/advtek/NodePeopleAdmin/

References

On this section we show you the post we use to help us develop this app

https://www.ng.bluemix.net/docs/templates/nodejshelloworld.jsp
http://www.ibm.com/developerworks/cloud/library/cl-bluemix-nodejs-app/
http://thoughtsoncloud.com/2014/07/getting-started-ibm-bluemix-node-js/
http://www.ibm.com/developerworks/cloud/library/cl-math-app/index.html

Leave a Reply