NODE - UsmanLive · BUILDING RESTFUL API'S USING EXPRESS. Client/Server Architecture Usman Akram...
Transcript of NODE - UsmanLive · BUILDING RESTFUL API'S USING EXPRESS. Client/Server Architecture Usman Akram...
NODEBUILDING RESTFUL API'S USING EXPRESS
Client/Server Architecture
Usman Akram CUI LAHORE 2
Client/Server Architecture
Usman Akram CUI LAHORE 3
REpresentational State Transfer (REST)
Usman Akram CUI LAHORE 4
http://usman.com/api/customers
Usman Akram CUI LAHORE 5
http://usman.com/api/customers
Usman Akram CUI LAHORE 6
http://usman.com/api/customers/1
Usman Akram CUI LAHORE 7
http://usman.com/api/customers/1
Usman Akram CUI LAHORE 8
http://usman.com/api/customers/1
Usman Akram CUI LAHORE 9
http://usman.com/api/customers/1
Usman Akram CUI LAHORE 10
http://usman.com/api/customers
Usman Akram CUI LAHORE 11
All RESTFUL calls
Usman Akram CUI LAHORE 12
Pain to code like this const server = http.createServer((req,res)=>{
if(req.url==='/'){
res.write(JSON.stringify([1,4,5,6]));
res.end();
}
});
Usman Akram CUI LAHORE 13
Express https://www.npmjs.com/package/express15 Million Downloads a Month
npm i express
Usman Akram CUI LAHORE 14
Expressconst express = require('express');
const app = express();
app.use(express.json()); //middleware
//handle api calls here
Usman Akram CUI LAHORE 15
Expressconst port = 3000;
app.listen(port,function(){
console.log(`Listening on Port 3000....`);
})
Usman Akram CUI LAHORE 16
Express API Callslet courses = [
{id:1,name:'Operating Systems'},
{id:2,name:'Math'}
];
Usman Akram CUI LAHORE 17
Get callapp.get('/',function (request,response) {
response.send("Hello World");
});
Usman Akram CUI LAHORE 18
Send array back to clientapp.get('/api/courses',function (request,response) {
response.send([1,3,4,5,5,8]);
});
Usman Akram CUI LAHORE 19
Route parametersapp.get('/api/courses/:id',function (request,response) {
//request.query to get query parameters
const course = courses.find(c=>c.id==request.params.id);
if(!course)
return response.status(404).send("Course not found for given ID");
response.send(course);
});
Usman Akram CUI LAHORE 20
Post requestapp.post('/api/courses',(request,response)=>{
if(!request.body.name) response.status(400).send("Body Not provided");
else {const course = {
id:courses.length+1,
name:request.body.name
}
courses.push(course);
response.send(course);
}});
Usman Akram CUI LAHORE 21
Postman
Usman Akram CUI LAHORE 22
Postman
Usman Akram CUI LAHORE 23
Validation with joinpm I joi
const Joi = require('joi');
const schema = {
name:Joi.string().min(3).required()
}
Usman Akram CUI LAHORE 24
Validation with joiconst result = Joi.validate(request.body,schema);
//console.log(result);
if(result.error) response.status(400).send(result.error.details[0].message);
Usman Akram CUI LAHORE 25
Clean joifunction validateCourse(course) {
const schema = {
name: Joi.string().min(3).required()
};
const result = Joi.validate(course, schema);
return result;
} //require joi at top preferably extract a //module
Usman Akram CUI LAHORE 26
Put Requestapp.put('/api/courses/:id',(request,response)=>{
const course = courses.find(c=>c.id==request.params.id);
if(!course) {
response.status(404).send("Course not found for given ID"); return;
}
course.name = request.body.name;
const {error} = validateCourse({name:course.name});
Usman Akram CUI LAHORE 27
Put Requestif(error) {
response.status(400).send(error.details[0].message);
return;
}
response.send(course);
});
Usman Akram CUI LAHORE 28
Delete Requestapp.delete("/api/courses/:id", (request, response) => {
const course = courses.find(c => c.id == request.params.id);
if (!course) {
response.status(404).send("Course not found for given ID"); return;
}
Usman Akram CUI LAHORE 29
Delete Requestconst index = courses.indexOf(course);
courses.splice(index, 1);
response.send(course);
});
Usman Akram CUI LAHORE 30
Grab the source code and get startedhttps://1drv.ms/f/s!AtGKdbMmNBGdhHN4tlJnBBdKqjUm
Run
> npm install
>node index.js
Go through the code
Usman Akram CUI LAHORE 31
Express- Advanced TopicsGO PRO
Middlewareapp.get('/',function (request,response) {
response.send("Hello World");
});
Is technically a middleware. It breaks the request response cycle
What if we do something here and then don’t send response.
Usman Akram CUI LAHORE 33
Adding a middlewareconst express = require('express');
const app = express();
app.use(express.json());
Get request
If body contain json then parse it
Forward it to next middleware.
Usman Akram CUI LAHORE 34
Request processing pipeline
Usman Akram CUI LAHORE 35
Custom middlewarefunction log(request,response,next){
console.log("Logging...");
next();
}
module.exports = log;
Usman Akram CUI LAHORE 36
Using your own middlewareconst logger = require('./logger-middleware');
app.use(logger);
Usman Akram CUI LAHORE 37
helmethelmet helps you secure your Express apps by setting various HTTP headers. It's not a silver bullet, but it can help!
First, run npm install helmet
const express = require('express')
const helmet = require('helmet')
const app = express()
app.use(helmet())
Usman Akram CUI LAHORE 38
First, run npm install helmet
ExerciseCheck what morgan is and how it works
Info:
Urlencoded middleware is built in. It parse info from url
Usman Akram CUI LAHORE 39
HTML ?
Usman Akram CUI LAHORE 40
PUGapp.use(express.static('public'));
app.set('view engine', 'pug');
app.get('/', function (request, response) {
//response.send("Hello World");
response.render('index', { title: "My PaogeTitle", message: 'Hello Hareem h1 Tag' });
});
Usman Akram CUI LAHORE 41
/views/index.pughtml
head
title=title
body
h1=message
Usman Akram CUI LAHORE 42