Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Creating an API in Node.js

DZone's Guide to

Creating an API in Node.js

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

· Integration Zone
Free Resource

Discover how Microservices are a type of software architecture where large applications are made up of small, self-contained units working together through APIs that are not dependent on a specific language. Brought to you in partnership with AppDynamics.

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:

Discover the six challenges and best practices in managing microservice performance, brought to you in partnership with AppDynamics.

Topics:
node js ,mysql ,api

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}