Web
Analytics
building rest api with node.js and express | Angular | ASP.NET Tutorials

For Consultation : +91 9887575540

Stay Connected :

Step 1: Create a Node application and install dependencies.

npm init
npm install --save express
npm install --save body-parser
npm install --save underscore
npm install --save nodemon





Step 2: Create a movies.json file and add following code.

[{
    "Id": "1",
    "Title": "DDLJ",
    "Director": "Karan Johar"
   
   },
   {
    "Id": "2",
    "Title": "Sholey",
    "Director": "Sippi"
   
   },
   {
    "Id": "3",
    "Title": "Fashion",
    "Director": "MB"
   
   }
   
  ]

Step 3: Create new file index.js and  add following code into index.js.

var express    = require('express');        // call express
var app        = express();                 // define our app using express
var bodyParser = require('body-parser');
var jsondata= require('./movies.json');
var _und = require('underscore');

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

var port = process.env.PORT || 8080;      

var router = express.Router();      

router.get('/', function(req, res){
res.json(jsondata);

})
router.post('/postdata', function(req,res){
if(req.body.Id && req.body.Title)
{
jsondata.push(req.body);
res.json(jsondata);
}
else
{
    console.log('please put some values to insert');
}

})
router.put('/updatedata/:id', function(req,res){
if(req.params.id)
{
_und.each(jsondata , function(elem, index){
if(req.params.id === elem.Id){
    elem.Title = "Hello Brother";

    elem.Director = "xyz";
}

})
res.json(jsondata);
}
else
{
    console.log('Invalid Request');
}

})

router.delete('/deletedata/:id', function(req, res) {
    getindextodelete = -1;
    if(req.params.id){

        _und.each(jsondata, function(elem,index){
if(elem.Id === req.params.id){
    getindextodelete  = index;
  

}

        })
        if(getindextodelete > -1)
        {
            jsondata.splice(getindextodelete ,1);
        }

    res.json(jsondata);   
    }
    else{
        console.log('Please pass body elements with id');
    }
});

app.use('/api', router);
app.listen(port);

Step 4: Run Program and test it on postman.

nodemon index.js