Creating Web API Using Node.js And MySQL

Do you know creating RESTful API using node.js and Express Template is as easy as making tea or coffee?? Seriously!!! So, in this tutorial, we will see how to create a basic RESTful API using node.js with MySQL as database.

From this article, I am starting a series for creating To-Do applications in Angular 2 which will use node.js as a back-end. It is part 1 of the series. We will start by performing the CRUD (Create,Read,Update,Delete) operation in node.js. Our API will accept GET, POST, PUT, and DELETE requests.

Before starting with creating API in node.js, below are the steps for setting up the environment. You will also need to install MySQL Server either locally or on a remote machine. You can get it easily with XAMPP or WAMP.

Setting up the environment

  • Install node.js.
  • Install Express generator.

    cmd> npm install express -generator -g

    node.js

  • Install Express Template of node.js.

    1. cmd> express  

    Here, in this example, I am using Express template for node.js. The above code creates a sample node.js project ready for us.

    node.js


  • Install dependency for MySQL.

    cmd> npm install mysql --save


    As I am using MySQL as my database, so I need to install dependencies of MySQL into my project. By writing the above command, we will add the dependency to package.json file.

    node.js

  • Install Cors

    cmd> npm install cors --save

    As we know, CORS (cross -origin resource sharing) is important while creating API, the above code will install the dependency of CORS into package.json file.

    node.js

  • Install all the dependency of package.json

    cmd> npm install


    node.js

Setting up the table in mysql

  1. script file  
  2. for table[code language = "sql"]  
  3. CREATE TABLE IF NOT EXISTS `task` (`Id`  
  4.     varchar(50) NOT NULL, `Title`  
  5.     varchar(500) DEFAULT NULL, `Status`  
  6.     varchar(100) DEFAULT NULL, PRIMARY KEY(`Id`)) ENGINE = InnoDB DEFAULT CHARSET = latin1;  
  7. --Dumping data  
  8. for table `task`  
  9.     --  
  10.     INSERT INTO `task` (`Id`, `Title`, `Status`) VALUES('1''Go to Market tomorrow''done'), ('2''Email to manager''pending'), ('3''Push code to GitHub''done'), ('4''Go For Running''done'), ('5''Go to Movie''pending');  
  11. [/code]  
Creating the API using node.js

Now, as we are done with environment setup and database, we need a file which can connect to the database. So, let’s create a file called dbconnection.js and inside the file, we will store the information to connect with the database. In below example, I am connected to the local database which was created above. You can connect to a remote database by simply changing your host, username, and password.

create dbconnection.js

  1. [code language = "javascript"]  
  2. var mysql = require('mysql');  
  3. var connection = mysql.createPool({  
  4.     host: 'localhost',  
  5.     user: 'root',  
  6.     password: '',  
  7.     database: 'demo'  
  8. });  
  9. module.exports = connection;  
  10. [/code]  
Building Task model

Create Task.js file inside the models folder, as shown following.

node.js

As we are done with setting up the connection, now we will create the model for Task. Create a folder called models and inside that folder, create Task.js file. Our Task model contains five methods - getAllTasks, getTaskById, addTask, updateTask, and deleteTask.

First we need to include the dbconnection module which we created earlier in our Task model.

Task.js
  1. [code language = "javascript"]  
  2. var db = require('../dbconnection'); //reference of dbconnection.js  
  3. var Task = {  
  4.     getAllTasks: function(callback) {  
  5.         return db.query("Select * from task", callback);  
  6.     },  
  7.     getTaskById: function(id, callback) {  
  8.         return db.query("select * from task where Id=?", [id], callback);  
  9.     },  
  10.     addTask: function(Task, callback) {  
  11.         return db.query("Insert into task values(?,?,?)", [Task.Id, Task.Title, Task.Status], callback);  
  12.     },  
  13.     deleteTask: function(id, callback) {  
  14.         return db.query("delete from task where Id=?", [id], callback);  
  15.     },  
  16.     updateTask: function(id, Task, callback) {  
  17.         return db.query("update task set Title=?,Status=? where Id=?", [Task.Title, Task.Status, id], callback);  
  18.     }  
  19. };  
  20. module.exports = Task;  
  21. [/code]  
Setting up the Routes

Although, we have created the dbconnection and task model but without setting up the routes, we can’t really do anything with what we created so far. Each route is an HTTP method, either GET, PUT, POST, or DELETE, with a specific URL end-point.
  1. [code language = "javascript"]  
  2. router.get('/:id?'function(req, res, next) {  
  3.     if (req.params.id) {  
  4.         Task.getTaskById(req.params.id, function(err, rows) {  
  5.             if (err) {  
  6.                 res.json(err);  
  7.             } else {  
  8.                 res.json(rows);  
  9.             }  
  10.         });  
  11.     } else {  
  12.         Task.getAllTasks(function(err, rows) {  
  13.             if (err) {  
  14.                 res.json(err);  
  15.             } else {  
  16.                 res.json(rows);  
  17.             }  
  18.         });  
  19.     }  
  20. });  
  21. [/code]  
Now, let’s understand what we did. We just created the router.get method, which will be executed when user requests HTTP GET method. We can call route.get method with or without parameter; i.e., parameter id is optional. We can create the optional parameter by simply adding " ? " as postfix. So, first it will check whether the id is passed or not. If id is passed, then it will call the Task.getTaskById method which is created previously in Task.js model; otherwise, it will call Task.getAllTasks method.
  1. [code language = "javascript"]  
  2. router.post('/'function(req, res, next) {  
  3.     Task.addTask(req.body, function(err, count) {  
  4.         if (err) {  
  5.             res.json(err);  
  6.         } else {  
  7.             res.json(req.body); //or return count for 1 & 0  
  8.         }  
  9.     });  
  10. });  
  11. [/code]  
It is executed when user requests for HTTP POST method. It will call the Task.AddTask method and pass the data as req.body parameter. It will return the task object on successful insertion or return error message if insertion failed.

Over all Tasks.js


Here, in routing file, we need to include Task.js which is created previously inside the models folder.
  1. [code language = "javascript"]  
  2. var express = require('express');  
  3. var router = express.Router();  
  4. var Task = require('../models/Task');  
  5. router.get('/:id?'function(req, res, next) {  
  6.     if (req.params.id) {  
  7.         Task.getTaskById(req.params.id, function(err, rows) {  
  8.             if (err) {  
  9.                 res.json(err);  
  10.             } else {  
  11.                 res.json(rows);  
  12.             }  
  13.         });  
  14.     } else {  
  15.         Task.getAllTasks(function(err, rows) {  
  16.             if (err) {  
  17.                 res.json(err);  
  18.             } else {  
  19.                 res.json(rows);  
  20.             }  
  21.         });  
  22.     }  
  23. });  
  24. router.post('/'function(req, res, next) {  
  25.     Task.addTask(req.body, function(err, count) {  
  26.         if (err) {  
  27.             res.json(err);  
  28.         } else {  
  29.             res.json(req.body); //or return count for 1 & 0  
  30.         }  
  31.     });  
  32. });  
  33. router.delete('/:id'function(req, res, next) {  
  34.     Task.deleteTask(req.params.id, function(err, count) {  
  35.         if (err) {  
  36.             res.json(err);  
  37.         } else {  
  38.             res.json(count);  
  39.         }  
  40.     });  
  41. });  
  42. router.put('/:id'function(req, res, next) {  
  43.     Task.updateTask(req.params.id, req.body, function(err, rows) {  
  44.         if (err) {  
  45.             res.json(err);  
  46.         } else {  
  47.             res.json(rows);  
  48.         }  
  49.     });  
  50. });  
  51. module.exports = router;  
  52. [/code]  
Setting up the app.js

This is the main entry point of node.js application. When user requests any method, first it will be redirected to app.js then from the app.js it will be redirected to requested routes. So, one can say it a configuration file.

We need to set a few lines in app.js, as following.
  • var cors=require('cors');
  • var Tasks=require('./routes/Tasks');
  • app.use(cors());
  • app.use('/Tasks',Tasks);

After including these lines, your app.js will look like these.

  1. [code language = ”javascript”]  
  2. var express = require('express');  
  3. var path = require('path');  
  4. var favicon = require('serve-favicon');  
  5. var logger = require('morgan');  
  6. var cookieParser = require('cookie-parser');  
  7. var bodyParser = require('body-parser');  
  8. var cors = require('cors');  
  9. var routes = require('./routes/index');  
  10. var users = require('./routes/users');  
  11. var Tasks = require('./routes/Tasks');  
  12. var app = express();  
  13. // view engine setup  
  14. app.set('views', path.join(__dirname, 'views'));  
  15. app.set('view engine''jade');  
  16. // uncomment after placing your favicon in /public  
  17. //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));  
  18. app.use(cors());  
  19. app.use(logger('dev'));  
  20. app.use(bodyParser.json());  
  21. app.use(bodyParser.urlencoded({  
  22.     extended: false  
  23. }));  
  24. app.use(cookieParser());  
  25. app.use(express.static(path.join(__dirname, 'public')));  
  26. app.use('/', routes);  
  27. app.use('/users', users);  
  28. app.use('/Tasks', Tasks);  
  29. // catch 404 and forward to error handler  
  30. app.use(function(req, res, next) {  
  31.     var err = new Error('Not Found');  
  32.     err.status = 404;  
  33.     next(err);  
  34. });  
  35. // error handlers  
  36. // development error handler  
  37. // will print stacktrace  
  38. if (app.get('env') === 'development') {  
  39.     app.use(function(err, req, res, next) {  
  40.         res.status(err.status || 500);  
  41.         res.render('error', {  
  42.             message: err.message,  
  43.             error: err  
  44.         });  
  45.     });  
  46. }  
  47. // production error handler  
  48. // no stacktraces leaked to user  
  49. app.use(function(err, req, res, next) {  
  50.     res.status(err.status || 500);  
  51.     res.render('error', {  
  52.         message: err.message,  
  53.         error: {}  
  54.     });  
  55. });  
  56. module.exports = app;  
  57. [/code]  
Done  -- we are all set to run this newly created RESTful API.

npm start


node.js

The following table summarizes the routes we will be using and the method that will be called.

Path Request Type
http://localhost:3000/Tasks GET
http://localhost:3000/Tasks/1 GET
http://localhost:3000/Tasks/1 DELETE
http://localhost:3000/TasksPOST (pass data in body)
http://localhost:3000/Tasks/1 PUT (pass data in body)

To test the API, I am using REST Client tool of Mozilla Firefox. You can use POSTMAN in Google chrome.

http://localhost:3000/Tasks

node.js

http://localhost:3000/Tasks/1

node.js

Click here to download the Demo.Want to host RESTful API on Heroku Server? Have a look at my post Hosting Web API On Heroku Server.

Conclusion

We have seen how simple it is to create a RESTful API using Node.js, Express, and MySQL. Guys, isn’t it easy? You can download the full source code from github from the above link.

Hope it will be helpful to you!! If it helped you to understand basic node.js REST API, then please share and comment on it.

Thanks!!

Up Next
    Ebook Download
    View all
    Learn
    View all