MySQL Data Access API Development Using Express.JS, Node.JS

In this article, we are looking into the introduction of Node.JS and Express.JS and then, I am going to create a simple MySQL data access API using Express.js, NodeJS.

As we all know, Node.JS is the most trending open source technology that’s directly or indirectly partitioning into advanced web development, and let’s have lookup what is Node.JS?

Node.JS Definition

Node.JS is a platform that provides environment (outside the web browser) to execute JavaScript and which is built on Chrome's V8 JavaScript engine developed by Ryan Dahl.

Why Node.JS?

NodeJs processing model depends on a single thread with event looping.

When clients send HTTP requests to NodeJs server, the Event loop is woken up by OS. It will pass the request and response objects as JavaScript closures to worker functions with callbacks.

For long-running jobs like I/O operations running on non-blocking worker threads, when the job is complete, responses are sent to the main thread via a callback. Event loop returns result to the client.

NodeJs has following features,

  • Consistently asynchronous
  • Event Driven, Lightweight
  • Same language on client\server
  • NPM, Yarn (built-in support for package management)
  • Built Http/https server, sockets
  • Develop Real-time, Web, Mobile applications

Node.JS is not best platform for

  • Heavy Server-Side Computation/Processing

Node.JS System Module

  • events - To handle events
  • fs - To handle the file system
  • http - To make Node.js act as an HTTP server
  • https - To make Node.js act as an HTTPS server.
  • net - To create servers and clients
  • os - Provides information about the operation system
  • path - To handle file paths

Node.JS Installation

  • Download the Windows installer from the js® web site.
  • Run the installer (the .msi file you downloaded in the previous step.)
  • Follow the prompts in the installer (Accept the license agreement, click the NEXT button a bunch of times and accept the default installation settings).
  • To see if Node is installed, open the Windows Command Prompt, PowerShell or a similar command line tool, and type node -v.
  • To see if NPM is installed, type npm –v. (NPM is a package manager for Node.js packages or modules)

Express.JS

The express framework provides an abstraction layer above HTTP module to make handling web traffic (Request/ Response) with developing middleware and APIs. There are also tons of middleware available to complete the common task for express frameworks, such as- CORS, XSRF, POST parsing, Cookies etc.

  • JS framework is built on Node.JS HTTP module.
  • We can install Express.Js global by just type npm install -g express in command prompt.

Now, we have our development environment ready with NodeJS, Express.js installation. And, I am going to demonstrate how we can create MySQL data access API using Node.JS and Express.js.

Let’s start with creating a folder as “sample-api”.

  • Open a folder in command prompt and type ‘npm init’ to initiate the project.

    Node.JS

  • Enter details like project name, version, description etc. then type ’Yes’.
  • It will create a JSON file inside sample-api folder which contains the information regarding the project and NPM package that are needed into this project. We called dependencies.

    Node.JS

  • Now, we are creating a MySQL table for users and their transaction details, as below.
    1. --  
    2. -- Table structure for table `users`  
    3. --  
    4. DROP TABLE IF EXISTS `users`;  
    5. CREATE TABLE `users` (  
    6.   `UserID` int(11) NOT NULL AUTO_INCREMENT,  
    7.   `Namevarchar(45) DEFAULT NULL,  
    8.   PRIMARY KEY (`UserID`)  
    9. ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;  
    10.   
    11. --  
    12. -- Table structure for table `transactions`  
    13. --  
    14. DROP TABLE IF EXISTS `transactions`;  
    15. CREATE TABLE `transactions` (  
    16.   `TransactionId` int(11) NOT NULL AUTO_INCREMENT,  
    17.   `UserId` int(11) DEFAULT NULL,  
    18.   `TransactionAmount` decimal(10,2) DEFAULT NULL,  
    19.   `Balance` decimal(10,2) DEFAULT NULL,  
    20.   `TransactionDate` date DEFAULT NULL,  
    21.   PRIMARY KEY (`TransactionId`)  
    22. ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;  

  • Then, we are installing NPM packages for MySQL to make MySQL connection and fetch insert, update records, express to build HTTP server, maintaining server route, body-parser to parsing body into JSON format by entering this command.

    Node.JS

  • We can see that the packages are added to the node_modules folder in our project folder (sample-api). And, I have created this type of folder structure for our project. There are no specific rules regarding project structure, but we are maintaining everything with the modular design to keep it separate and well-maintained.

    Node.JS

  • Now, we are creating MySQLConnect module for establishing the connection with MySQL and executing the MySQL queries.
  • For that, we have created ‘connection/MySQLConnect.JS’ file.
    1. // establish Mysql Connection  
    2. var mysql = require('mysql');  
    3.   
    4. function MySQLConnect() {  
    5.   
    6.   this.pool = null;  
    7.     
    8.   // Init MySql Connection Pool  
    9.   this.init = function() {  
    10.     this.pool = mysql.createPool({  
    11.       connectionLimit: 10,  
    12.       host     : 'localhost',  
    13.       user     : 'root',  
    14.       password : 'admin@123',  
    15.       database: 'sample-db'  
    16.     });  
    17.   };  
    18.   
    19.   // acquire connection and execute query on callbacks  
    20.   this.acquire = function(callback) {  
    21.   
    22.     this.pool.getConnection(function(err, connection) {  
    23.       callback(err, connection);  
    24.     });  
    25.   
    26.   };  
    27.   
    28. }  
    29.   
    30. module.exports = new MySQLConnect();  

  • Then, I have created ‘data_access/transaction.js’ file for acquiring the MySQL connection and return the response with data.
    1. //methods for fetching mysql data  
    2. var connection = require('../connection/MySQLConnect');  
    3.   
    4. function Transaction() {  
    5.   
    6.     // get all users data   
    7.     this.getAllUsers = function (res) {  
    8.         // initialize database connection  
    9.         connection.init();  
    10.         // calling acquire methods and passing callback method that will be execute query  
    11.         // return response to server   
    12.         connection.acquire(function (err, con) {  
    13.             con.query('SELECT DISTINCT * FROM users'function (err, result) {  
    14.                 con.release();  
    15.                 res.send(result);  
    16.             });  
    17.         });  
    18.     };  
    19.   
    20.     this.getTransactionById = function (id, res) {  
    21.         // initialize database connection  
    22.         connection.init();  
    23.         // get id as parameter to passing into query and return filter data  
    24.         connection.acquire(function (err, con) {  
    25.             var query = 'SELECT date_format(t.TransactionDate,\'%d-%b-%Y\') as date, ' +  
    26.                 'CASE WHEN t.TransactionAmount >= 0 THEN t.TransactionAmount ' +  
    27.                 'ELSE 0 END AS Credit, CASE WHEN t.TransactionAmount < 0 THEN ' +  
    28.                 't.TransactionAmount ELSE 0 END AS Debit, t.Balance FROM ' +  
    29.                 'transactions t INNER JOIN users u ON t.UserId=u.UserID WHERE t.UserId = ?;';  
    30.             con.query(query, id, function (err, result) {  
    31.                     con.release();  
    32.                     res.send(result);  
    33.                 });  
    34.         });  
    35.     };  
    36.   
    37. }  
    38.   
    39. module.exports = new Transaction();  

  • Now, I have developed routes for returning the data based on each request. So, I have added ‘route/route.js’ file.
    1. //custom route for fetching data  
    2. var transactions = require('../data_access/transaction');  
    3.   
    4. module.exports = {  
    5.     //set up route configuration that will be handle by express server  
    6.     configure: function (app) {  
    7.   
    8.         // adding route for users, here app is express instance which provide use  
    9.         // get method for handling get request from http server.   
    10.         app.get('/api/users'function (req, res) {  
    11.             transactions.getAllUsers(res);  
    12.         });  
    13.   
    14.         // here we gets id from request and passing to it transaction method.  
    15.         app.get('/api/transactions/:id/'function (req, res) {  
    16.             transactions.getTransactionById(req.params.id, res);  
    17.         });  
    18.   
    19.     }  
    20. };  

  • Now, we are writing the code for setting up the server using Express and here, we initialize the database connection and set route configuration with application.
    1. /**  
    2.  * Creating server using express.js 
    3.  * http://localhost:8000/api/users 
    4.  * http://localhost:8000/api/transactions/1 
    5. */  
    6. var express = require('express');  
    7. var bodyparser = require('body-parser');  
    8.   
    9. var routes = require('./routes/route');  
    10.   
    11. // creating server instance  
    12. var app = express();  
    13.   
    14. // for posting nested object if we have set extended true  
    15. app.use(bodyparser.urlencoded({ extended : true}));  
    16.   
    17. // parsing JSON  
    18. app.use(bodyparser.json());  
    19.   
    20. //set application route with server instance  
    21. routes.configure(app);  
    22.   
    23. // listening application on port 8000  
    24. var server = app.listen(8000, function(){  
    25.     console.log('Server Listening on port ' + server.address().port);  
    26. });  

  • Our API is created; we can verify the API by running the server on localhost. To run our Server, we enter ‘npm start’ command in console. The npm start command is run on the node with starting page which we have set ‘main’ (server.js) key in package.json file. The server is ready for listening on port 8000.

    Node.JS

We are verifying our API call by requesting it from the below URL.

  • http://localhost:8000/api/users

    Node.JS

  • http://localhost:8000/api/transactions/1

    Node.JS

Conclusion

In this article, we have looked into introduction of Node.JS and Express.JS, and we have created simple MySQL data access API using Express.js.

You can find the entire code on GitHub.

Please provide your feedback and let me know your thoughts on Node.JS/Express.JS.


Similar Articles