DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Node.js REST API Frameworks
  • Using Truffle L2 Boxes to Bridge Blockchain Networks
  • How to Leverage Speech-to-Text With Node.js
  • Creating a Secure REST API in Node.js

Trending

  • How To Validate Archives and Identify Invalid Documents in Java
  • Choosing the Appropriate AWS Load Balancer: ALB vs. NLB
  • Four Ways for Developers To Limit Liability as Software Liability Laws Seem Poised for Change
  • The Systemic Process of Debugging
  1. DZone
  2. Data Engineering
  3. Databases
  4. Creating an API in Node.js

Creating an API in Node.js

Today we are going to see how to create an API in Node.js with MySQL.

Vipul Malhotra user avatar by
Vipul Malhotra
·
Jul. 25, 16 · Tutorial
Like (9)
Save
Tweet
Share
17.82K Views

Join the DZone community and get the full member experience.

Join For Free

Today, we're going to create an API in Node.js. We'll use an express-generator package and MySQL to bring it to life and give it purpose. Follow along as I walk you through the various steps from installation to configuration to completion.

Step 1: Let's start with creating a project in Node.js using an express-generator package. Please refer my another article to get info on that: Creating Node Application Using Express Generator.

Step 2: Now, let's install the MySQL package by using the command: npm install mysql.

Step 3: Connect our application with MySQL.

Let's create a file database.js in our project and write the below code in it:

var mysql = require('mysql');  

module.exports = function handle_db(req, res) {  
    var pool = mysql.createPool({  

        connectionLimit: 100,  
        host: 'localhost',  
        user: 'root',  
        password: '*******',  
        database: 'test'  

    });  

    pool.getConnection(function (err, connection) {  
        if (err) {  
            console.error("This is error msg, when connecting to db: " + err);  
            connection.release();  

            res.json({ "code": 100, "status": "Error in connecting database" });  
            return;  
        }  

        console.log("from db config: connected as id: " + connection.threadId);  
        connection.on('error', function (err) {  
            res.json({ "code": 100, "status": "Error in connection database" });  
            return;  

        });  
        return connection;  

    });  
return pool;  
}  


The code creates a connection with my local database and then provides a connection object as an output from the function getConnection. We will use this object whenever we need a database connection object. 
 
Now, let's include this file into our main file app.js by using:

var pool = require('./database')();  


Step 4: We shall now create a welcome message from our API. To do this, let's create a file routes.js in our project and write:

module.exports = function (app, pool) {  
app.get('/', function (req, res) {  
        res.send("Welcome to C-sharp corner Api");  
    });  
}; 


We have, for now, set the initial application port to 5050 by using the below code in app.js:

app.listen(process.env.PORT || 5050);  
console.log("App listening on port 5050");  


Let's run the application and view the output inPostman. You can also see the same in a browser:

Image title


Step 5: Let's have a view of what the current data in our table users is.

Image title

Step 6: Let's create a folder called API and inside it, let's create a file called user.api.js and create a get function that fetches all the data from the users table and provides it to us. The code for the same is as below:

module.exports = function (app, pool) {  

    app.get('/api/users', function (req, res) {  
        var con = pool.getConnection(function (err, con) {  
            con.query('SELECT * FROM users', function (err, rows) {  

                if (!err) {  

                    console.log(rows);  
                    res.json(rows);  

                }  
                else {  
                    console.error("From users.api.js :" + err);  
                    res.json(err);  
                }  
                con.release();  
            });  
        });  

    }); 


The code states that when a GET request is sent with the URL "/api/users," then we select all the data from the users table and send it to the response object.
 
Please make sure that you update the code in the routes.js as below to include this new file:

module.exports = function (app, pool) {  

require('./api/user.api')(app,pool);  
    app.get('/', function (req, res) {  

        res.send("Welcome to C-sharp corner Api");  
    });  
};  


We can test this GET statement in Postman using the URL: localhost:5050/api/users 

Please see below the screenshot containing the output:

Image title


Step 7: Now, let's create a GetByID using the below code in the user.api.js file.

app.get('/api/users/:id', function (req, res) {  
     con = pool.getConnection(function (err, con) {  
         con.query('SELECT * FROM users where userid=?', [req.params.id], function (err, rows) {  
             if (!err) {  

                 console.log(rows);  
                 res.json(rows);  

             }  
             else {  
                 console.error("From users.api.js :" + err);  
                 res.json(err);  
             }  
             con.release();  
         });  
     });  

 });  


The code simply gets the user on the basis of userid. Here's the output:

Image title


Step 8: Now, let's create an update function by including the below code in the user.api.js file:

app.put('/api/users/:id', function (req, res) {  
       con = pool.getConnection(function (err, con) {  
           con.query('UPDATE users SET UserName=? , Description=? where UserID=?', [req.body.username, req.body.desc, req.params.id], function (err, rows) {  
               if (!err) {  

                   console.log(rows);  
                   res.json(rows);  

               }  
               else {  
                   console.error("From users.api.js :" + err);  
                   res.json(err);  
               }  
               con.release();  

           });  
       });  
   });  


Please note that there are i/p parameters, which we can easily provide using Postman as shown below:

Image title


Step 9: In the same way, an insert and delete function would be coded as below with respective screenshots.
 
Insert:

app.post('/api/users/', function (req, res) {  
    con = pool.getConnection(function (err, con) {  
        con.query('INSERT INTO users (UserID,UserName,Description) VALUES(?,?,?)', [req.body.userid,req.body.username, req.body.desc], function (err, rows) {  
            if (!err) {  

                console.log(rows);  
                res.json(rows);  

            }  
            else {  
                console.error("From users.api.js :" + err);  
                res.json(err);  
            }  
            con.release();  

        });  
    });  
});  


Image title


Delete:

 app.delete('/api/users/:id', function (req, res) {  
    con = pool.getConnection(function (err, con) {  
        con.query('DELETE FROM users WHERE UserID=?', [req.params.id], function (err, rows) {  
            if (!err) {  

                console.log(rows);  
                res.json(rows);  

            }  
            else {  
                console.error("From users.api.js :" + err);  
                res.json(err);  
            }  
            con.release();  

        });  
    });  
});  


Image title


The complete code of user.api.js  is as below:

module.exports = function (app, pool) {  

    app.get('/api/users', function (req, res) {  
        var con = pool.getConnection(function (err, con) {  
            con.query('SELECT * FROM users', function (err, rows) {  

                if (!err) {  

                    console.log(rows);  
                    res.json(rows);  

                }  
                else {  
                    console.error("From users.api.js :" + err);  
                    res.json(err);  
                }  
                con.release();  
            });  
        });  

    });  

    app.get('/api/users/:id', function (req, res) {  
        con = pool.getConnection(function (err, con) {  
            con.query('SELECT * FROM users where userid=?', [req.params.id], function (err, rows) {  
                if (!err) {  

                    console.log(rows);  
                    res.json(rows);  

                }  
                else {  
                    console.error("From users.api.js :" + err);  
                    res.json(err);  
                }  
                con.release();  
            });  
        });  

    });  

    app.put('/api/users/:id', function (req, res) {  
        con = pool.getConnection(function (err, con) {  
            con.query('UPDATE users SET UserName=? , Description=? where UserID=?', [req.body.username, req.body.desc, req.params.id], function (err, rows) {  
                if (!err) {  

                    console.log(rows);  
                    res.json(rows);  

                }  
                else {  
                    console.error("From users.api.js :" + err);  
                    res.json(err);  
                }  
                con.release();  

            });  
        });  
    });  

        app.post('/api/users/', function (req, res) {  
        con = pool.getConnection(function (err, con) {  
            con.query('INSERT INTO users (UserID,UserName,Description) VALUES(?,?,?)', [req.body.userid,req.body.username, req.body.desc], function (err, rows) {  
                if (!err) {  

                    console.log(rows);  
                    res.json(rows);  

                }  
                else {  
                    console.error("From users.api.js :" + err);  
                    res.json(err);  
                }  
                con.release();  

            });  
        });  
    });  

      app.delete('/api/users/:id', function (req, res) {  
        con = pool.getConnection(function (err, con) {  
            con.query('DELETE FROM users WHERE UserID=?', [req.params.id], function (err, rows) {  
                if (!err) {  

                    console.log(rows);  
                    res.json(rows);  

                }  
                else {  
                    console.error("From users.api.js :" + err);  
                    res.json(err);  
                }  
                con.release();  

            });  
        });  
    });  

};  


I hope this article helped in understanding how to create an API in Node.js.

Related Refcard:

Node.js

API Node.js

Opinions expressed by DZone contributors are their own.

Related

  • Node.js REST API Frameworks
  • Using Truffle L2 Boxes to Bridge Blockchain Networks
  • How to Leverage Speech-to-Text With Node.js
  • Creating a Secure REST API in Node.js

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: