Nowadays, web api is one of the most popular topic in our mobile world. And with NodeJS together with express framework, defining a web api takes minutes.

Basic API Definition With Express

Express framework initializer is very handy to create our example. To make use of it simply install it from npm. This will create express executable under /usr/bin/

1
npm install express-generator -g

Usage of express generator is also very easy. Execute the below command after installing express-generator and this will create the folder structure for you and some samples included to start your web application directly.

1
express firstapi

In this post, I am concentrating on API, so I haven’t provided a view engine for express. If I like to than all I need to do is call express like;

1
express ---view=pug firstapp

for pug view engine. I am planning to write another post for pug engine also but for now lets go back to our first web api with NodeJS and Express.
After executing the above command, it will create a folder called ‘firstapp’. Go to that directory and install the dependencies.

1
2
cd firstapi
npm install

Now we are ready with our application, but we can remove some unnecessary files generated like CSS and default views, since we are creating a web api here.

1
rm -rf public views

The routing is already handled under app.js file that is generated and server creation is handled under bin/www file. So, now we are ready with our API structure. I am going to left the details of these files for another post.

The only remaining thing left is to write our first api GET method. This will be our welcome to our api. Under routes directory Here express generator already generated two routes for you, but this routes are trying to render a web page. We are going to deal with index.js and let users.js as it is.

Let’s change index.js with our favorite editor. (vim in my case) Edit this file like below;

1
2
cd routes
vim index.js

index.js

1
2
3
4
5
6
7
8
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
res.json({ message : "Welcome to My First API"});
});
module.exports = router;

After these changes, try your web api. Execute;

1
2
3
4
npm start
# Example Output
> firstapi@0.0.0 start /home/ubuntu/projects/firstapi
> node ./bin/www

To see the output just browse http://localhost:3000
The default port for express generated application is 3000. If everything goes well, you should see something like this.

1
{"message":"Welcome to My First API"}

Writing a Post Method

Let’s write our first post method also. So that we have the most common rest api calls in place. Open the index.js file and add the below code under our get method.

index.js

1
2
3
4
5
6
7
8
router.post('/', function(req, res, next) {
var name = req.body.name;
if(name){
res.json({ message : "Welcome to my first api " + name});
} else {
res.json({ message : "Welcome, but I don't know your name."});
}
});

You can try this with post via an api test tool. I would recommend Postman or Restlet Client. Here the post body should contain a json as below;

1
2
3
{
"name" : "Volkan Nazmi Metin"
}

And you need to see an output like;

1
2
3
4
5
6
7
8
#Output with name as above
{
"message": "Welcome to my first api Volkan Nazmi Metin"
}
#Output without name or empty body
{
"message": "Welcome, but I don't know your name."
}

Lets also integrate one more thing to our api for fun. It is a good practice to measure your api performance at all times. There is a realy good and simple npm package (response-time) for NodeJS to accomplish this. Go to firstapi folder and execute;

1
npm install response-time --save

This will install the response-time npm package and also update your package.json file. To make it work, open your app.js file and edit as follows;

1
2
3
4
5
6
7
8
9
10
11
12
// ....
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
// Add this line
var responseTime = require('response-time');
// ...
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// And this line
app.use(responseTime());
// ..

After you restart your api (kill node and npm start) and call for your new get and post methods, you will see an additional header information that tells you the requests response time (cpu time). Here how your new header looks like;

1
2
3
4
5
6
7
Connection → keep-alive
Content-Length → 50
Content-Type → application/json; charset=utf-8
Date → Tue, 07 Mar 2017 10:27:53 GMT
ETag → W/"32-3heCmpVClrd08MKwYxBj2Q"
X-Powered-By → Express
X-Response-Time → 0.766ms // This is the newly added header after response time functionality.

The End for this post and thanks for reading. I know, we have gaps to still fill and you may have questions, please comment.

See the source used in this post from github