Build a NodeJS API within 10 Minutes

Let’s build a NodeJS API using MongoDB and the Express framework within 10 minutes. I’ll show you in this tutorial exactly how to do it. Let’s get started.

API Orchestration with Node.js on z/OS
Example to API Orchestration with Node.js on z/OS
Image credits: IBM

Pre-Reqs for this Tutorial:

  • Basic understanding of REST APIs
  • JavaScript knowledge (somewhere between basic to intermediate)
  • CRUD operations

To give you guys a refresher about REST Architecture.

What is REST architecture?

REST stands for REpresentational State Transfer. REST is web standards based architecture and uses HTTP Protocol. A REST Server simply provides access to resources and REST client accesses and modifies the resources using the HTTP protocol. Here each resource is identified by URIs/ global IDs. REST uses the various representations to represent a resource like text, JSON, XML but JSON is the most popular one.

Let’s get started

I’m assuming you have already NodeJS setup installed but if you don’t then see the step-by-step guide for that here.

Once you have “package.json, the next step is to install the dependencies.

npm install --save express mongodb@(version) body-parser

P.S: Replace the (version) with the appropriate version you want to install.

Next up, we can create our “server.js file to build our API.

Server (server.js)

All of these dependencies should be ready in your file.

const express        = require('express');
const MongoClient    = require('mongodb').MongoClient;
const bodyParser     = require('body-parser');
const app            = express();

Once that’s done, we need to specify a port so that our app can start listening to the HTTP requests.

const port = 8000;
app.listen(port, () => {
  console.log('The port in use :' + port);
});

P.S: 8000 is commonly used for internet radio streams using Nicecast/Icecast/Shoutcast/Winamp audio streaming. Also commonly used as an alternate HTTP port. Some firewalls use it for HTTP web administration.

Let’s build our routes

In Express, routes are wrapped in a function, which takes the Express instance and a database as arguments.

module.exports = function(app, db) {};

You can then export this function through your index.js:

const noteRoutes = require('./note_routes');
module.exports = function(app, db) {  noteRoutes(app, db);  // Other route groups could go here, in the future};

Then import it for use in server.js:

const express = require('express');const MongoClient    = require('mongodb').MongoClient;const bodyParser     = require('body-parser');
const app = express();
const port = 8000;
require('./app/routes')(app, {});app.listen(port, () => {  console.log('We are live on ' + port);});

Note that since you don’t have a database yet set up, you’re just passing in an empty object.

Okay, now you can make your CREATE route.

The syntax is simple:

module.exports = function(app, db) {  app.post('/notes', (req, res) => {    // You'll create your note here.    
res.send('Hello')  });};

Nice! You created your first real route.

Next step is to add some parameters to your request and process them in your API and, finally, add in your database.

Last step to your preliminary route: set up the database, and then add your data in.

The easiest way to set up a Mongo database is through mLab: it’s free for the smallest size, and quite fast to setup.

Once you create an account and a MongoDB deployment, add a user to the database with a username and password:

Now in your server.js, you can use the MongoClient to connect to your DB, and use this to wrap your app setup:

const express = require('express');const MongoClient = require('mongodb').MongoClient;const bodyParser = require('body-parser');const db             = require('./config/db');
const app = express();
const port = 8000;
app.use(bodyParser.urlencoded({ extended: true }));
MongoClient.connect(db.url, (err, database) => {  if (err) return console.log(err)  require('./app/routes')(app, database);
app.listen(port, () => {    console.log('We are live on ' + port);  });               })

We got it!

That’s it! You have a working Node API with one of the four major CRUD operations. Similarly, you can implement Read, Update and Delete operations with their relevant routes.

I’ll try to update this article with those other 3 operations as well, but if I don’t, I’m sure you can do it by yourself wth a few tinkering here and there! 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *