How To Create An Organised API with Node.js??

0
1436
Advertisement

The Below post describes in series with a series of details for target environment & overview of high-level components. It includes the following divisions.

  1. Web Server information.
  2. How to Handle GET requests.
  3. How to Handle POST, PUT & DELETE requests.
  4. How to Add Filtration, Sorting & Pagination for GET request.
  5. DB Basics.

Target Environment

Generally, one can prefer to run Node.js in the host OS & communicate the database(DB) as. You need to follow instructions if you want to do this & require to follow the basic and in-depth follow the installation procedures to get work on your platform.

Advertisement

High-Level Components

We can organize REST API in 4 layers. The requests from HTTP will go through these layers in turn. We have a lot more going on depending on support & features. These are the components required.

  1. Web Server
  2. Router
  3. Controllers
  4. Database API’s

Creating An REST API with Node.js

The required setup & installation required dependencies & node level module for an app in working properly. But in this case, we use MongoDB & NoSQL DB as it is an optimal choice and no requirement for the relational database(DB). Without running & installing it locally we will attach with a sandbox DB on mLAb. But it is suggested that using MongoDB Atlas – for hosting at your database in production.

Step – Installation of npm

Initialize the npm & install the below.

npm init

npm install mongoose

npm install express

npm install body-parser

Mongoose is Object Relational Mapper.

Express is for application as it is a default for many of the Node.js apps today.

Body-parser is a middleware used to parse data sent via HTTP request.

Setting up a Project

For coding, we are to use any of the text editor’s but it is recommended that Visual Studio could be better and hassle-free for coding. We need to create a new file within the editor as an example:: server.js.

We will be Coding in the following file created as below.

const mongoose1 = require(‘mongoose1’);

const express = require(‘express’);

const bodyParser = require(‘body-parser’);

const app = express();

const port = process.env.PORT||3000;

app.use(bodyParser.json());

module.exports = app;

The above-mentioned code provides the capacity for adding express routes which are used for writing for various url’s to the API.

Setting Few Particular Files::

//mongoose.js

var mongoose = require(‘mongoose1’);

mongoose.Promise = global.Promise;

mongoose.connect(process.env.MONGODB_URI);

module.export={mongoose1};

This will allow us for connecting with mLab Mongo Database client.

Setting the UserSchema::

Creating schema will give access to every user in DB-(database) with the specific look. In common, a user contains the following – name, email & password.

mongoose.model(‘User’, UserSchema);

With the above code, we are binding layout of a schema to model named ‘User’. The above mentioned is the access ID used to pull data in DB & the need to export the same in various parts of the program.

//User.js

var mongoose = require(‘mongoose1’);

var Userschema = new.mongoose1.schema(

{

name: string, email: string, password:string

}

);

mongoose1.model(‘User1’, UserSchema);

module.exports = mongoose1.model(‘User1’);

Adding Different Routes

Route are url’s on which users need to click to perform various actions(post, get, delete, put).

With the following, By creating different routing paths to the API. It controls the actions on how the data flow from & into the database. POST request for simple route to be created.

app.post(‘/users/signup’, (req,res)=>{

var body=req.body;

var user=new User1(body);

user1.save().then(

()=>{

res.status(100).send();}).catch((e)=>{res.send(200).send(e);});});

The app has to have a .Post scenario which takes 2 parameters.

  1. Rote which can be linked to the function.
  2. The function itself is the 2 parameter.

It acquires 2 more parameters such as

  1. Request to a server.
  2. Response from a server.

Inside the function, we use User model which contain the values which are to be inserted into the DB. They will be created in a structured schema that we created. After that, the callback function is backed up via another 2 parameters success value & error value. We can check for an error while creating the user & respond accordingly.

JSON data with the Post request shall be containing the below details:

{

“name”:”Lokesh”, “email”:”lokesh@gmail.com”, “password”:”newsboy”

}

For storing the above data in MongoDB

Create User Model & than call the mongoose method of save() with same instance i.e, user1.save() which is already in the code. In the program, we have included status codes of 100 for response as In & for Failure 200 status code to return.

Let us request for all users in the DB.

app.get(‘/users/data’, (reg,res)=>{

sale.find().then((data)=>{

res.status(100).send(JSON.stringify(data,undefined,1))

}).catch((e)=>

res.status(200).send(e));});

The application object has .get, the method that takes 2 parameters.

In the function find() method for a user model also uses 2 parameters. The “Find” is one of the methods which returns the value from the DB.

First parameter – Object – refers the requirement which needs to be fulfilled to return the values. As a result, the above example Object has been empty, All the users from DB will get returned.

Solution

As its only a scraped tip of an iceberg. Its just plain JS view in the same way. To break it down its just a simple code. As the basic level of code for a tutorial purpose.

Advertisement

LEAVE A REPLY

Please enter your comment!
Please enter your name here