
Required installation
NodeJs
Visual Studio Code
Check with the below command that NodeJS installation succeeded or not in VS CODE terminal
node --version
npm --version
Command to create a new project
npm --init
Running application
node index.js
Installing express framework
npm install --save express
Installing Nodemon
npm install --save-dev nodemon
Installation needed
MySql Workbench
Installing MySQL npm package
npm install --save mysql
db.config.js [Full]
const { createPool } = require("mysql");
/** Connection pool creation - START */
const db = createPool({
port: 3306,
host: "<YOUR DB SERVER>",
user: "<YOUR DB USERNAME>",
password: "<YOUR DB PASSWORD>",
database: "<YOUR DB NAME>",
connectionLimit: 10,
});
/** Connection pool creation - END */
module.exports = db;
Installations needed
Postman
Installing body-parser
npm install --save body-parser
index.js [Full]
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const usersRoutes = require("./routes/users.route");
app.use(bodyParser.json());
app.use("/users", usersRoutes);
app.listen(3000, () => {
console.log("I am ready to lisen you");
});
users.route.js [Full]
const usersController = require("../controllers/users.controller");
var express = require("express");
var router = express.Router();
router.post("/register", usersController.register);
//router.post("/login", usersController.login);
module.exports = router;
users.controller.js [Full]
const usersService = require("../services/users.service");
exports.register = (req, res, next) => {
// Validation area
const data = {
firstName: req.body.firstName,
lastName: req.body.lastName,
emailId: req.body.emailId,
password: req.body.password,
};
usersService.register(data, (error, results) => {
if (error) {
console.log(error);
return res.status(400).send({ success: 0, data: "Bad request" });
}
return res.status(200).send({
success: 1,
data: results,
});
});
};
users.service.js [Full]
const db = require("../config/db.config");
exports.register = (data, callback) => {
db.query(
`INSERT INTO users (firstName, lastName, emailId, password) VALUES (?, ?, ?, ?)`,
[data.firstName, data.lastName, data.emailId, data.password],
(error, results, fields) => {
if (error) {
return callback(error);
}
return callback(null, `Registration successful`);
}
);
};
Body parameters to pass in POSTMAN
{
"firstName": "Navin",
"lastName": "Balla",
"emailId": "navin@sample.com",
"password": "abcd"
}
Installing necessary packages for swagger
npm install --save swagger-jsdoc swagger-ui-express
index.js [Full]
const express = require("express");
const swaggerJsdoc = require("swagger-jsdoc");
const swaggerUi = require("swagger-ui-express");
const app = express();
const bodyParser = require("body-parser");
const usersRoutes = require("./routes/users.route");
app.use(bodyParser.json());
/** Swagger Initialization - START */
const swaggerOption = {
swaggerDefinition: (swaggerJsdoc.Options = {
info: {
title: "my-posts",
description: "API documentation",
contact: {
name: "Developer",
},
servers: ["http://localhost:3000/"],
},
}),
apis: ["index.js", "./routes/*.js"],
};
const swaggerDocs = swaggerJsdoc(swaggerOption);
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerDocs));
/** Swagger Initialization - END */
app.use("/users", usersRoutes);
app.listen(3000, () => {
console.log("I am ready to lisen you");
});
users.route.js [Full]
const usersController = require("../controllers/users.controller");
var express = require("express");
var router = express.Router();
router.post("/register", usersController.register);
/**
* @swagger
* /users/register:
* post:
* description: Used to register user
* tags:
* - users
* parameters:
* - in: body
* name: User
* description: User data
* schema:
* type: object
* required:
* - firstName
* - lastName
* - emailId
* - password
* properties:
* firstName:
* type: string
* minLength: 1
* maxLength: 45
* example: Navin
* lastName:
* type: string
* minLength: 1
* maxLength: 45
* example: Balla
* emailId:
* type: string
* minLength: 1
* maxLength: 100
* example: navin@sample.com
* password:
* type: string
* minLength: 1
* maxLength: 45
* example: abcd
* responses:
* '200':
* description: Resource added successfully
* '500':
* description: Internal server error
* '400':
* description: Bad request
*/
//router.post("/login", usersController.login);
module.exports = router;
index.js [Full]
const express = require("express");
const swaggerJsdoc = require("swagger-jsdoc");
const swaggerUi = require("swagger-ui-express");
const app = express();
const bodyParser = require("body-parser");
const usersRoutes = require("./routes/users.route");
const postsRoutes = require("./routes/posts.route");
app.use(bodyParser.json());
/** Swagger Initialization - START */
const swaggerOption = {
swaggerDefinition: (swaggerJsdoc.Options = {
info: {
title: "my-posts",
description: "API documentation",
contact: {
name: "Developer",
},
servers: ["http://localhost:3000/"],
},
}),
apis: ["index.js", "./routes/*.js"],
};
const swaggerDocs = swaggerJsdoc(swaggerOption);
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerDocs));
/** Swagger Initialization - END */
app.use("/users", usersRoutes);
app.use("/posts", postsRoutes);
app.listen(3000, () => {
console.log("I am ready to lisen you");
});
posts.route.js [Full]
const postsController = require("../controllers/posts.controller");
var express = require("express");
var router = express.Router();
router.post("/add-post", postsController.addPost);
/**
* @swagger
* /posts/add-post:
* post:
* description: Used to add post
* tags:
* - posts
* parameters:
* - in: body
* name: Post
* description: Post data
* schema:
* type: object
* required:
* - description
* - imagePath
* - addedByUserId
* properties:
* description:
* type: string
* minLength: 1
* maxLength: 1000
* example: This is sample post
* imagePath:
* type: string
* minLength: 1
* maxLength: 1000
* example: abc.png
* addedByUserId:
* type: integer
* example: 1
* responses:
* '200':
* description: Resource added successfully
* '500':
* description: Internal server error
* '400':
* description: Bad request
*/
module.exports = router;
posts.controller.js [Full]
const postsService = require("../services/posts.service");
exports.addPost = (req, res, next) => {
const data = {
description: req.body.description,
imagePath: req.body.imagePath,
addedByUserId: req.body.addedByUserId,
};
postsService.addPost(data, (error, results) => {
if (error) {
console.log(error);
return res.status(400).send({ success: 0, data: "Bad request" });
}
return res.status(200).send({
success: 1,
data: results,
});
});
};
posts.service.js [Full]
const db = require("../config/db.config");
exports.addPost = (data, callback) => {
db.query(
`INSERT INTO posts (description, imagePath, datetimeCreated, addedByUserId)
VALUES (?, ?, ?, ?)`,
[data.description, data.imagePath, new Date(), data.addedByUserId],
(error, results, fields) => {
if (error) {
return callback(error);
}
return callback(null, "Post added successfully");
}
);
};
posts.route.js [Code snippet]
router.post("/add-post-comment", postsController.addPostComment);
/**
* @swagger
* /posts/add-post-comment:
* post:
* description: Used to add post comment
* tags:
* - posts
* parameters:
* - in: body
* name: Comment
* description: Post Comment
* schema:
* type: object
* required:
* - postId
* - comment
* - addedByUserId
* properties:
* postId:
* type: integer
* example: 1
* comment:
* type: string
* minLength: 1
* maxLength: 1000
* example: This is sample comment
* addedByUserId:
* type: integer
* example: 1
* responses:
* '200':
* description: Resource added successfully
* '500':
* description: Internal server error
* '400':
* description: Bad request
*/
posts.controller.js [Code snippet]
exports.addPostComment = (req, res, next) => {
const data = {
postId: req.body.postId,
comment: req.body.comment,
addedByUserId: req.body.addedByUserId,
};
postsService.addPostComment(data, (error, results) => {
if (error) {
console.log(error);
return res.status(400).send({ success: 0, data: "Bad request" });
}
return res.status(200).send({
success: 1,
data: results,
});
});
};
posts.service.js [Code snippet]
exports.addPostComment = (data, callback) => {
db.query(
`INSERT INTO comments (postId, comment, datetimeCreated, addedByUserId) VALUES (?, ?, ?, ?)`,
[data.postId, data.comment, new Date(), data.addedByUserId],
(error, results, fields) => {
if (error) {
return callback(error);
}
return callback(null, `Comment Added Successfully`);
}
);
};
The course is created to give the detailed planning needed for creating a RESTApi application in NodeJS using the Express framework. Which will help you to create applications from scratch & maintainable for increasing scale of it as well. The course project is designed step-by-step by giving a good understanding of security, performance, load, scale & maintenance. The course covers the below things.
RESTApi need & working style
RESTApi architecture, different approaches
File structure planning
Detailed working for route, controller & services
Nodemon & Body parser
GET, POST, PUT & DELETE methods understanding
HTTP response codes understanding
Database connection
Swagger documentation
Course project
It's amazing to create a single RESTApi application that serves data to websites, apps, and more. At the same time, it's important to know the structure for creation. We are here to help you with every inch of NodeJs RESTApi development.
This course includes a sample NodeJS application as a course project which includes Swagger for good documentation, MySQL for database, the good file structure for scalable & maintainable application. Here I have tried to solve the issues that come with the first project creation to everyone like planing file structure, pattern selection, different approaches for the same thing & deciding the better from that, and more.
What is Swagger?
It simplifies API development for users, teams, and enterprises with the Swagger open source. RESTApi developers can easily communicate details about REST API to testers & frontend developers which includes route name, method, parameters, body, input validation, and much more.