Building Simple REST API with Express.js and MySQL

Express.js is used to create a REST API which performs operations on a database, Requirements to keep following this tutorial, I’ll assume that you already know the basic level working with express.js and also SQL Language.

Go ahead and create your database and store in your data in MySql

Requirements

Create your file `server.js`

Install the following packages in order to use express.js

npm init
npm install express cors body-parser path mysql --save

This will install all the packages needed in order to run the express.js server.

Basic Structure

// Basic Express.js REST API with MySql DB
var mods = require("./models"); // Models const express = require("express"),
app = express(),
mysql = require("mysql"), // import mysql module
cors = require("cors"),
bodyParser = require("body-parser");
path = require("path");// DB Configuration
db = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "myDBName",
});/* * * * * * * * * * * * * * * * * * * * * * * * *
* ROUTES *
* * * * * * * * * * * * * * * * * * * * * * * * */// First route
app.get("/api", function (req, res) { res.status(200).send("Welcome to your first api!");});// Get Data from DB
app.get("/api/data", function (req, res) { let sql = `SELECT * FROM users`; db.query(sql, function (err, data, fields) { if (err) throw err;
res.json({
status: 200,
data,
message: "User lists retrieved successfully",
});
});
});// Insert Data into DB
app.post("/api/insert", function (req, res) { let sql = `INSERT INTO users(name, gender) VALUES (?)`; let values = [req.body.name, req.body.gender]; db.query(sql, [values], function (err, data, fields) {
if (err) throw err;
res.json({
status: 200,
message: "New user added successfully",
});
});
});// listening on this port
const PORT = process.env.PORT || 5000;app.listen(PORT, () => {console.log(`Server is running on PORT ${PORT}`);});

Query API

In order to query the different routes of the API, you can open this link in the browser or use a specialized tool to query the API

open

1.) http://localhost:5000/api
2.) http://localhost:5000/api/data
3.) http://localhost:5000/api/insert

output of link 1.)

Welcome to your first api!

Make sure you update the configurations of the database with yours and you check that the routes are correctly written down.

Thanks for reading ☺️
If you enjoyed the article, you can buy me a coffee 
here

Leave a Reply

Your email address will not be published.