📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Setup MySQL database
create database demo;
CREATE TABLE `todos` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`description` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1 ;
Tools and technologies used
- Node.js (npm)
- Express
- Body-parser
- MySQL
- Visual studio code IDE
Development steps
- Creating an application
- Install dependencies
- Setting up the webserver
- Defining Routes using Express
- Developing the Restful APIs
- Testing our APIs
- Conclusion
- Source code on GitHub repository
1. Creating an application
- Open a terminal and create a new folder for the application.
$ mkdir node-express-mysql-crud-restapi
- Initialize the application with a package.json file
$ cd node-express-mysql-crud-restapi
$ npm init
{
"name": "node-express-mysql-crud-restapi",
"version": "1.0.0",
"description": "Todo App",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"Express",
"RestAPI",
"MySQL",
"Todos"
],
"author": "javaguides.net",
"license": "MIT"
}
2. Install dependencies
$ npm install express body-parser mysql --save
{
"name": "node-express-mysql-crud-restapi",
"version": "1.0.0",
"description": "Todo App",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"Express",
"RestAPI",
"MySQL",
"Todos"
],
"author": "javaguides.net",
"license": "MIT",
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1",
"mysql": "^2.18.1"
}
}
3. Setting up the webserver
const express = require('express');
const bodyParser = require('body-parser');
// create express app
const app = express();
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }))
// parse application/json
app.use(bodyParser.json())
// define a simple route
app.get('/', (req, res) => {
res.json({"message": "Welcome to Todo app"});
});
// listen for requests
app.listen(4000, () => {
console.log("Server is listening on port 4000");
});
$ npm install
$ node main.js
Server is listening on port 4000
4. Defining Routes using Express
$ mkdir app/routes
$ cd app/routes
module.exports = (app) => {
const todos = require('../controllers/todo.controller.js');
// Create a new todo
app.post('/todos', todos.create);
// Retrieve all todos
app.get('/todos', todos.findAll);
// Retrieve a single todo by id
app.get('/todos/:id', todos.findOne);
// Update a Todo with id
app.put('/todos/:id', todos.update);
// Delete a Todo by id
app.delete('/todos/:id', todos.delete);
}
// Require Notes routes
require('./app/routes/note.routes.js')(app);
const express = require('express');
const bodyParser = require('body-parser');
// create express app
const app = express();
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }))
// parse application/json
app.use(bodyParser.json())
// define a simple route
app.get('/', (req, res) => {
res.json({"message": "Welcome to Todo app"});
});
require('./app/routes/todo.routes.js')(app);
// listen for requests
app.listen(4000, () => {
console.log("Server is listening on port 4000");
});
5. Developing the Restful APIs
Connect to MySQL Database
const mysql = require('mysql');
// connection configurations
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'demo'
});
// connect to database
connection.connect(function (err) {
if (err) throw err
console.log('You are now connected with mysql database...')
})
Create a Todo
// Create and Save a new Todo
exports.create = (req, res) => {
// Validate request
if (!req.body.description) {
return res.status(400).send({
message: "Todo description can not be empty"
});
}
var params = req.body;
console.log(params);
connection.query("INSERT INTO todos SET ? ", params,
function (error, results, fields) {
if (error) throw error;
return res.send({
data: results,
message: 'New todo has been created successfully.'
});
});
};
Retrieve all Todos
// Retrieve and return all todos from the database.
exports.findAll = (req, res) => {
connection.query('select * from todos',
function (error, results, fields) {
if (error) throw error;
res.end(JSON.stringify(results));
});
};
Retrieve a single Todo by Id
// Find a single todo with a id
exports.findOne = (req, res) => {
connection.query('select * from todos where Id=?',
[req.params.id],
function (error, results, fields) {
if (error) throw error;
res.end(JSON.stringify(results));
});
};
Update a Todo
/ Update a todo identified by the id in the request
exports.update = (req, res) => {
// Validate Request
if (!req.body.description) {
return res.status(400).send({
message: "Todo description can not be empty"
});
}
console.log(req.params.id);
console.log(req.body.description);
connection.query('UPDATE `todos` SET `name`=?,`description`=? where `id`=?',
[req.body.name, req.body.description, req.params.id],
function (error, results, fields) {
if (error) throw error;
res.end(JSON.stringify(results));
});
};
Delete a Todo
// Delete a todo with the specified id in the request
exports.delete = (req, res) => {
console.log(req.body);
connection.query('DELETE FROM `todos` WHERE `Id`=?',
[req.body.id], function (error, results, fields) {
if (error) throw error;
res.end('Record has been deleted!');
});
};
Complete code - todo.controller.js
const mysql = require('mysql');
// connection configurations
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'demo'
});
// connect to database
connection.connect(function (err) {
if (err) throw err
console.log('You are now connected with mysql database...')
})
// Create and Save a new Todo
exports.create = (req, res) => {
// Validate request
if (!req.body.description) {
return res.status(400).send({
message: "Todo description can not be empty"
});
}
var params = req.body;
console.log(params);
connection.query("INSERT INTO todos SET ? ", params,
function (error, results, fields) {
if (error) throw error;
return res.send({
data: results,
message: 'New todo has been created successfully.'
});
});
};
// Retrieve and return all todos from the database.
exports.findAll = (req, res) => {
connection.query('select * from todos',
function (error, results, fields) {
if (error) throw error;
res.end(JSON.stringify(results));
});
};
// Find a single todo with a id
exports.findOne = (req, res) => {
connection.query('select * from todos where Id=?',
[req.params.id],
function (error, results, fields) {
if (error) throw error;
res.end(JSON.stringify(results));
});
};
// Update a todo identified by the id in the request
exports.update = (req, res) => {
// Validate Request
if (!req.body.description) {
return res.status(400).send({
message: "Todo description can not be empty"
});
}
console.log(req.params.id);
console.log(req.body.description);
connection.query('UPDATE `todos` SET `name`=?,`description`=? where `id`=?',
[req.body.name, req.body.description, req.params.id],
function (error, results, fields) {
if (error) throw error;
res.end(JSON.stringify(results));
});
};
// Delete a todo with the specified id in the request
exports.delete = (req, res) => {
console.log(req.body);
connection.query('DELETE FROM `todos` WHERE `Id`=?',
[req.body.id], function (error, results, fields) {
if (error) throw error;
res.end('Record has been deleted!');
});
};
Enroll in the leading Autocad institute in Delhi and Noida.High Technologies Solutions believes in quality training and provide innovative friendly environment.We also provide live projects, Assignments, free demo class and placement assistance. Call at 9311002620.
ReplyDeleteautocad training institute in Delhi
autocad training institute in Noida
Thanks for this blog are more informative contents step by step. I here attached my site would you see this blog.
ReplyDelete7 tips to start a career in digital marketing
“Digital marketing is the marketing of product or service using digital technologies, mainly on the Internet, but also including mobile phones, display advertising, and any other digital medium”. This is the definition that you would get when you search for the term “Digital marketing” in google. Let’s give out a simpler explanation by saying, “the form of marketing, using the internet and technologies like phones, computer etc”.
we have offered to the advanced syllabus course digital marketing for available join now.
more details click the link now.
https://www.webdschool.com/digital-marketing-course-in-chennai.html
Amazing articles useful information.
ReplyDeleteWeb designing trends in 2020
When we look into the trends, everything which is ruling today’s world was once a start up and slowly begun getting into. But Now they have literally transformed our lives on a tremendous note. To name a few, Facebook, WhatsApp, Twitter can be a promising proof for such a transformation and have a true impact on the digital world.
we have offered to the advanced syllabus course web design and development for available join now.
more details click the link now.
https://www.webdschool.com/web-development-course-in-chennai.html
This has been very helpful. I wish you had an additional one on how to add support for authentication!
ReplyDelete