Create Node.js REST API with Example: Express, MYSQL

Create Node.js REST API with Examples: Express, MYSQL

Why node.js for API development?

What’s Express?

How to Build NodeJS API?

Prerequisites

Let’s Start With NodeJS API?

Overview of Node JS API Implementation?

NodeJS API Routes

Create NodeJS REST API

$ mkdir NODEJS
$ cd NODEJS

Initialize the Node.js application with a package.json file:

npm initname: (NODEJS) 
version: (1.0.0)
description: Node.js Restful CRUD API with Node.js, Express and MySQL
entry point: (index.js) server.js
test command:
git repository:
keywords: nodejs, express, mysql, restapi
author: Sapan Mohanty
license: (ISC)
npm install express mysql body-parser --save
{
"name": "NODEJS",
"version": "1.0.0",
"description": "Node.js Restful CRUD API with Node.js, Express and MySQL",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"nodejs",
"express",
"mysql",
"restapi"
],
"author": "Sapan Mohanty",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1",
"mysql": "^2.18.1"
}
}

Our Folder Structure Will be

Setup Express Web Server

//server.js
const express = require("express");
const bodyParser = require("body-parser");
const app = express();// parse requests of content-type - application/json
app.use(bodyParser.json());
// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// simple route
app.get("/", (req, res) => {
res.json({ message: "Welcome to Nodejs Simple REST API application." });
});
require("./app/routes/property.routes.js")(app);// set port, listen for requests
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});

What we doing here?

node server.js.
Node Js server is UP

Create MySQL Table

USE `nodejs`;/*Table structure for table `properties` */DROP TABLE IF EXISTS `properties`;CREATE TABLE `properties` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`property_name` varchar(150) DEFAULT NULL,
`address` varchar(220) DEFAULT NULL,
`city` varchar(50) DEFAULT NULL,
`country` varchar(50) DEFAULT NULL,
`type` varchar(50) DEFAULT NULL,
`minimum_price` decimal(10,2) DEFAULT NULL,
`maximum_price` decimal(10,2) DEFAULT NULL,
`ready_to_sell` tinyint(1) DEFAULT 1,
`last_update` datetime DEFAULT current_timestamp() ON UPDATE current_timestamp(),
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8mb4;

Configure & Connect to MySQL Database

module.exports = {
HOST: "localhost",
USER: "root",
PASSWORD: "",
DB: "nodejs"
};
// models/db.jsconst mysql = require("mysql");
const dbConfig = require("../config/db.config.js");
// Create a connection to the database
const connection = mysql.createConnection({
host: dbConfig.HOST,
user: dbConfig.USER,
password: dbConfig.PASSWORD,
database: dbConfig.DB
});
// open the MySQL connection
connection.connect(error => {
if (error) throw error;
console.log("Successfully connected to the database.");
});
module.exports = connection;

Create the Model

(C)reate a New Property
(U)pdate a Property By id
(R)ead a Property By id
(R)ead All Properties
(D)elete a Property By Id
(D)elete all Properties
// models/property.model.jsconst sql = require("./db.js");// constructor
const Property = function(property) {
this.property_name = property.property_name,
this.address = property.address,
this.city = property.city,
this.country = property.country,
this.type = property.type,
this.minimum_price = property.minimum_price,
this.maximum_price = property.maximum_price,
this.ready_to_sell = property.ready_to_sell
};
Property.create = (newProperty, result) => {
sql.query("INSERT INTO properties SET ?", newProperty, (err, res) => {
if (err) {
console.log("error: ", err);
result(err, null);
return;
}
console.log("created property: ", { id: res.insertId, ...newProperty });
result(null, { id: res.insertId, ...newProperty });
});
};
Property.findById = (propertyId, result) => {
sql.query(`SELECT * FROM properties WHERE id = ${propertyId}`, (err, res) => {
if (err) {
console.log("error: ", err);
result(err, null);
return;
}
if (res.length) {
console.log("found property: ", res[0]);
result(null, res[0]);
return;
}
// not found Property with the id
result({ kind: "not_found" }, null);
});
};
Property.getAll = result => {
sql.query("SELECT * FROM properties", (err, res) => {
if (err) {
console.log("error: ", err);
result(null, err);
return;
}
console.log("properties: ", res);
result(null, res);
});
};
Property.updateById = (id, property, result) => {
sql.query(
"UPDATE properties SET property_name = ?, address = ?, city = ?, country = ?, minimum_price = ?, maximum_price = ?, ready_to_sell = ? WHERE id = ?",
[property.property_name, property.address, property.city,property.country, property.minimum_price,property.maximum_price, property.ready_to_sell, id],
(err, res) => {
if (err) {
console.log("error: ", err);
result(null, err);
return;
}
if (res.affectedRows == 0) {
// not found Property with the id
result({ kind: "not_found" }, null);
return;
}
console.log("updated property: ", { id: id, ...property });
result(null, { id: id, ...property });
}
);
};
Property.remove = (id, result) => {
sql.query("DELETE FROM properties WHERE id = ?", id, (err, res) => {
if (err) {
console.log("error: ", err);
result(null, err);
return;
}
if (res.affectedRows == 0) {
// not found Property with the id
result({ kind: "not_found" }, null);
return;
}
console.log("deleted property with id: ", id);
result(null, res);
});
};
Property.removeAll = result => {
sql.query("DELETE FROM properties", (err, res) => {
if (err) {
console.log("error: ", err);
result(null, err);
return;
}
console.log(`deleted ${res.affectedRows} properties`);
result(null, res);
});
};
module.exports = Property;

Let’s Jump into Routes

/properties: GET, POST, DELETE
/properties/: propertyId: GET, PUT, DELETE
// routes/property.routes.phpmodule.exports = app => {
const properties = require("../controllers/property.controller.js");
// Create a new Customer
app.post("/properties", properties.create);
// Retrieve all Customers
app.get("/properties", properties.findAll);
// Retrieve a single Customer with propertyId
app.get("/properties/:propertyId", properties.findOne);
// Update a Customer with propertyId
app.put("/properties/:propertyId", properties.update);
// Delete a Customer with propertyId
app.delete("/properties/:propertyId", properties.delete);
// Create a new Customer
app.delete("/properties", properties.deleteAll);
};
...require("./app/routes/property.routes.js")(app);app.listen(...);

Create the Controller

const Property = require("../models/property.model.js");// Create and Save a new Property
exports.create = (req, res) => {
// Validate request
if (!req.body) {
res.status(400).send({
message: "Content can not be empty!"
});
}
// Create a Property
const property = new Property({
property_name: req.body.property_name,
address: req.body.address,
city: req.body.city,
country: req.body.country,
type: req.body.type,
minimum_price: req.body.minimum_price,
maximum_price: req.body.maximum_price,
ready_to_sell:req.body.ready_to_sell
});
Property.create(property, (err, data) => {
if (err)
res.status(500).send({
message:
err.message || "Some error occurred while creating the Property."
});
else res.send(data);
});
};
exports.findAll = (req, res) => {
Property.getAll((err, data) => {
if (err)
res.status(500).send({
message:
err.message || "Some error occurred while retrieving properties."
});
else res.send(data);
});
};
exports.findOne = (req, res) => {
Property.findById(req.params.propertyId, (err, data) => {
if (err) {
if (err.kind === "not_found") {
res.status(404).send({
message: `Not found Property with id ${req.params.propertyId}.`
});
} else {
res.status(500).send({
message: "Error retrieving Property with id " + req.params.propertyId
});
}
} else res.send(data);
});
};
exports.update = (req, res) => {
// Validate Request
if (!req.body) {
res.status(400).send({
message: "Content can not be empty!"
});
}
console.log(req.body); Property.updateById(
req.params.propertyId,
new Property(req.body),
(err, data) => {
if (err) {
if (err.kind === "not_found") {
res.status(404).send({
message: `Not found Property with id ${req.params.propertyId}.`
});
} else {
res.status(500).send({
message: "Error updating Property with id " + req.params.propertyId
});
}
} else res.send(data);
}
);
};
exports.delete = (req, res) => {
Property.remove(req.params.propertyId, (err, data) => {
if (err) {
if (err.kind === "not_found") {
res.status(404).send({
message: `Not found Property with id ${req.params.propertyId}.`
});
} else {
res.status(500).send({
message: "Could not delete Property with id " + req.params.propertyId
});
}
} else res.send({ message: `Property was deleted successfully!` });
});
};
exports.deleteAll = (req, res) => {
Property.removeAll((err, data) => {
if (err)
res.status(500).send({
message:
err.message || "Some error occurred while removing all properties."
});
else res.send({ message: `All Properties were deleted successfully!` });
});
};

Test the APIs

node server.jsThe console shows:Server is running on port 3000.
Successfully connected to the database.
Fetch Records From Table
npm initnode server.js

What did we learn so far?

Technology Enthusiast/ CTO/ Product Owner/ Connectivity Specialist/ API / Backend Development/ AI & ML, Prof: https://www.linkedin.com/in/travel-technology-cto/