Quick guidance to build a Node.js API

Node.js seems a bit frightening to beginners, but it is not complicated at all. Here is a small tutorial which will help you to build your own node.js API within a fraction of an hour. This is a very quick and simple guide to Node.js, express framework and MongoDB.

You can access the entire code on GithHub.

Before you start building your API, you should know the basics of JavaScript, CRUD operations and REST APIs. Here you will be creating an API for a simple todo application where you will perform CRUD operations like create, read, update and delete on your todos.

Setting up your Application:

Step 1:
Installing Node.js and MongoDB.

Step 2:
Create your directory structure as follows:

| – node_api
++| – data/
++++++| – todo-schema.js
++| – routes/
++++++| – index.js
++++++| – todoRoutes.js
++| – config.js
++| – package.json
++| – server.js

Step 3:
Setting up your package.json for installing dependencies.

{
  "scripts": {
    "dev": "nodemon server.js"
  },
  "dependencies": {
    "body-parser": "^1.16.0",
    "express": "^4.14.0",
    "mongodb": "^2.2.22",
    "mongoose": "^4.7.8"
  },
  "devDependencies": {
    "nodemon": "^1.11.0"
  }
}

Nodemon is a package that automatically restarts your server when your files change, so I highly recommend installing it as a dev dependency. Then you can write a script in your package.json under ‘scripts‘ which will run your server just by the command: npm run dev.

Express – Framework
MongoDB – Database
Mongoose – MongoDB object modeling tool
BodyParser – Handle JSON requests

Now let’s add basic config in the config.js file:

module.exports = {
  url : 'mongodb://localhost/todo',
  port: 3000
};

The URL above is the path for your mongo database.

Let’s start on the API by setting up your server.js. First, require all the dependencies.

const express        = require('express');
const mongoose       = require('mongoose');
const bodyParser     = require('body-parser');
const app            = express();
const config         = require('./config');

mongoose will be used to interact with your database. You will have to initialize your app as an instance of express, the framework used. For managing the database, you can use RoboMongo which is a MongoDB manager. Let’s create a database in MongoDB via RoboMongo. Before that make sure MongoDB is running on your machine. In order to run MongoDB, navigate to the bin repository of your installed MongoDB instance and run the following command: mongod.exe. In a new terminal, navigate to bin again and run the command: mongo.exe.

Now start RoboMongo and you see the following screen.

Untitled.png

Click on connect and go ahead. By default, the server runs on port 27017. Let’s create a database. You will see the following screen after connecting.

Untitled.png

Right click on New Connection in the left pane and you shall see an option- ‘create database’, clicking on that you will get the above dialog box, add your database name and you are good to go. Then add your collections there. So this is one way to create the database, you can also do this via the mongo shell and use RoboMongo only for viewing your data.

This is how you can create the schema for for your collection in /data/todo-schema.js

var mongoose = require("mongoose");

// Create a new schema for a todo
var schema = new mongoose.Schema({
  todo : String,
  state : String
});

module.exports = mongoose.model('urls', schema);

Your final server.js will look as follows:

const express        = require('express');
const mongoose       = require('mongoose');
const bodyParser     = require('body-parser');
const app            = express();
const config         = require('./config');

app.use(bodyParser.urlencoded({ extended: true }));

// your app will be running at this port
const port = process.env.PORT || config.port;

// connect to your mongo database
mongoose.connect(config.url);

// import the routes
require('./routes')(app, {});

// Listening on the port
app.listen(port, () => {
  console.log('We are live on ' + port);
});

Let’s write our routes /routes/todoRoutes.js

const Todo = require('../data/todo-schema');

module.exports = function(app, db) {

// Creating a todo
app.post('/todo', (req, res) => {
  const todo = new Todo ({
    todo: req.body.todo,
    state: req.body.state
  });
  todo.save(function (err, data) {
    if (err) {
      console.log("an error occurred", err);
    } else {
      res.send(data);
    }
   })
});

// Fetching all todos
app.get('/todos' , (req, res) => {
  Todo.find({}, function (err, todos) {
    if (err) {
      cosole.log("an error occurred", err);
    } else {
      res.send(todos);
    }
  })
});
};

You can now test these api calls using Postman, by making a call to localhost:3000

For the POST call, that is to create a todo the url will be localhost:3000/todo and we need to send the body according to the schema defined:

Untitled.png

In the above image, you can see that a POST call is made to localhost:3000/todo and we need to send the body as key value pair. To add those key value pairs, you can click on x-www-form-urlencoded radio button. TheseAnd in response, you get the JSON data which is the newly created object and the object has been given a unique id by MongoDB. So this is how you can create an API call for posting data.

Similarly, you can make a GET call to use our GET API call to fetch all the created todos in our database:

Untitled.png

As you can see in the above image, A GET call is made to localhost:3000/todos to fetch all the todos.

So this how you create very basic APIs in Node JS. Prior knowledge of JavaScipt is a must. Also, MongoDB knowledge like creating of database and collections and performing CRUD operations on the same is required. So the way we created POST, GET calls, we can also have DELETE and UPDATE calls for deleting and updating a todo respectively.

You can get the entire code on GitHub. Feel free to contact for any queries.

Now start building your own API, explore NODE JS and you will love it.

Happy Coding until next time!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s