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

What's hot (20)

PDF
Vue.js
Jadson Santos
 
PPT
JAVA OOP
Sunil OS
 
PPT
Maven Introduction
Sandeep Chawla
 
PPTX
Node.js Express
Eyal Vardi
 
PDF
Building Advanced XSS Vectors
Rodolfo Assis (Brute)
 
PPTX
Solid principles
Monica Rodrigues
 
PPTX
Rest api with node js and express
GirlsInTechnology Nepal
 
PPT
Resource Bundle
Sunil OS
 
PDF
Spring Framework
NexThoughts Technologies
 
PPTX
ASP.NET Core MVC + Web API with Overview
Shahed Chowdhuri
 
PDF
API for Beginners
Sébastien Saunier
 
PDF
REST APIs with Spring
Joshua Long
 
PDF
Nodejs presentation
Arvind Devaraj
 
PPTX
[Final] ReactJS presentation
洪 鹏发
 
PPT
Java 8 - CJ
Sunil OS
 
PPTX
ASP.NET Core MVC + Web API with Overview
Shahed Chowdhuri
 
PDF
Spring Framework - Spring Security
Dzmitry Naskou
 
PPTX
Node js Introduction
sanskriti agarwal
 
PPTX
Introduction Node.js
Erik van Appeldoorn
 
PPTX
Node js introduction
Joseph de Castelnau
 
JAVA OOP
Sunil OS
 
Maven Introduction
Sandeep Chawla
 
Node.js Express
Eyal Vardi
 
Building Advanced XSS Vectors
Rodolfo Assis (Brute)
 
Solid principles
Monica Rodrigues
 
Rest api with node js and express
GirlsInTechnology Nepal
 
Resource Bundle
Sunil OS
 
Spring Framework
NexThoughts Technologies
 
ASP.NET Core MVC + Web API with Overview
Shahed Chowdhuri
 
API for Beginners
Sébastien Saunier
 
REST APIs with Spring
Joshua Long
 
Nodejs presentation
Arvind Devaraj
 
[Final] ReactJS presentation
洪 鹏发
 
Java 8 - CJ
Sunil OS
 
ASP.NET Core MVC + Web API with Overview
Shahed Chowdhuri
 
Spring Framework - Spring Security
Dzmitry Naskou
 
Node js Introduction
sanskriti agarwal
 
Introduction Node.js
Erik van Appeldoorn
 
Node js introduction
Joseph de Castelnau
 

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

PDF
RESTful API in Node.pdf
SudhanshiBakre1
 
PDF
Basic API Creation with Node.JS
Azilen Technologies Pvt. Ltd.
 
PDF
MEAN Stack WeNode Barcelona Workshop
Valeri Karpov
 
PPTX
Create Rest API in Nodejs
Irfan Maulana
 
PDF
Learn backend java script
Tsuyoshi Maeda
 
PPTX
Develop a Basic REST API from Scratch Using TDD with Val Karpov
MongoDB
 
PPTX
Develop a Basic REST API from Scratch Using TDD with Val Karpov
MongoDB
 
PDF
node.js practical guide to serverside javascript
Eldar Djafarov
 
PDF
Getting started with node JS
Hamdi Hmidi
 
PPTX
Webinar: Get Started with the MEAN Stack
MongoDB
 
PDF
Developing and Testing a MongoDB and Node.js REST API
All Things Open
 
PDF
TDD a REST API With Node.js and MongoDB
Valeri Karpov
 
PPTX
RESTful API - Best Practices
Tricode (part of Dept)
 
PPTX
Local SQLite Database with Node for beginners
Laurence Svekis ✔
 
PDF
Introduction to Node.js
Somkiat Puisungnoen
 
PPT
nodejs tutorial foor free download from academia
rani marri
 
PDF
GraphQL in an Age of REST
Yos Riady
 
PPTX
MIKE Stack Introduction - MongoDB, io.js, KendoUI, and Express
Charlie Key
 
PDF
Backend Basic in nodejs express and mongodb PPT.pdf
sadityaraj353
 
RESTful API in Node.pdf
SudhanshiBakre1
 
Basic API Creation with Node.JS
Azilen Technologies Pvt. Ltd.
 
MEAN Stack WeNode Barcelona Workshop
Valeri Karpov
 
Create Rest API in Nodejs
Irfan Maulana
 
Learn backend java script
Tsuyoshi Maeda
 
Develop a Basic REST API from Scratch Using TDD with Val Karpov
MongoDB
 
Develop a Basic REST API from Scratch Using TDD with Val Karpov
MongoDB
 
node.js practical guide to serverside javascript
Eldar Djafarov
 
Getting started with node JS
Hamdi Hmidi
 
Webinar: Get Started with the MEAN Stack
MongoDB
 
Developing and Testing a MongoDB and Node.js REST API
All Things Open
 
TDD a REST API With Node.js and MongoDB
Valeri Karpov
 
RESTful API - Best Practices
Tricode (part of Dept)
 
Local SQLite Database with Node for beginners
Laurence Svekis ✔
 
Introduction to Node.js
Somkiat Puisungnoen
 
nodejs tutorial foor free download from academia
rani marri
 
GraphQL in an Age of REST
Yos Riady
 
MIKE Stack Introduction - MongoDB, io.js, KendoUI, and Express
Charlie Key
 
Backend Basic in nodejs express and mongodb PPT.pdf
sadityaraj353
 
Ad

Recently uploaded (20)

DOCX
8th International Conference on Electrical Engineering (ELEN 2025)
elelijjournal653
 
PPTX
Break Statement in Programming with 6 Real Examples
manojpoojary2004
 
PDF
Book.pdf01_Intro.ppt algorithm for preperation stu used
archu26
 
DOC
MRRS Strength and Durability of Concrete
CivilMythili
 
PDF
Unified_Cloud_Comm_Presentation anil singh ppt
anilsingh298751
 
PPTX
Introduction to Neural Networks and Perceptron Learning Algorithm.pptx
Kayalvizhi A
 
PDF
Zilliz Cloud Demo for performance and scale
Zilliz
 
PDF
ARC--BUILDING-UTILITIES-2-PART-2 (1).pdf
IzzyBaniquedBusto
 
PPTX
Arduino Based Gas Leakage Detector Project
CircuitDigest
 
PPTX
Shinkawa Proposal to meet Vibration API670.pptx
AchmadBashori2
 
PPTX
Green Building & Energy Conservation ppt
Sagar Sarangi
 
PDF
Ethics and Trustworthy AI in Healthcare – Governing Sensitive Data, Profiling...
AlqualsaDIResearchGr
 
PPTX
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
PPTX
Types of Bearing_Specifications_PPT.pptx
PranjulAgrahariAkash
 
PPTX
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
PPTX
UNIT DAA PPT cover all topics 2021 regulation
archu26
 
PPTX
原版一样(Acadia毕业证书)加拿大阿卡迪亚大学毕业证办理方法
Taqyea
 
PDF
Set Relation Function Practice session 24.05.2025.pdf
DrStephenStrange4
 
PDF
MAD Unit - 2 Activity and Fragment Management in Android (Diploma IT)
JappanMavani
 
PPTX
Pharmaceuticals and fine chemicals.pptxx
jaypa242004
 
8th International Conference on Electrical Engineering (ELEN 2025)
elelijjournal653
 
Break Statement in Programming with 6 Real Examples
manojpoojary2004
 
Book.pdf01_Intro.ppt algorithm for preperation stu used
archu26
 
MRRS Strength and Durability of Concrete
CivilMythili
 
Unified_Cloud_Comm_Presentation anil singh ppt
anilsingh298751
 
Introduction to Neural Networks and Perceptron Learning Algorithm.pptx
Kayalvizhi A
 
Zilliz Cloud Demo for performance and scale
Zilliz
 
ARC--BUILDING-UTILITIES-2-PART-2 (1).pdf
IzzyBaniquedBusto
 
Arduino Based Gas Leakage Detector Project
CircuitDigest
 
Shinkawa Proposal to meet Vibration API670.pptx
AchmadBashori2
 
Green Building & Energy Conservation ppt
Sagar Sarangi
 
Ethics and Trustworthy AI in Healthcare – Governing Sensitive Data, Profiling...
AlqualsaDIResearchGr
 
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
Types of Bearing_Specifications_PPT.pptx
PranjulAgrahariAkash
 
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
UNIT DAA PPT cover all topics 2021 regulation
archu26
 
原版一样(Acadia毕业证书)加拿大阿卡迪亚大学毕业证办理方法
Taqyea
 
Set Relation Function Practice session 24.05.2025.pdf
DrStephenStrange4
 
MAD Unit - 2 Activity and Fragment Management in Android (Diploma IT)
JappanMavani
 
Pharmaceuticals and fine chemicals.pptxx
jaypa242004
 
Ad

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/