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

Middleware :Backbone of Express.js Part 1

 

Now, you can deploy your Node.js app to App Engine standard environment

 

Today we will discuss most important topic for developing web application in Node.js using Express framework.Express is a minimal and flexible framework for web and mobile application.A Express application is essentially a series of Middleware function calls one after another.

Middleware is core concept behind Express.js.

Because Middleware is core concept behind experss.js in case request processing and routing so,with better understanding of Middleware can be able help us to construct maintainable application with less line of code.
Middleware in Express
When the Express.js is running,it is listening to request.Each request is processed according to a defined chain of Middleware and routes, starting from top to bottom.

Request,and Response objects can be accessed by Middleware.

Create Middleware

For creating middleware we have require three parameters first parameter is req i.e requesting object second parameter is res i.e. responding object and our third parameter is next is a function and used for continuing for next Middleware.We will explain i detail latter in upcoming examples.

Example :

Containing Single middleware

In case of single Middleware our application contains single Middleware as we know that Middleware contains three parameters as we discussed previously first parameter is req i.e requesting object second parameter is res i.e. responding object and our third parameter is next is a function and used for continuing for next Middleware because in this case our application contains only one Middleware so our third parameter is optional.


//Declaring express module
var express = require('express');
var app = express();
//Create Middleware
app.use('/',function(req,res){
 console.log("hello World");
})
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 world message on your console.

Containing Multiple Middlewares

When our application contains multiple Middleware then in that case our flow will be from top to bottom and for performing such operation by our Middleware contains three parameters as in above example contain two parameters and in this case our third parameter is next.

Note: next is absolutely a function which is used to continue flow inside our application from top to bottom from one middleware to another.

middleWare.js


var express = require('express');
var app = express();
//Creating first middleware having 3 parameters
app.use('/',function(req,res,next){
 console.log("Start");
 next();
})
//Creating second middleware having 3 parameters
app.get('/',function(req,res,next){
 res.send('Hello middleware');
 next();
})
/*Creating third middleware having 2 parameters it is not mendatory that our
last middleare doesnot contain only two parameters it can also conation third paremeter
and it is good for your better paractice. 
*/
app.use('/',function(req,res){
 console.log("End");
})
//it is port number
app.listen(3000);

Open command prompt and run command


node middleWare.js

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


localhost:3000

And you will obtain result as shown bellow
Middleware in Express

Functionality of Middlware

  1. It can be able to execute any code.
  2. It make changes to request and response process.
  3. It stops after ending request response cycle.
  4. It can call next Middleware function in the stack.

On the basis of Application in Express.js Middleware can be categorized in following types:

  • Application-level middleware
  • Route level middleware
  • Error handling middleware
  • Built-in middleware
  • Third-party middleware

Use Ejs with Express.js

Express is a minimal and flexible Node.js framework which commonly used for developing web and mobile applications.

How to use Express.js ?

Because Express.js is a framework of Node.js hence for using it we have to at first install it and for installing it we use this following command.


npm install express

After executing command our package has been installed. Now we can be able to develop our web application, During developing web application we have also used template Engines for fast development and for speedy execution.

Benefit of template Engines
  1. Enables to use static file in application.
  2. The template replaces variable in a template file with actual values.
  3. At the client-side, Template file transforms into HTML file.

here are various type of templates are available like

  1. Pug
  2. Mustache
  3. EJS

here During developing application we are using EJS Template now we are going to install template and after that proceeding further.

For installing EJS write following command.


npm install ejs

After executing this command we are ready to create .ejs files i.e template files

Now it’s time to develop an application without wasting our time hence before developing an application it is mandatory that you should understand standard folder structure of application and here I have designed a folder structure for application as shown below.

From the above image, you can be able to understand the folder structure of the application. But still, I like to explain some points.

  1. node_modules (folder): contains required packages like express,ejs
  2. server.js: creates a server
  3. rest folders are located inside views folder

So, at first, we create a server for that

 class=”entry-title”server.js



// server.js
// load the things we need
var express = require('express');
var app = express();

// set the view engine to ejs
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/views'));

// use res.render to load up an ejs view file

// index page 
app.get('/', function(req, res) {
    res.render('pages/index');
});

// about page 
app.get('/about', function(req, res) {
    res.render('pages/about');
});

app.listen(3000);
console.log('Ur server is started on 3000');

Now we create include inside views folder which contains 3 files header.ejs, footer.ejs, head.ejs. class=”entry-title”

#krdheeraj #freelearning #selflearning #puppeteer #javascript #node.js
Express is minimal and flexible Node.js framework which commonly used for developing web and Mobile application.

Use Ejs with Express.js

 class=”entry-title”header.ejs


<!-- views/include/header.ejs -->

<nav class="navbar navbar-default" role="navigation">
<div class="container-fluid">

<div class="navbar-header">
<a class="navbar-brand" href="#">
<span class="glyphicon glyphicon glyphicon-tree-deciduous"></span>
EJS Is Fun
</a>

<ul class="nav navbar-nav">
<li><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
</ul>
</div>
</div>
</nav>

footer.ejs

#krdheeraj #freelearning #selflearning #puppeteer #javascript #node.js
Express is minimal and flexible Node.js framework which commonly used for developing web and Mobile application.

Use Ejs with Express.js


<!-- views/include/footer.ejs -->
<p class="text-center text-muted">© Copyright 2018 <a href="http://www.krdheeraj.info/">krdheeraj.info</a></p>

head.ejs class=”entry-title”

#krdheeraj #freelearning #selflearning #puppeteer #javascript #node.js
Express is minimal and flexible Node.js framework which commonly used for developing web and Mobile application.

Use Ejs with Express.js


<!-- views/include/head.ejs -->
<meta charset="UTF-8">
<title>Mean stack Developer</title>

<!-- CSS (load bootstrap from a css folder) -->
<link rel="stylesheet" href="css/bootstrap.min.css">
<style>
body { padding-top:50px; }
</style>

Now it’s time design pages in this application I have add two pages index.ejs and about.ejs class=”entry-title”

index.ejs


<!-- views/pages/index.ejs -->
<!DOCTYPE html>
<html lang="en">
<head>
<% include ../include/head %>
</head>
<body class="container">

<header>
<% include ../include/header %>
</header>

<main>

<div class="jumbotron">
<h1>This is great </h1>
<p>Welcome to templating using EJS</p>
</div>

</main>

<footer>

<% include ../include/footer %>

</footer>

</body>

</html>

 

about.ejs


<!-- views/pages/about.ejs -->

<!DOCTYPE html>
<html lang="en">
<head>
<% include ../include/head %>
</head>
<body class="container">

<header>
<% include ../include/header %>
</header>

<main>
<div class="row">
<div class="col-sm-8">
<div class="jumbotron">
<h1>This is great</h1>
<p>Welcome to templating using EJS</p>
</div>
</div>

<div class="col-sm-4">
<div class="well">
<h3>Great Example of /express.js using templating engine ejs!</h3>
</div>
</div>

</div>
</main>

<footer>
<% include ../partials/footer %>
</footer>

</body>
</html>

Hence, now our web application is ready open command prompt write command


node server.js

then message has been displayed on command prompt

Ur server is started on 3000

it means your server has been started,

Now copy the below link and paste inside browser


localhost:3000

 

Explore more about Express

RESTful API with Express
Middleware: Backbone of Express.js Part 1
Middleware: Backbone of Express.js Part 2