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)

PPTX
Node.js Express
Eyal Vardi
 
PPTX
SharePoint Framework 101 (SPFx)
Matthew J. Bailey , MCT
 
PDF
spring-api-rest.pdf
Jaouad Assabbour
 
PPTX
Spring Boot
Jiayun Zhou
 
PPTX
Rest api with node js and express
GirlsInTechnology Nepal
 
PDF
Express node js
Yashprit Singh
 
PPTX
Javascript
Nagarajan
 
PDF
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
Edureka!
 
PDF
How to go about testing in React?
Lisa Gagarina
 
PPTX
Express JS
Designveloper
 
PDF
Spring Boot
HongSeong Jeon
 
PPTX
Mockito
sudha rajamanickam
 
PDF
NodeJS for Beginner
Apaichon Punopas
 
PDF
12 Steps to API Load Testing with Apache JMeter
WSO2
 
PDF
How to Build Real-time Chat App with Express, ReactJS, and Socket.IO?
Katy Slemon
 
PPTX
Introduction to Node js
Akshay Mathur
 
PPTX
Spring boot
sdeeg
 
PPTX
Introduction to spring boot
Santosh Kumar Kar
 
PPTX
Testing of React JS app
Aleks Zinevych
 
PPTX
Lab #2: Introduction to Javascript
Walid Ashraf
 
Node.js Express
Eyal Vardi
 
SharePoint Framework 101 (SPFx)
Matthew J. Bailey , MCT
 
spring-api-rest.pdf
Jaouad Assabbour
 
Spring Boot
Jiayun Zhou
 
Rest api with node js and express
GirlsInTechnology Nepal
 
Express node js
Yashprit Singh
 
Javascript
Nagarajan
 
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
Edureka!
 
How to go about testing in React?
Lisa Gagarina
 
Express JS
Designveloper
 
Spring Boot
HongSeong Jeon
 
NodeJS for Beginner
Apaichon Punopas
 
12 Steps to API Load Testing with Apache JMeter
WSO2
 
How to Build Real-time Chat App with Express, ReactJS, and Socket.IO?
Katy Slemon
 
Introduction to Node js
Akshay Mathur
 
Spring boot
sdeeg
 
Introduction to spring boot
Santosh Kumar Kar
 
Testing of React JS app
Aleks Zinevych
 
Lab #2: Introduction to Javascript
Walid Ashraf
 

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
TDD a REST API With Node.js and MongoDB
Valeri Karpov
 
PDF
Developing and Testing a MongoDB and Node.js REST API
All Things Open
 
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
 
TDD a REST API With Node.js and MongoDB
Valeri Karpov
 
Developing and Testing a MongoDB and Node.js REST API
All Things Open
 
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)

PDF
20ES1152 Programming for Problem Solving Lab Manual VRSEC.pdf
Ashutosh Satapathy
 
PPTX
What is Shot Peening | Shot Peening is a Surface Treatment Process
Vibra Finish
 
PPTX
Presentation 2.pptx AI-powered home security systems Secure-by-design IoT fr...
SoundaryaBC2
 
PPTX
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
PPT
Carmon_Remote Sensing GIS by Mahesh kumar
DhananjayM6
 
PDF
Data structures notes for unit 2 in computer science.pdf
sshubhamsingh265
 
PPTX
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
PPTX
MATLAB : Introduction , Features , Display Windows, Syntax, Operators, Graph...
Amity University, Patna
 
PPTX
The Role of Information Technology in Environmental Protectio....pptx
nallamillisriram
 
PDF
SERVERLESS PERSONAL TO-DO LIST APPLICATION
anushaashraf20
 
PPTX
Introduction to Design of Machine Elements
PradeepKumarS27
 
PPTX
Introduction to Internal Combustion Engines - Types, Working and Camparison.pptx
UtkarshPatil98
 
PPTX
Damage of stability of a ship and how its change .pptx
ehamadulhaque
 
PPTX
Water Resources Engineering (CVE 728)--Slide 3.pptx
mohammedado3
 
PPT
New_school_Engineering_presentation_011707.ppt
VinayKumar304579
 
PPTX
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
PDF
Electrical Machines and Their Protection.pdf
Nabajyoti Banik
 
PDF
Halide Perovskites’ Multifunctional Properties: Coordination Engineering, Coo...
TaameBerhe2
 
PDF
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 
PDF
MAD Unit - 1 Introduction of Android IT Department
JappanMavani
 
20ES1152 Programming for Problem Solving Lab Manual VRSEC.pdf
Ashutosh Satapathy
 
What is Shot Peening | Shot Peening is a Surface Treatment Process
Vibra Finish
 
Presentation 2.pptx AI-powered home security systems Secure-by-design IoT fr...
SoundaryaBC2
 
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
Carmon_Remote Sensing GIS by Mahesh kumar
DhananjayM6
 
Data structures notes for unit 2 in computer science.pdf
sshubhamsingh265
 
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
MATLAB : Introduction , Features , Display Windows, Syntax, Operators, Graph...
Amity University, Patna
 
The Role of Information Technology in Environmental Protectio....pptx
nallamillisriram
 
SERVERLESS PERSONAL TO-DO LIST APPLICATION
anushaashraf20
 
Introduction to Design of Machine Elements
PradeepKumarS27
 
Introduction to Internal Combustion Engines - Types, Working and Camparison.pptx
UtkarshPatil98
 
Damage of stability of a ship and how its change .pptx
ehamadulhaque
 
Water Resources Engineering (CVE 728)--Slide 3.pptx
mohammedado3
 
New_school_Engineering_presentation_011707.ppt
VinayKumar304579
 
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
Electrical Machines and Their Protection.pdf
Nabajyoti Banik
 
Halide Perovskites’ Multifunctional Properties: Coordination Engineering, Coo...
TaameBerhe2
 
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 
MAD Unit - 1 Introduction of Android IT Department
JappanMavani
 
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/