SlideShare a Scribd company logo
Restful Api with Express
js, Node js & MySQl
Presented by : Jeetendra Singh
Prerequisite to express js
• I am assuming you have already installed
nodejs in your operating system either
windows/linux/mac(unix)
• In this presentation i am using Mysql
server as database, So assuming your
server is already having mysql installed
• Nowadays, it’s quite common to create
web and mobile apps that consume data
from apis. This provide facility to, client
side or server side code can be developed
by different teams or same
• we are going to use a very popular web
framework called Express to create REST
apis.
What is Express js?
• Express is a minimalist web framework
that was highly inspired by the Sinatra
framework from the Ruby language. With
this module, you can create anything from
small applications to large, complex ones.
This framework allows you to build APIs
and also to create simple web sites.
Advantages of Express:
• 1. Easily integratable with template
engines
• 2. flexible and Robust routing.
• 3. Minimalist code
• 4. A huge list of third-party modules
available
• 5. Express is having biggest community
available in nodejs
Install NodeJs and MySQL
• Create a database 'node-task-demo'
• Create tables inside it.
CREATE TABLE IF NOT EXISTS `tasks` (
`id` int(11) NOT NULL,
`task` varchar(200) NOT NULL,
`status` tinyint(1) NOT NULL DEFAULT '1',
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `tasks` ADD PRIMARY KEY (`id`);
ALTER TABLE `tasks` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
Insert some sample data into
the tasks table.
INSERT INTO `tasks` (`id`, `task`, `status`, `created_at`)
VALUES
(1, 'Find bugs', 1, '2016-04-10 23:50:40'),
(2, 'Review code', 1, '2016-04-10 23:50:40'),
(3, 'Fix bugs', 1, '2016-04-10 23:50:40'),
(4, 'Refactor Code', 1, '2016-04-10 23:50:40'),
(5, 'Push to prod', 1, '2016-04-10 23:50:50');
Setup Node Restful Project
Go to Terminal or Command Line, create a
project folder.
> mkdir express-node-rest-project
> cd express-node-rest-project
create a file package.json
Initialize your node project with below npm
command, which will create a file called
package.json and it will ask few questions
about project.
> npm init --yes
Here is my final package.json
file.
{
"name": "express-node-rest-project",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.15.2",
"mysql": "^2.13.0"
}
}
Install express js framework and
MySQL driver with NPM.
> npm install express --save
> npm install mysql --save
> npm install body-parser --save
We are going to implement
following API calls
Create Express Server
Create server.js file, Open it with editor, copy following code. Please read the comments
for better understanding.
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
// default route
app.get('/', function (req, res) {
return res.send({ error: true, message: 'hello' })
});
// port must be set to 8080 because incoming http requests are routed from port 80 to port 8080
app.listen(8080, function () {
console.log('Node app is running on port 8080');
});
Express server is ready, you can start your server with node server.js command, to see
output point your browser to http://localhost:8080.
Node MySQL – Database Connection
Update your server.js file with MySQL connection code. Here you have to modify the
MySQL database name, host, username and password.
See the code:
const express = require('express');
const app = express();
const mysql = require('mysql');
...
...
// connection configurations
const mc = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'node_task_demo'
});
mc.connect(); // connect to database
// default route
app.get('/', function (req, res) {
.....
.....
Implementing the API calls with
express js
Now that we have our express serer up and
running with database connection, we need
to manage todos in the database.
Getting the Todos list – We are going to
create a new route so that when a user
hits /todos, it will return a list of all todos in
JSON format. Update your server.js with
below code.
Retrieve all todos
app.get('/todos', function (req, res) {
mc.query('SELECT * FROM tasks', function (error,
results, fields) {
if (error) throw error;
return res.send({ error: false, data: results, message:
'Todos list.' });
});
});
This function simply return all todos information as you can
see in this query, to call this API use this URL
http://localhost:8080/todos.
Retrieve todo with id
app.get('/todo/:id', function (req, res) {
let task_id = req.params.id;
if (!task_id) {
return res.status(400).send({ error: true, message: 'Please provide task_id' });
}
mc.query('SELECT * FROM tasks where id=?', task_id, function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results[0], message: 'Todos list.' });
});
});
This function check record of given id and return if found anything, to call this API use this
URL http://localhost:8080/todo/1.
Search Method
Search for todos with their name
app.get('/todos/search/:keyword', function (req, res) {
let keyword = req.params.keyword;
mc.query("SELECT * FROM tasks WHERE task LIKE ? ", ['%' +
keyword + '%'], function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results, message: 'Todos
search list.' });
});
});
This function search in database for your given query, to call this API
use this URL http://localhost:8080/todos/search/bug
Add a new todo
app.post('/todo', function (req, res) {
let task = req.body.task;
if (!task) {
return res.status(400).send({ error:true, message: 'Please provide task' });
}
mc.query("INSERT INTO tasks SET ? ", { task: task }, function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results, message: 'New task has been created
successfully.' });
});
});
Service Url is: http://localhost:8080/todo
In Form body task filed with name task should be there
Delete Task
app.delete('/todo', function (req, res) {
let task_id = req.body.task_id;
if (!task_id) {
return res.status(400).send({ error: true, message: 'Please provide task_id' });
}
mc.query('DELETE FROM tasks WHERE id = ?', [task_id], function (error, results,
fields) {
if (error) throw error;
return res.send({ error: false, data: results, message: 'Task has been updated
successfully.' });
});
});
Note: it uses a http delete method
Update todo with id
app.put('/todo', function (req, res) {
let task_id = req.body.task_id;
let task = req.body.task;
if (!task_id || !task) {
return res.status(400).send({ error: task, message: 'Please provide task and
task_id' });
}
mc.query("UPDATE tasks SET task = ? WHERE id = ?", [task, task_id], function (error,
results, fields) {
if (error) throw error;
return res.send({ error: false, data: results, message: 'Task has been updated
successfully.' });
});
});
This API accept put request and updates submitted data in your database. To call this
API use this URL http://localhost:8080/todo/{id}
Start Node Server
• Start your nodejs Server using following
command in your terminal
> node server.js
it will make available all your apis at
following port:
http://localhost:8080/
Thanks
Thanks to Bear it me :)

More Related Content

PDF
NodeJS for Beginner
PPTX
Basic Concept of Node.js & NPM
PPTX
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
PDF
Workshop 21: React Router
PPTX
ReactJS presentation.pptx
PPTX
Express JS
PPTX
Rest api with node js and express
PPTX
Express js
NodeJS for Beginner
Basic Concept of Node.js & NPM
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
Workshop 21: React Router
ReactJS presentation.pptx
Express JS
Rest api with node js and express
Express js

What's hot (20)

PPTX
Advance Java Topics (J2EE)
PDF
Nodejs presentation
PDF
Angular Observables & RxJS Introduction
PPTX
PPTX
Build RESTful API Using Express JS
PDF
PDF
TypeScript - An Introduction
PPTX
Introduction to NodeJS
PPTX
Introduction to Node.js
PPTX
Introduction to Node js
PPTX
ASP.NET Web API
PPT
Node.js Express Framework
PPTX
Express JS
PPTX
PPTX
.Net Core
PPTX
What Is Express JS?
PPTX
Nodejs functions & modules
PPTX
Node js Introduction
PDF
TypeScript Introduction
PPTX
reactJS
Advance Java Topics (J2EE)
Nodejs presentation
Angular Observables & RxJS Introduction
Build RESTful API Using Express JS
TypeScript - An Introduction
Introduction to NodeJS
Introduction to Node.js
Introduction to Node js
ASP.NET Web API
Node.js Express Framework
Express JS
.Net Core
What Is Express JS?
Nodejs functions & modules
Node js Introduction
TypeScript Introduction
reactJS
Ad

Similar to RESTful API In Node Js using Express (20)

PDF
Node.js with MySQL.pdf
KEY
Writing robust Node.js applications
PDF
Future Decoded - Node.js per sviluppatori .NET
PPT
nodejs_at_a_glance.ppt
KEY
Building HTTP API's with NodeJS and MongoDB
PPT
nodejs_at_a_glance, understanding java script
PDF
Express node js
PDF
Build Web Apps using Node.js
PDF
Divide and Conquer – Microservices with Node.js
PPTX
harry presentation
PPTX
Local SQLite Database with Node for beginners
PDF
Nodejs first class
PPT
nodejs tutorial foor free download from academia
PDF
Writing RESTful web services using Node.js
PPTX
Full stack development with node and NoSQL - All Things Open - October 2017
PPTX
Full Stack Development with Node.js and NoSQL
PPTX
Building Web Apps with Express
PDF
Node js introduction
PDF
Create a Full-Stack Web App with React & Node.js in 2024
PPTX
Building and Scaling Node.js Applications
Node.js with MySQL.pdf
Writing robust Node.js applications
Future Decoded - Node.js per sviluppatori .NET
nodejs_at_a_glance.ppt
Building HTTP API's with NodeJS and MongoDB
nodejs_at_a_glance, understanding java script
Express node js
Build Web Apps using Node.js
Divide and Conquer – Microservices with Node.js
harry presentation
Local SQLite Database with Node for beginners
Nodejs first class
nodejs tutorial foor free download from academia
Writing RESTful web services using Node.js
Full stack development with node and NoSQL - All Things Open - October 2017
Full Stack Development with Node.js and NoSQL
Building Web Apps with Express
Node js introduction
Create a Full-Stack Web App with React & Node.js in 2024
Building and Scaling Node.js Applications
Ad

Recently uploaded (20)

PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PPTX
Welding lecture in detail for understanding
PPTX
UNIT 4 Total Quality Management .pptx
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PPTX
Lecture Notes Electrical Wiring System Components
PPT
Project quality management in manufacturing
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PPTX
Strings in CPP - Strings in C++ are sequences of characters used to store and...
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PPTX
OOP with Java - Java Introduction (Basics)
PDF
Structs to JSON How Go Powers REST APIs.pdf
PDF
Digital Logic Computer Design lecture notes
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
Welding lecture in detail for understanding
UNIT 4 Total Quality Management .pptx
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
Lecture Notes Electrical Wiring System Components
Project quality management in manufacturing
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
Operating System & Kernel Study Guide-1 - converted.pdf
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
Strings in CPP - Strings in C++ are sequences of characters used to store and...
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
OOP with Java - Java Introduction (Basics)
Structs to JSON How Go Powers REST APIs.pdf
Digital Logic Computer Design lecture notes

RESTful API In Node Js using Express

  • 1. Restful Api with Express js, Node js & MySQl Presented by : Jeetendra Singh
  • 2. Prerequisite to express js • I am assuming you have already installed nodejs in your operating system either windows/linux/mac(unix) • In this presentation i am using Mysql server as database, So assuming your server is already having mysql installed
  • 3. • Nowadays, it’s quite common to create web and mobile apps that consume data from apis. This provide facility to, client side or server side code can be developed by different teams or same • we are going to use a very popular web framework called Express to create REST apis.
  • 4. What is Express js? • Express is a minimalist web framework that was highly inspired by the Sinatra framework from the Ruby language. With this module, you can create anything from small applications to large, complex ones. This framework allows you to build APIs and also to create simple web sites.
  • 5. Advantages of Express: • 1. Easily integratable with template engines • 2. flexible and Robust routing. • 3. Minimalist code • 4. A huge list of third-party modules available • 5. Express is having biggest community available in nodejs
  • 6. Install NodeJs and MySQL • Create a database 'node-task-demo' • Create tables inside it. CREATE TABLE IF NOT EXISTS `tasks` ( `id` int(11) NOT NULL, `task` varchar(200) NOT NULL, `status` tinyint(1) NOT NULL DEFAULT '1', `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `tasks` ADD PRIMARY KEY (`id`); ALTER TABLE `tasks` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
  • 7. Insert some sample data into the tasks table. INSERT INTO `tasks` (`id`, `task`, `status`, `created_at`) VALUES (1, 'Find bugs', 1, '2016-04-10 23:50:40'), (2, 'Review code', 1, '2016-04-10 23:50:40'), (3, 'Fix bugs', 1, '2016-04-10 23:50:40'), (4, 'Refactor Code', 1, '2016-04-10 23:50:40'), (5, 'Push to prod', 1, '2016-04-10 23:50:50');
  • 8. Setup Node Restful Project Go to Terminal or Command Line, create a project folder. > mkdir express-node-rest-project > cd express-node-rest-project
  • 9. create a file package.json Initialize your node project with below npm command, which will create a file called package.json and it will ask few questions about project. > npm init --yes
  • 10. Here is my final package.json file. { "name": "express-node-rest-project", "version": "1.0.0", "description": "", "main": "server.js", "scripts": { "test": "echo "Error: no test specified" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "express": "^4.15.2", "mysql": "^2.13.0" } }
  • 11. Install express js framework and MySQL driver with NPM. > npm install express --save > npm install mysql --save > npm install body-parser --save
  • 12. We are going to implement following API calls
  • 13. Create Express Server Create server.js file, Open it with editor, copy following code. Please read the comments for better understanding. const express = require('express'); const app = express(); const bodyParser = require('body-parser'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); // default route app.get('/', function (req, res) { return res.send({ error: true, message: 'hello' }) }); // port must be set to 8080 because incoming http requests are routed from port 80 to port 8080 app.listen(8080, function () { console.log('Node app is running on port 8080'); });
  • 14. Express server is ready, you can start your server with node server.js command, to see output point your browser to http://localhost:8080. Node MySQL – Database Connection Update your server.js file with MySQL connection code. Here you have to modify the MySQL database name, host, username and password. See the code: const express = require('express'); const app = express(); const mysql = require('mysql'); ... ... // connection configurations const mc = mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'node_task_demo' }); mc.connect(); // connect to database // default route app.get('/', function (req, res) { ..... .....
  • 15. Implementing the API calls with express js Now that we have our express serer up and running with database connection, we need to manage todos in the database. Getting the Todos list – We are going to create a new route so that when a user hits /todos, it will return a list of all todos in JSON format. Update your server.js with below code.
  • 16. Retrieve all todos app.get('/todos', function (req, res) { mc.query('SELECT * FROM tasks', function (error, results, fields) { if (error) throw error; return res.send({ error: false, data: results, message: 'Todos list.' }); }); }); This function simply return all todos information as you can see in this query, to call this API use this URL http://localhost:8080/todos.
  • 17. Retrieve todo with id app.get('/todo/:id', function (req, res) { let task_id = req.params.id; if (!task_id) { return res.status(400).send({ error: true, message: 'Please provide task_id' }); } mc.query('SELECT * FROM tasks where id=?', task_id, function (error, results, fields) { if (error) throw error; return res.send({ error: false, data: results[0], message: 'Todos list.' }); }); }); This function check record of given id and return if found anything, to call this API use this URL http://localhost:8080/todo/1.
  • 18. Search Method Search for todos with their name app.get('/todos/search/:keyword', function (req, res) { let keyword = req.params.keyword; mc.query("SELECT * FROM tasks WHERE task LIKE ? ", ['%' + keyword + '%'], function (error, results, fields) { if (error) throw error; return res.send({ error: false, data: results, message: 'Todos search list.' }); }); }); This function search in database for your given query, to call this API use this URL http://localhost:8080/todos/search/bug
  • 19. Add a new todo app.post('/todo', function (req, res) { let task = req.body.task; if (!task) { return res.status(400).send({ error:true, message: 'Please provide task' }); } mc.query("INSERT INTO tasks SET ? ", { task: task }, function (error, results, fields) { if (error) throw error; return res.send({ error: false, data: results, message: 'New task has been created successfully.' }); }); }); Service Url is: http://localhost:8080/todo In Form body task filed with name task should be there
  • 20. Delete Task app.delete('/todo', function (req, res) { let task_id = req.body.task_id; if (!task_id) { return res.status(400).send({ error: true, message: 'Please provide task_id' }); } mc.query('DELETE FROM tasks WHERE id = ?', [task_id], function (error, results, fields) { if (error) throw error; return res.send({ error: false, data: results, message: 'Task has been updated successfully.' }); }); }); Note: it uses a http delete method
  • 21. Update todo with id app.put('/todo', function (req, res) { let task_id = req.body.task_id; let task = req.body.task; if (!task_id || !task) { return res.status(400).send({ error: task, message: 'Please provide task and task_id' }); } mc.query("UPDATE tasks SET task = ? WHERE id = ?", [task, task_id], function (error, results, fields) { if (error) throw error; return res.send({ error: false, data: results, message: 'Task has been updated successfully.' }); }); }); This API accept put request and updates submitted data in your database. To call this API use this URL http://localhost:8080/todo/{id}
  • 22. Start Node Server • Start your nodejs Server using following command in your terminal > node server.js it will make available all your apis at following port: http://localhost:8080/