RESTful API with Express

REST Stands for Representational State Transfer and in simple words we can say that REST APIS are way to interact with backend and perform CRUD Operations using HTTP verbs.

REST is not an architecture, but rather an architectural style.

According to Wikipidea
REST is an architectural style that defines a set of constraints and properties based on HTTP. Web services that conforms to REST architectural style termed RESTful. web services provide interoperability  between computer systems on the internet. more
Architectural Constraints of REST

REST defines 6 architectural constraints which make any web service – a true RESTful API.

  1.  Uniform Interface
  2. Client-Server
  3.  Stateless
  4. Cacheable
  5. Layered System
  6. Code on Demand(optional)

Uniform Interface: Once a developer becomes familiar with one of your API, he should be able to follow the similar approach for other APIs.

Client-Server: Servers and clients may also be replaced and developed independently, as long as the interface between them is not altered.

Stateless: No client context shall be stored on the server between requests. The client is responsible for managing the state of the application.

Layered System: REST allows you to use a layered system architecture where you deploy the APIs on server A, and store data on server B and authenticate requests in Server C.

Code on Demand(optional): All above constraints help you build a truly RESTful API and you should follow them. Still, at times you may find yourself violating one or two constraints. Do not worry, you are still making a RESTful API – but not “truly RESTful”.

For further understanding I am explaining with an example and below is folder structure of REST API example

Rest API Application

During creation of APIs generally we design separate file in separate folder like

  • controller: It contains business logic of API
  • Model: It stores Database Schema of API
  • routes: It contains router file of API

Now we are designing our files
index.js



const express=require("express");
const routes=require("./routes/readFileRoutes");
const fs=require("fs");
const app=express();
//listen port
app.listen(3000,()=>{
    console.log("Port has been satrted \nplease check port 3000");
    routes.setRoutes(app);


})

routes/readFileRoutes.js



/**
 * containing routing part of application
 *
 */
const routeControl=require("./../constroller/readController");
const express=require("express");

let setRoutes=(app)=>{
  
    app.get('/readUser',routeControl.readUserFile);
}

module.exports={
 
    setRoutes:setRoutes

}


controller/readController.js



/**
 * containing logial part of application
 *
 */
const fs=require("fs");

let readUserFile = (req,res) => { 

    fs.readFile("./user.json", 'UTF-8', (err, data) => {
        if (err) {
            console.log(err);
        } else {
            console.log(data);
            res.send(data);
        }
    })

}
module.exports={
    readUserFile:readUserFile
}


user.json



{
    "userInfo":[
        {"firstName":"Jon","lastName":"Karter","age":38,"eyeColor":"Brown"},
        {"firstName":"Aish","lastName":"Roy","age":48,"eyeColor":"Blue"},
        {"firstName":"Jackie","lastName":"Chain","age":58,"eyeColor":"Brown"},
        {"firstName":"Tom","lastName":"Cruse","age":38,"eyeColor":"Brown"},
        {"firstName":"Angle","lastName":"Peter","age":38,"eyeColor":"Black"},
        {"firstName":"Mickie","lastName":"Magri","age":38,"eyeColor":"Brown"}
    ]
}

Now for reading your file just open your terminal and type



node index.js

After that open your Browser paste link as given below



http://localhost:3000/readUser

MongoDb installation on Windows 32 bit System
Rest API in Angular 4
Angular 4 Service Tutorial
Angular 4 Component Tutorial

Middleware :Backbone of Express.js Part 2

Hi codeteasers,

In previous post we had discussed about basic of middleware.In this post we will see some different aspects of middleware. Before starting new aspects of middleware  at first revised what we had learnt  previously.

    • What is middleware?
    • Basic examples of middleware containing single middleware and containing multiple middleware.
    • Functionality of Middleware.
    • Types of Middleware

Middleware in Express

In this post we will learn how and where we have to use different types of middleware.So, before starting new concepts about middleware at first I summarized previous concept about middleware.

  • Conceptually middleware is a way to encapsulate functionality that operates on an HTTP request to your application.
  • Middleware is simply a function that contains three parameters req,  res and next.

            var express=require('express');

            var app=express();

            app.use(function(req,res,next){
               console.log('hello middleware');
              });
           app.listen(3000);

Run application

Open command prompt and run command


node middleWare.js

After that to see your result open your browser and copy link.


localhost:3000

After refreshing browser you got hello middlewaremessage on your console.

  • Middleware has access to request and response object.
  • Next method tells middleware to use next middleware , if inside a middleware you don’t call next() method then at that middleware our request terminates.

Now we come to point that inside this post we will learn about different types of middleware and how to use these middleware.

Conceptually middleware is classified into five categories.
  • Application-level middleware
  • Route-level middleware
  • Error handling middleware
  • Built-in middleware
  • Third-party middleware
Application-level middleware

A middleware that effects whole application is known as application level middleware.

Application-level middleware starts with app.use and app.method.

for further understanding of Applicaton-level middleware we go through an Example.


Var app=require(‘express’);

app.use(function(req,res,next){

console.log(‘Hello Application-level middleware’);
});
app.listen(3000);

Run application

Open command prompt and run command


node applicationmiddleWare.js

After that to see your result open your browser and copy link.


localhost:3000

After refreshing browser you got Hello Application-level middlewaremessage on your console.

where app denotes objects for whole application

Route-level middleware

Rout-level middleware is same as Application-level middleware but basic difference is that it bound instance of express.Router() instead of express() .


       Var express=require(‘express’);

        var router= express.Router();

       router.use(function(req,res,next(){

       console.log('Router middleware Router Example first middleware');

       /* to call next middleware we use next method*/

      next();

      });
     app.listen(3000);

Run application

Open command prompt and run command


node routmiddleWare.js

After that to see your result open your browser and copy link.


localhost:3000

After refreshing browser you got Router middleware Router Example first middlewaremessage on your console.

Error handling middleware

Error handler middleware is same as other middleware like Application-level middleware and

Route-level middleware functions but difference is that it contains four parameters instead of three parameters.


var express=require('express');

var app=express();

 app.use(function(err,req,res,next){

     console.error(err.stack)
     
     res.status(500).send('Something broke');


}); 

app.listen(3000);

Run application

Open command prompt and run command


node errormiddleWare.js
Built-in middleware

The middleware functions that previously included with Express but now seperate in express modules.

Express has following built-in middleware functions.

express.static
Syntax  : express.static(root,[options])
express.json 
synatx  : express.json([options])
express.urlncoded 
syntax : express.urlncoded()
Third-party middleware

Express apps uses third party modules for adding functionality of application.

Installing required node.js module for adding required functionality inside application.

Below example shows installing and loading the cookie-parsing middleware function cookie-parser.
Installing cookie-parser


npm install cookie-parser

Implementation


      var express = require('express');

      var app = express();

      var cookieParser = require('cookie-parser');

      // load the cookie-parsing middleware

      app.use(cookieParser())

You should also visit
Use Ejs with Express.js

Node.js Database Connectivity with Postgresql

PostgreSQL Operation with Node.js

Create Server in Node.js