SlideShare a Scribd company logo
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

More Related Content

What's hot

Top 10 frameworks of node js
Top 10 frameworks of node jsTop 10 frameworks of node js
Top 10 frameworks of node js
Habilelabs
 
MongoDB 101
MongoDB 101MongoDB 101
MongoDB 101
Abhijeet Vaikar
 
Basics of MongoDB
Basics of MongoDB Basics of MongoDB
Basics of MongoDB
Habilelabs
 
Connecting NodeJS & MongoDB
Connecting NodeJS & MongoDBConnecting NodeJS & MongoDB
Connecting NodeJS & MongoDB
Enoch Joshua
 
Mongo db basics
Mongo db basicsMongo db basics
Mongo db basics
Claudio Montoya
 
Node js getting started
Node js getting startedNode js getting started
Node js getting started
Pallavi Srivastava
 
Introduction to mongo db
Introduction to mongo dbIntroduction to mongo db
Introduction to mongo db
NexThoughts Technologies
 
Intro to mongo db
Intro to mongo dbIntro to mongo db
Intro to mongo db
Chi 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 tutorials
SpringPeople
 
MongoDB for Beginners
MongoDB for BeginnersMongoDB for Beginners
MongoDB for Beginners
Enoch Joshua
 
Mongodb
MongodbMongodb
Mongodb
Scott Motte
 
Mongo db
Mongo dbMongo db
Mongo db
Raghu nath
 
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
gillygize
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDBJustin Smestad
 
Mongo DB 102
Mongo DB 102Mongo DB 102
Mongo DB 102
Abhijeet Vaikar
 
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 Tools
Rainforest QA
 
Web Services with Objective-C
Web Services with Objective-CWeb Services with Objective-C
Web Services with Objective-C
Juio Barros
 
An introduction to MongoDB
An introduction to MongoDBAn introduction to MongoDB
An introduction to MongoDB
César Trigo
 

What's hot (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
 

Similar to Node js crash course session 5

MongoDB
MongoDBMongoDB
MongoDB
kesavan N B
 
MongoDB.pdf
MongoDB.pdfMongoDB.pdf
MongoDB.pdf
ArthyR3
 
NOSQL and MongoDB Database
NOSQL and MongoDB DatabaseNOSQL and MongoDB Database
NOSQL and MongoDB Database
Tariqul 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 Stack
MongoDB
 
Mongoose and MongoDB 101
Mongoose and MongoDB 101Mongoose and MongoDB 101
Mongoose and MongoDB 101
Will Button
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
S.Shayan Daneshvar
 
Mongo DB
Mongo DBMongo 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
 
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
Lisa Roth, PMP
 
PostgreSQL, MongoDb, Express, React, Structured
PostgreSQL, MongoDb, Express, React, StructuredPostgreSQL, MongoDb, Express, React, Structured
PostgreSQL, MongoDb, Express, React, Structured
priya951125
 
Switch to Backend 2023
Switch to Backend 2023Switch to Backend 2023
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Winston Hsieh
 
Hatkit Project - Datafiddler
Hatkit Project - DatafiddlerHatkit Project - Datafiddler
Hatkit Project - Datafiddler
holiman
 
Mongodb Introduction
Mongodb IntroductionMongodb Introduction
Mongodb Introduction
Raghvendra Parashar
 
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
Muhammad Raza
 
SCDJWS 6. REST JAX-P
SCDJWS 6. REST  JAX-PSCDJWS 6. REST  JAX-P
SCDJWS 6. REST JAX-P
Francesco Ierna
 
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
MongoDB
 
CSC PPT 12.pptx
CSC PPT 12.pptxCSC PPT 12.pptx
CSC PPT 12.pptx
DrRavneetSingh
 
MongoDB - An Introduction
MongoDB - An IntroductionMongoDB - An Introduction
MongoDB - An Introduction
sethfloydjr
 

Similar to 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
 

Recently uploaded

Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
Srikant77
 

Recently uploaded (20)

Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
 

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