Hi there, it’s been a long time before I wrote some tutorials I’ve learned from some video tutorials that I want to share. I’m doing this not just to copy their works but to make sure that I’ve understood how it works. Let’s start with what we need. We all know that I’m a huge fan of NodeJS and Javascript so Let’s start :). And thank you to my Online Teacher Rob Percival 🙂 He is so awesome.

NPM dependencies:“body-parser”: “1.15.2”,”express”: “^4.14.0″,”underscore”: “^1.8.3

    1. Create a folder on your desktop/documents


    1. name the folder todo-api


    1. Open the terminal and go to the folder by typing the “cd Desktop/todo-api” or “cd Documents/todo-api”


    1. Once done, create a server.js file by typing “touch server.js”


    1. Open the file by typing “open server.js” the computer will use your default editor


    1. Here’s the first part, we will add the NPM package that we have downloaded.( If you don’t know how to install npm package, please type on the terminal “npm install express underscore body-parser –save”.)


    1. On the server.js file, we have to initialize the following npm package and the array variable\n
      1. var express = require('express'); // add express package
        var app = express(); //common developers style apply the express to app variable
        var bodyParser = require('body-parser'); // add body-parser for getting the data from the form
        var _ = require('underscore'); //add the underscore npm package
        var port = process.env.PORT || 3000; // setting up the port of our node app
        var todos= []; // setup the array of tods
        var todoNextId = 1; // A bad practice to add the counter variable in the code it shold be added in the database
        app.use(bodyParser.json()); // make sure to use the bodyParser.json
    2. We will define our Routes for the application.
        1. app.get('/',function(req,res){
           res.send('TODO API ROOT');
          }); // getting to the root page
        1. //get all todos with query parameter request
          // sample /todos?q=love&completed=true
          app.get('/todos', function(req, res) {\
           var queryParams = req.query; // contains the URL query parameters (after the ? in the URL).
           var filteredTodos = todos; // ARRAY of todos //we will check if the user will use a query param for completed 
           if (queryParams.hasOwnProperty('completed') && queryParams.completed === 'true') {
           filteredTodos = _.where(filteredTodos, {
           completed: true
           } else if (queryParams.hasOwnProperty('completed') && queryParams.completed === 'false') {
           filteredTodos = _.where(filteredTodos, {
           completed: false
           } //we will check if the cu will search for description\n 
           if (queryParams.hasOwnProperty('q') && queryParams.q.length > 0) {
           filteredTodos = _.filter(filteredTodos, function(todo) {
           return todo.description.toLowerCase().indexOf(queryParams.q.toLowerCase()) > -1;\
           n\ n res.json(filteredTodos); // returned all the filtertodos
        1. //GET the full details of specific Todo\napp.get('/todos/:id',function(req,res){\n  var todoId = parseInt(req.params.id,10);\n  var matchedTodo = _.findWhere(todos,{id:todoId}); // code from underscore where you will return the selected todos.\n \nif(matchedTodo){\n  res.json(matchedTodo);\n}else{\n  res.status(404).send();\n}\n\n});\n
        1. //adding new todos:\n// /todos\n\napp.post('/todos',function(req,res){\n  var body = _.pick(req.body,'description','completed');\n\n  if(!_.isBoolean(body.completed) || !_.isString(body.description) || body.description.trim().length === 0) {\n    return res.status(400).send();\n  }\n\n  body.description = body.description.trim();\n  //add id field\n  body.id = todoNextId++;\n  //pusy body into array\n  todos.push(body);\n\n\n  res.json(body);\n});
        1. //deleting selected todo\napp.delete('/todos/:id',function(req,res){\n\n  var todoId = parseInt(req.params.id);\n  var matchedTodo = _.findWhere(todos,{id: todoId});\n\n  if(!matchedTodo){\n    res.status(404).json({"error": "no todo found with that id"});\n  }else{\n    todos = _.without(todos,matchedTodo);\n    res.json(matchedTodo);\n  }\n});ja
        1. //update selected todo.\n\napp.put('/todos/:id', function(req,res){\n  var todoId = parseInt(req.params.id);\n  var matchedTodo = _.findWhere(todos,{id: todoId});\n\n  var body = _.pick(req.body,'description','completed');\n  var validAttributes = {};\n\n  if(!matchedTodo){\n    return res.status(404).send();\n  }\n\n\n  if(body.hasOwnProperty('completed') && _.isBoolean(body.completed)){\n      validAttributes.completed = body.completed;\n    }else if(body.hasOwnProperty('completed')){\n      // Bad\n      return res.status(404).send();\n    }else{\n      // never provided attribue: no problem here\n    }\n  if(body.hasOwnProperty('description') && _.isString(body.description) && body.description.trim().length >0){\n    validAttributes.description = body.description;\n\n  }else if(body.hasOwnProperty('description')){\n    return res.status(404).send();\n  }\n\n  // HERE final update\n\n  _.extend(matchedTodo, validAttributes);\n\n  res.json(matchedTodo);\n  \n});
        1. app.listen(port,function(){\n  console.log('server is now running');});//setting up the port for nodejs app


    1. Once done and save the file.


  1. You can test the complete application that I’ve uploaded to https://kingmhar-todo-api.herokuapp.com using the POSTMAN.
      1. GET ALL TODOSgotodo
      1. GET SPECIFIC TODOSgotodoid
      1. ADDING NEW TODOSpostingtodo
      1. DELETING TODOSdeletingtodo
      1. UPDATING TODOSdeletingtodo

You can also visit the complete code in my github  https://github.com/kirahmadlare/todoapi.

Happy coding 🙂 If you need to know more about this application. Please let me know and maybe I can help you.