SlideShare uma empresa Scribd logo
1 de 25
Node JS crash course
Build REST API | 8:15 pm
Abdul Rahman
Masri Attal
@abed_attal
Elie Hannouch
@eliehannouch
● A REST API (also known as RESTful API) is an application programming
interface (API or web API) that conforms to the constraints of REST
architectural style and allows for interaction with RESTful web services.
What is REST API
● REST which stands for Representational State Transfer, is an architectural
style for providing standards between computer systems on the web and
mostly use JSON as the preferred choice for transferring data as they are
easy to understand and is readable.
● What is server
● Express
● Routing
● Body params
Recap of last week var express = require(“express”)
var app = express();
app.get(‘/’, function(req,res){
res.send(‘First node app’);
}
app.get('/search/:id', function(req, res){
res.send(‘This is id’+req.param.id);
});
var port = Number(process.env.port || 3000);
app.listen(3000,function(){
console.log(“Listening on “ + port + “...”);
}
app.get('/search?id=1', function(req, res){
res.send('id: ' + req.query.id);
//req.query.id => give value: 1
});
app.post('/register', (req, res) => {
// logic to save to database
res.status(201).send({message : Saved!})
});
Req query & Error status code
// 401 Unauthorized
app.get('/user', (req, res) => {
res.status(401).send({message : "You need to login to view this"})
});
// 500 Internal Server Error
app.post('/500', (req, res) => {
res.status(500).send({message : "I failed. I'm sorry"})
});
Express and MongoDB
In this tutorial, we will be using Node, Express and MongoDB to create a REST
API that would support the four operations — GET, POST, PUT and DELETE.
So, our REST API will perform all these four operations.
We will use MongoDB as the NoSQL database to store all our data. MongoDB
stores data in JSON format.
Rest API and Front End
Finally, our front-end application (for example React) use the REST API endpoints
hosted on the Express.js server. The application is a Tinder-like application for
the sample_airbnb database, containing information on various listings, available
as part of the sample datasets you can load into the Atlas cluster.
Connecting to MongoDB Atlas
● Create a config file in the server directory with your connection string.
● There, assign a new ATLAS_URI variable the value of the connection string.
● Replace the <username> and the <password> with your database username
and password. Once done, your file should look similar to the one below.
● ATLAS_URI=mongodb+srv://<username>:<password>@sandbox.jadwj.mongodb.
net/myFirstDatabase?retryWrites=true&w=majority
Connecting to MongoDB Atlas
What is the best way to interact with a database?
There are two common approaches for interacting with a database:
● Using the databases' native query language (e.g. MongoDB)
● Using an Object Data Model ("ODM") or an Object Relational Model ("ORM").
An ODM/ORM represents the website's data as JavaScript objects, which are
then mapped to the underlying database. Some ORMs are tied to a specific
database, while others provide a database-agnostic backend.
const { MongoClient } = require("mongodb");
const connectionString = process.env.ATLAS_URI;
const client = new MongoClient(connectionString,
{
useNewUrlParser: true,
useUnifiedTopology:true,
}
);
Connect MongoDB Natively
let dbConnection;
module.exports = {
connectToServer: function (callback) {
client.connect(function (err, db) {
if (err || !db)
return callback(err);
dbConnection = db.db("sample_airbnb");
console.log("Successfully connected to MongoDB.");
return callback();
}); },
getDb: function () {
return dbConnection;
},
};
app.get("/listings",function (req, res)=> {
const dbConnect = dbo.getDb();
dbConnect
.collection("listingsAndReviews")
.find({})
.toArray(function (err, result) {
if (err) {
res.status(400).send("Error fetching listings!");
} else {
res.json(result);
}
});
});
Execute Native MongoDB Queries - find
app.post("/listings/recordSwipe",function (req, res) => {
const dbConnect = dbo.getDb();
const matchDocument = { “title”:”hello” };
dbConnect
.collection("matches")
.insertOne(matchDocument, function (err, result) {
if (err) {
res.status(400).send("Error inserting matches!");}
else {
console.log(`Added a new match with id ${result.insertedId}`);
res.status(204).send(); }
});
});
Execute MongoDB Queries - insertOne
We're going to use the Mongoose ODM to access our database.
Mongoose acts as a front end to MongoDB, an open source NoSQL database
that uses a document-oriented data model. A “collection” of “documents” in a
MongoDB database is analogous to a “table” of “rows” in a relational database.
This ODM and database combination is extremely popular in the Node
community, partially because the document storage and query system looks
very much like JSON, and is hence familiar to JavaScript developers.
Using Mongoose and MongoDb
Mongoose is installed in your project like any other dependency using NPM.
To install it, use the following command inside your project folder:
npm install mongoose
Installing Mongoose adds all its dependencies, including the MongoDB database
driver, but it does not install MongoDB itself.
Installing Mongoose and MongoDB
Connecting to MongoDB using Mongoose
Mongoose requires a connection to a MongoDB database. You can require() and
connect to a locally hosted database with mongoose.connect(), as shown below.
var mongoose = require('mongoose');
var mongoDB = 'mongodb://127.0.0.1/my_database';
mongoose.connect(mongoDB, {useNewUrlParser: true, useUnifiedTopology: true});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
MVC
We can describe the MVC architecture in simple terms:
● Model: the part of our application that will deal
with the database or any data-related
functionality.
● View: everything the user will see — basically, the
pages that we’re going to send to the client.
● Controller: the logic of our site, and the glue
between models and views. Here we call our
models to get the data, then we put that data on
our views to be sent to the users.
Defining and creating models
● Models are defined using the Schema interface which allows you to define the
fields stored in each document along with their validation requirements and
default values.
● In addition, you can define static and instance helper methods to make it
easier to work with your data types, and also virtual properties that you can
use like any other field, but which aren't actually stored in the database
● Schemas are then "compiled" into models using the mongoose.model()
method. Once you have a model you can use it to find, create, update, and
delete objects of the given type.
The code fragment below shows how you might define a simple schema. First
you require() mongoose, then use the Schema constructor to create a new
schema instance, defining the various fields inside it in the constructor's object
parameter.
Defining schemas
var mongoose = require('mongoose');
//Define a schema
var Schema = mongoose.Schema;
var SomeModelSchema = new Schema({
a_string: String,
a_date: Date
});
var SomeModel = mongoose.model('SomeModel', SomeModelSchema );
Schema types (fields)
A schema can have an arbitrary number of fields — each one represents a
field in the documents stored in MongoDB. An example schema showing
many of the common field types and how they are declared is shown below.
● Date
● Number
● Boolean
● etc..
Validation
Mongoose provides built-in and custom validators, and synchronous and asynchronous
validators. It allows you to specify both the acceptable range of values and the error message
for validation failure in all cases.
The built-in validators include:
● All SchemaTypes have the built-in required validator. This is used to specify whether the
field must be supplied in order to save a document.
● Numbers have min and max validators.
● Strings have:
○ enum: specifies the set of allowed values for the field.
○ match: specifies a regular expression that the string must match.
○ maxLength and minLength for the string.
Schema example with validation
var schema = new Schema(
{
name: String,
binary: Buffer,
living: Boolean,
updated: { type: Date, default: Date.now() },
age: { type: Number, min: 18, max: 65, required: true },
array: [],
ofString: [String],
nested: { stuff: { type: String, lowercase: true, trim: true } }
})
const express = require('express'); //import express
const router = express.Router()
const teaController = require('../controllers/tea');
router.post('/tea', teaController.newTea);
module.exports = router
Express and Routes
// newTea function for post tea route
const newTea = (req, res, next) => {
res.json({message: "POST new tea"}); //dummyfuncti
};
module.exports = {newTea};
route.js
/controllers/tea.js
const express = require ('express');
const routes = require('./routes/tea');
const app = express();
app.use(express.json());
app.use('/', routes); //to use the routes
const listener = app.listen(process.env.PORT || 3000,
() => { console.log('Your app is listening on port ' +
listener.address().port) })
server.js
Once you've created a schema you can use it to create models. The model
represents a collection of documents in the database that you can search,
while the model's instances represent individual documents that you can save
and retrieve.
Using Models
var Athlete = mongoose.model('Athlete', yourSchema);
// Create an instance of model Athlete
var athlete = new Athlete({ name: 'awesome' });
// Save the new model instance, passing a callback
athlete.save(function (err) {
if (err) return handleError(err);
// saved!
});
// find all athletes who play tennis, selecting the 'name' and 'age'
Athlete.find({ 'sport': 'Tennis' }, 'name age', function (err, athletes) {
if (err) return handleError(err);
// 'athletes' list of athletes match the criteria.
})
module.exports = (app) => {
const brands = require('../controllers/brand.controller.js');
// Create a new brand
app.post('/brands', brands.create);
// Retrieve all brands
app.get('/brands', brands.findAll);
Creating CRUD REST
Basic GET & POST
// Retrieve a single brand with brandId
app.get('/brands/:brandId', brands.findOne);
// Update a brand with brandId
app.put('/brands/:brandId', brands.update);
// Delete a brand with brandId
app.delete('/brands/:brandId', brands.delete);
}
Creating CRUD REST
API by ID : GET & UPDATE & DELETE

Mais conteúdo relacionado

Mais procurados

Top 10 frameworks of node js
Top 10 frameworks of node jsTop 10 frameworks of node js
Top 10 frameworks of node jsHabilelabs
 
Basics of MongoDB
Basics of MongoDB Basics of MongoDB
Basics of MongoDB Habilelabs
 
Connecting NodeJS & MongoDB
Connecting NodeJS & MongoDBConnecting NodeJS & MongoDB
Connecting NodeJS & MongoDBEnoch Joshua
 
Intro to mongo db
Intro to mongo dbIntro to mongo db
Intro to mongo dbChi Lee
 
Mongo DB: Fundamentals & Basics/ An Overview of MongoDB/ Mongo DB tutorials
Mongo DB: Fundamentals & Basics/ An Overview of MongoDB/ Mongo DB tutorialsMongo DB: Fundamentals & Basics/ An Overview of MongoDB/ Mongo DB tutorials
Mongo DB: Fundamentals & Basics/ An Overview of MongoDB/ Mongo DB tutorialsSpringPeople
 
MongoDB for Beginners
MongoDB for BeginnersMongoDB for Beginners
MongoDB for BeginnersEnoch Joshua
 
Connecting to a REST API in iOS
Connecting to a REST API in iOSConnecting to a REST API in iOS
Connecting to a REST API in iOSgillygize
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDBJustin Smestad
 
Using Webservice in iOS
Using Webservice  in iOS Using Webservice  in iOS
Using Webservice in iOS Mahboob Nur
 
mobile in the cloud with diamonds. improved.
mobile in the cloud with diamonds. improved.mobile in the cloud with diamonds. improved.
mobile in the cloud with diamonds. improved.Oleg Shanyuk
 
MongoDB Command Line Tools
MongoDB Command Line ToolsMongoDB Command Line Tools
MongoDB Command Line ToolsRainforest QA
 
Web Services with Objective-C
Web Services with Objective-CWeb Services with Objective-C
Web Services with Objective-CJuio Barros
 
An introduction to MongoDB
An introduction to MongoDBAn introduction to MongoDB
An introduction to MongoDBCésar Trigo
 

Mais procurados (20)

Top 10 frameworks of node js
Top 10 frameworks of node jsTop 10 frameworks of node js
Top 10 frameworks of node js
 
MongoDB 101
MongoDB 101MongoDB 101
MongoDB 101
 
Basics of MongoDB
Basics of MongoDB Basics of MongoDB
Basics of MongoDB
 
Connecting NodeJS & MongoDB
Connecting NodeJS & MongoDBConnecting NodeJS & MongoDB
Connecting NodeJS & MongoDB
 
Mongo db basics
Mongo db basicsMongo db basics
Mongo db basics
 
Node js getting started
Node js getting startedNode js getting started
Node js getting started
 
Introduction to mongo db
Introduction to mongo dbIntroduction to mongo db
Introduction to mongo db
 
Intro to mongo db
Intro to mongo dbIntro to mongo db
Intro to mongo db
 
Mongo DB: Fundamentals & Basics/ An Overview of MongoDB/ Mongo DB tutorials
Mongo DB: Fundamentals & Basics/ An Overview of MongoDB/ Mongo DB tutorialsMongo DB: Fundamentals & Basics/ An Overview of MongoDB/ Mongo DB tutorials
Mongo DB: Fundamentals & Basics/ An Overview of MongoDB/ Mongo DB tutorials
 
MongoDB for Beginners
MongoDB for BeginnersMongoDB for Beginners
MongoDB for Beginners
 
Mongodb
MongodbMongodb
Mongodb
 
Mongo db
Mongo dbMongo db
Mongo db
 
Connecting to a REST API in iOS
Connecting to a REST API in iOSConnecting to a REST API in iOS
Connecting to a REST API in iOS
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
Mongo DB 102
Mongo DB 102Mongo DB 102
Mongo DB 102
 
Using Webservice in iOS
Using Webservice  in iOS Using Webservice  in iOS
Using Webservice in iOS
 
mobile in the cloud with diamonds. improved.
mobile in the cloud with diamonds. improved.mobile in the cloud with diamonds. improved.
mobile in the cloud with diamonds. improved.
 
MongoDB Command Line Tools
MongoDB Command Line ToolsMongoDB Command Line Tools
MongoDB Command Line Tools
 
Web Services with Objective-C
Web Services with Objective-CWeb Services with Objective-C
Web Services with Objective-C
 
An introduction to MongoDB
An introduction to MongoDBAn introduction to MongoDB
An introduction to MongoDB
 

Semelhante a Node js crash course session 5

MongoDB.pdf
MongoDB.pdfMongoDB.pdf
MongoDB.pdfArthyR3
 
NOSQL and MongoDB Database
NOSQL and MongoDB DatabaseNOSQL and MongoDB Database
NOSQL and MongoDB DatabaseTariqul islam
 
MongoDB Days UK: Building Apps with the MEAN Stack
MongoDB Days UK: Building Apps with the MEAN StackMongoDB Days UK: Building Apps with the MEAN Stack
MongoDB Days UK: Building Apps with the MEAN StackMongoDB
 
Mongoose and MongoDB 101
Mongoose and MongoDB 101Mongoose and MongoDB 101
Mongoose and MongoDB 101Will Button
 
MongoDB .local London 2019: Fast Machine Learning Development with MongoDB
MongoDB .local London 2019: Fast Machine Learning Development with MongoDBMongoDB .local London 2019: Fast Machine Learning Development with MongoDB
MongoDB .local London 2019: Fast Machine Learning Development with MongoDBLisa Roth, PMP
 
MongoDB .local London 2019: Fast Machine Learning Development with MongoDB
MongoDB .local London 2019: Fast Machine Learning Development with MongoDBMongoDB .local London 2019: Fast Machine Learning Development with MongoDB
MongoDB .local London 2019: Fast Machine Learning Development with MongoDBMongoDB
 
PostgreSQL, MongoDb, Express, React, Structured
PostgreSQL, MongoDb, Express, React, StructuredPostgreSQL, MongoDb, Express, React, Structured
PostgreSQL, MongoDb, Express, React, Structuredpriya951125
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsWinston Hsieh
 
Hatkit Project - Datafiddler
Hatkit Project - DatafiddlerHatkit Project - Datafiddler
Hatkit Project - Datafiddlerholiman
 
Introduction to mean and mern || Event by DSC UNIDEB
Introduction to mean and mern || Event by DSC UNIDEBIntroduction to mean and mern || Event by DSC UNIDEB
Introduction to mean and mern || Event by DSC UNIDEBMuhammad Raza
 
MongoDB World 2019: Fast Machine Learning Development with MongoDB
MongoDB World 2019: Fast Machine Learning Development with MongoDBMongoDB World 2019: Fast Machine Learning Development with MongoDB
MongoDB World 2019: Fast Machine Learning Development with MongoDBMongoDB
 
MongoDB - An Introduction
MongoDB - An IntroductionMongoDB - An Introduction
MongoDB - An Introductionsethfloydjr
 

Semelhante a Node js crash course session 5 (20)

MongoDB
MongoDBMongoDB
MongoDB
 
MongoDB.pdf
MongoDB.pdfMongoDB.pdf
MongoDB.pdf
 
NOSQL and MongoDB Database
NOSQL and MongoDB DatabaseNOSQL and MongoDB Database
NOSQL and MongoDB Database
 
MongoDB Days UK: Building Apps with the MEAN Stack
MongoDB Days UK: Building Apps with the MEAN StackMongoDB Days UK: Building Apps with the MEAN Stack
MongoDB Days UK: Building Apps with the MEAN Stack
 
Mongoose and MongoDB 101
Mongoose and MongoDB 101Mongoose and MongoDB 101
Mongoose and MongoDB 101
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
Mongo DB
Mongo DBMongo DB
Mongo DB
 
MongoDB .local London 2019: Fast Machine Learning Development with MongoDB
MongoDB .local London 2019: Fast Machine Learning Development with MongoDBMongoDB .local London 2019: Fast Machine Learning Development with MongoDB
MongoDB .local London 2019: Fast Machine Learning Development with MongoDB
 
MongoDB .local London 2019: Fast Machine Learning Development with MongoDB
MongoDB .local London 2019: Fast Machine Learning Development with MongoDBMongoDB .local London 2019: Fast Machine Learning Development with MongoDB
MongoDB .local London 2019: Fast Machine Learning Development with MongoDB
 
PostgreSQL, MongoDb, Express, React, Structured
PostgreSQL, MongoDb, Express, React, StructuredPostgreSQL, MongoDb, Express, React, Structured
PostgreSQL, MongoDb, Express, React, Structured
 
Switch to Backend 2023
Switch to Backend 2023Switch to Backend 2023
Switch to Backend 2023
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Hatkit Project - Datafiddler
Hatkit Project - DatafiddlerHatkit Project - Datafiddler
Hatkit Project - Datafiddler
 
Mongodb Introduction
Mongodb IntroductionMongodb Introduction
Mongodb Introduction
 
Introduction to mean and mern || Event by DSC UNIDEB
Introduction to mean and mern || Event by DSC UNIDEBIntroduction to mean and mern || Event by DSC UNIDEB
Introduction to mean and mern || Event by DSC UNIDEB
 
SCDJWS 6. REST JAX-P
SCDJWS 6. REST  JAX-PSCDJWS 6. REST  JAX-P
SCDJWS 6. REST JAX-P
 
MongoDB World 2019: Fast Machine Learning Development with MongoDB
MongoDB World 2019: Fast Machine Learning Development with MongoDBMongoDB World 2019: Fast Machine Learning Development with MongoDB
MongoDB World 2019: Fast Machine Learning Development with MongoDB
 
CSC PPT 12.pptx
CSC PPT 12.pptxCSC PPT 12.pptx
CSC PPT 12.pptx
 
Express node js
Express node jsExpress node js
Express node js
 
MongoDB - An Introduction
MongoDB - An IntroductionMongoDB - An Introduction
MongoDB - An Introduction
 

Último

8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedDelhi Call girls
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxalwaysnagaraju26
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfayushiqss
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfryanfarris8
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...Nitya salvi
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456KiaraTiradoMicha
 

Último (20)

8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
 

Node js crash course session 5

  • 1. Node JS crash course Build REST API | 8:15 pm Abdul Rahman Masri Attal @abed_attal Elie Hannouch @eliehannouch
  • 2. ● A REST API (also known as RESTful API) is an application programming interface (API or web API) that conforms to the constraints of REST architectural style and allows for interaction with RESTful web services. What is REST API ● REST which stands for Representational State Transfer, is an architectural style for providing standards between computer systems on the web and mostly use JSON as the preferred choice for transferring data as they are easy to understand and is readable.
  • 3. ● What is server ● Express ● Routing ● Body params Recap of last week var express = require(“express”) var app = express(); app.get(‘/’, function(req,res){ res.send(‘First node app’); } app.get('/search/:id', function(req, res){ res.send(‘This is id’+req.param.id); }); var port = Number(process.env.port || 3000); app.listen(3000,function(){ console.log(“Listening on “ + port + “...”); }
  • 4. app.get('/search?id=1', function(req, res){ res.send('id: ' + req.query.id); //req.query.id => give value: 1 }); app.post('/register', (req, res) => { // logic to save to database res.status(201).send({message : Saved!}) }); Req query & Error status code // 401 Unauthorized app.get('/user', (req, res) => { res.status(401).send({message : "You need to login to view this"}) }); // 500 Internal Server Error app.post('/500', (req, res) => { res.status(500).send({message : "I failed. I'm sorry"}) });
  • 5. Express and MongoDB In this tutorial, we will be using Node, Express and MongoDB to create a REST API that would support the four operations — GET, POST, PUT and DELETE. So, our REST API will perform all these four operations. We will use MongoDB as the NoSQL database to store all our data. MongoDB stores data in JSON format.
  • 6. Rest API and Front End Finally, our front-end application (for example React) use the REST API endpoints hosted on the Express.js server. The application is a Tinder-like application for the sample_airbnb database, containing information on various listings, available as part of the sample datasets you can load into the Atlas cluster.
  • 7. Connecting to MongoDB Atlas ● Create a config file in the server directory with your connection string. ● There, assign a new ATLAS_URI variable the value of the connection string. ● Replace the <username> and the <password> with your database username and password. Once done, your file should look similar to the one below. ● ATLAS_URI=mongodb+srv://<username>:<password>@sandbox.jadwj.mongodb. net/myFirstDatabase?retryWrites=true&w=majority
  • 9. What is the best way to interact with a database? There are two common approaches for interacting with a database: ● Using the databases' native query language (e.g. MongoDB) ● Using an Object Data Model ("ODM") or an Object Relational Model ("ORM"). An ODM/ORM represents the website's data as JavaScript objects, which are then mapped to the underlying database. Some ORMs are tied to a specific database, while others provide a database-agnostic backend.
  • 10. const { MongoClient } = require("mongodb"); const connectionString = process.env.ATLAS_URI; const client = new MongoClient(connectionString, { useNewUrlParser: true, useUnifiedTopology:true, } ); Connect MongoDB Natively let dbConnection; module.exports = { connectToServer: function (callback) { client.connect(function (err, db) { if (err || !db) return callback(err); dbConnection = db.db("sample_airbnb"); console.log("Successfully connected to MongoDB."); return callback(); }); }, getDb: function () { return dbConnection; }, };
  • 11. app.get("/listings",function (req, res)=> { const dbConnect = dbo.getDb(); dbConnect .collection("listingsAndReviews") .find({}) .toArray(function (err, result) { if (err) { res.status(400).send("Error fetching listings!"); } else { res.json(result); } }); }); Execute Native MongoDB Queries - find
  • 12. app.post("/listings/recordSwipe",function (req, res) => { const dbConnect = dbo.getDb(); const matchDocument = { “title”:”hello” }; dbConnect .collection("matches") .insertOne(matchDocument, function (err, result) { if (err) { res.status(400).send("Error inserting matches!");} else { console.log(`Added a new match with id ${result.insertedId}`); res.status(204).send(); } }); }); Execute MongoDB Queries - insertOne
  • 13. We're going to use the Mongoose ODM to access our database. Mongoose acts as a front end to MongoDB, an open source NoSQL database that uses a document-oriented data model. A “collection” of “documents” in a MongoDB database is analogous to a “table” of “rows” in a relational database. This ODM and database combination is extremely popular in the Node community, partially because the document storage and query system looks very much like JSON, and is hence familiar to JavaScript developers. Using Mongoose and MongoDb
  • 14. Mongoose is installed in your project like any other dependency using NPM. To install it, use the following command inside your project folder: npm install mongoose Installing Mongoose adds all its dependencies, including the MongoDB database driver, but it does not install MongoDB itself. Installing Mongoose and MongoDB
  • 15. Connecting to MongoDB using Mongoose Mongoose requires a connection to a MongoDB database. You can require() and connect to a locally hosted database with mongoose.connect(), as shown below. var mongoose = require('mongoose'); var mongoDB = 'mongodb://127.0.0.1/my_database'; mongoose.connect(mongoDB, {useNewUrlParser: true, useUnifiedTopology: true}); var db = mongoose.connection; db.on('error', console.error.bind(console, 'MongoDB connection error:'));
  • 16. MVC We can describe the MVC architecture in simple terms: ● Model: the part of our application that will deal with the database or any data-related functionality. ● View: everything the user will see — basically, the pages that we’re going to send to the client. ● Controller: the logic of our site, and the glue between models and views. Here we call our models to get the data, then we put that data on our views to be sent to the users.
  • 17. Defining and creating models ● Models are defined using the Schema interface which allows you to define the fields stored in each document along with their validation requirements and default values. ● In addition, you can define static and instance helper methods to make it easier to work with your data types, and also virtual properties that you can use like any other field, but which aren't actually stored in the database ● Schemas are then "compiled" into models using the mongoose.model() method. Once you have a model you can use it to find, create, update, and delete objects of the given type.
  • 18. The code fragment below shows how you might define a simple schema. First you require() mongoose, then use the Schema constructor to create a new schema instance, defining the various fields inside it in the constructor's object parameter. Defining schemas var mongoose = require('mongoose'); //Define a schema var Schema = mongoose.Schema; var SomeModelSchema = new Schema({ a_string: String, a_date: Date }); var SomeModel = mongoose.model('SomeModel', SomeModelSchema );
  • 19. Schema types (fields) A schema can have an arbitrary number of fields — each one represents a field in the documents stored in MongoDB. An example schema showing many of the common field types and how they are declared is shown below. ● Date ● Number ● Boolean ● etc..
  • 20. Validation Mongoose provides built-in and custom validators, and synchronous and asynchronous validators. It allows you to specify both the acceptable range of values and the error message for validation failure in all cases. The built-in validators include: ● All SchemaTypes have the built-in required validator. This is used to specify whether the field must be supplied in order to save a document. ● Numbers have min and max validators. ● Strings have: ○ enum: specifies the set of allowed values for the field. ○ match: specifies a regular expression that the string must match. ○ maxLength and minLength for the string.
  • 21. Schema example with validation var schema = new Schema( { name: String, binary: Buffer, living: Boolean, updated: { type: Date, default: Date.now() }, age: { type: Number, min: 18, max: 65, required: true }, array: [], ofString: [String], nested: { stuff: { type: String, lowercase: true, trim: true } } })
  • 22. const express = require('express'); //import express const router = express.Router() const teaController = require('../controllers/tea'); router.post('/tea', teaController.newTea); module.exports = router Express and Routes // newTea function for post tea route const newTea = (req, res, next) => { res.json({message: "POST new tea"}); //dummyfuncti }; module.exports = {newTea}; route.js /controllers/tea.js const express = require ('express'); const routes = require('./routes/tea'); const app = express(); app.use(express.json()); app.use('/', routes); //to use the routes const listener = app.listen(process.env.PORT || 3000, () => { console.log('Your app is listening on port ' + listener.address().port) }) server.js
  • 23. Once you've created a schema you can use it to create models. The model represents a collection of documents in the database that you can search, while the model's instances represent individual documents that you can save and retrieve. Using Models var Athlete = mongoose.model('Athlete', yourSchema); // Create an instance of model Athlete var athlete = new Athlete({ name: 'awesome' }); // Save the new model instance, passing a callback athlete.save(function (err) { if (err) return handleError(err); // saved! }); // find all athletes who play tennis, selecting the 'name' and 'age' Athlete.find({ 'sport': 'Tennis' }, 'name age', function (err, athletes) { if (err) return handleError(err); // 'athletes' list of athletes match the criteria. })
  • 24. module.exports = (app) => { const brands = require('../controllers/brand.controller.js'); // Create a new brand app.post('/brands', brands.create); // Retrieve all brands app.get('/brands', brands.findAll); Creating CRUD REST Basic GET & POST
  • 25. // Retrieve a single brand with brandId app.get('/brands/:brandId', brands.findOne); // Update a brand with brandId app.put('/brands/:brandId', brands.update); // Delete a brand with brandId app.delete('/brands/:brandId', brands.delete); } Creating CRUD REST API by ID : GET & UPDATE & DELETE