KEMBAR78
RESTful API In Node Js using Express | PPT
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 :)

RESTful API In Node Js using Express

  • 1.
    Restful Api withExpress js, Node js & MySQl Presented by : Jeetendra Singh
  • 2.
    Prerequisite to expressjs • 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’squite 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 Expressjs? • 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 andMySQL • 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 sampledata 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 RestfulProject Go to Terminal or Command Line, create a project folder. > mkdir express-node-rest-project > cd express-node-rest-project
  • 9.
    create a filepackage.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 myfinal 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 jsframework and MySQL driver with NPM. > npm install express --save > npm install mysql --save > npm install body-parser --save
  • 12.
    We are goingto implement following API calls
  • 13.
    Create Express Server Createserver.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 isready, 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 APIcalls 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 withid 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 fortodos 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 newtodo 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 withid 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/
  • 23.