SlideShare a Scribd company logo
1 of 56
Switch to Backend
Getting started with backend development
By Siddharta Shankar Paul
Core Member, GDSC
Switch to backend Day 1
Topic structure
What is Fullstack
Development?
Frontend vs
Backend
Node.js &
NPM
How web works
What is backend?
HTTP requests
Static vs Dynamic
Websites
Full stack development is the end-to-end development of applications. It includes
both the front end and back end of an application. The front end is usually accessed by
a client, and the back end forms the core of the application where all the business logic
is applied.
What is Fullstack Development ?
Full Stack = FrontEnd + BackEnd
"Backend" refers to any part of a website or software program that users do not
see.
Blah blah blah...
What is Backend ?
"Backend" refers to any part of a website or software program that users do not
see.
Blah blah blah...
What is Backend ?
How web works
Payload (Request) DB Query
Response Data
Business Logic Resides
here
HTM
L
CSS Javascript
What is the need to Switch to Backend
???
●HTTP (Hyper Text Transfer Protocol)
●HTTPS (HTTP, but its Secure)
●TCP (Transmission Control Protocol)
●IP (Internet Protocol)
●API (Application Programming Interface)
Afraid of Buzzwords?
What is NodeJs???
Node. js is a single-threaded, open-source, cross-platform runtime
environment for building fast and scalable server-side and networking
applications. It runs on the V8 JavaScript runtime engine, and it uses event-
driven, non-blocking I/O architecture, which makes it efficient and suitable for
real-time applications.
● What is node JS in simple words?
● Is node JS for frontend or backend?
● What is Benefits of NodeJs?
What is REST API??
APIs are mechanisms that enable two software components to communicate with
each other using a set of definitions and protocols.
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. REST stands for representational state
transfer
The primary goal of API is to standardize data exchange between web services. Depending
on the type of API, the choice of protocol changes. On the other hand, REST API is an
architectural style for building web services that interact via an HTTP protocol.
When a client makes a request via a RESTful API, it transfers the information/representation of
the request or response from user to Webservice or vice versa through HTTP format.
REST APIs faster and more lightweight, with increased scalability—perfect for Internet of Things
(IoT) and mobile app development.
Request Method:
The request action should be indicated by the HTTP request method. The most common methods include GET, POST, PUT,
and DELETE.·
● GET retrieves resources. (From the above example: Get the menu list or food)
● POST submits new data to the server.(Order new food item to your order list)
● PUT updates existing data.(Changing from one variety to another like veg to non-veg)
● DELETE removes data.(Cancelling an item if it takes more time)
Response Method:
We can develop REST API, programming them to send the response according to the input header of the HTTP request. There
is a Media-Type attribute in the header which can be used in such cases and the response can be sent accordingly.
REST API can return both XML or JSON as response message, depending upon the Media-Type attribute in the HTTP request.
REST API must always return an appropriate Status code to the user/client so that the user/client can know the actual issue and
process accordingly.
HTTP Status Code Description:
● 1xx: Informational: It represents the request that has
been received, and it is in the continuing process.
● 2xx: Success: Success represents the HTTP Server
response that the server has successfully received
and understood the request.
● 3xx: Redirection: It indicates that further action must
be taken to fulfil the request.
● 4xx: Client Error: It represents an error when the
request has incorrect syntax or cannot complete the
request.
● 5xx: Server Error: The server has failed to fulfil a
valid request.
Thank You
Express.JS
How does express help you?
● Less code
● Promotes a better project structure
● Widely used. Has lots of plugins
Your First Express
Application
Your machine is the
localhost
Hostname: localhost
IP Address: 127.0.0.1
GET POST
PUT DELETE
PATCH
Methods
import express from "express";
const app = express();
app.get("/", (req, res)=>{
return res.send("Home");
}
app.listen(5000, ()=>{
console.log("Listening on PORT 5000");
});
Get the default export
from the express package
Create an Express
application
Set up your routes
Set the server up to listen
To HTTP requests
import fetch from 'node-fetch';
app.get("/post/rand", (req, res)=>{
const response = await fetch('https://dummyjson.com/posts');
const posts = await response.json();
const rand = Math.random() * posts.length;
for (let i = posts.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
const temp = posts[i];
posts[i] = posts[j];
posts[j] = temp;
}
const randomPosts = posts.subarray(0, rand);
return res.json({posts: randomPosts);
});
.
├── src/
│ └── routers/
│ └── hello.js
└── server.js
Structure your code
"post/:id”
Route Parameters
Specificity
Be more
Specific
As you go
up
app.get("/:hello/world", (_req, res)=>{
res.send('YO MAMA!');
});
app.get("/:hello/", (_req, res)=>{
res.send('SO!');
});
app.get("/", (_req, res)=>{
res.send('FAT!');
});
.
├── src/
│ ├── routers/
│ │ ├── hello.js
│ │ ├── post.js
│ │ └── index.js
│ └── controllers/
│ ├── hello/
│ │ └── get.js
│ ├── post/
│ │ ├── get.js
│ │ └── post.js
│ └── index.js
└── server.js
Structure your code
Again!
Extras
You don’t need them now, but you will
Middlewares
Router Middleware 1 Middleware 2
{could be more}
Controller
Cookies and Sessions
● Cookies are used to store data on the
client side.
Who am I speaking to?
● Sessions are used to store data on the
server side.
Static Folder
Direct access for clients.
Switch to Backend
Pratik Majumdar
@codadept
MongoDB & Prisma
Recap
Today’s Agenda
Database Prisma
ORM vs ODM Error Handling
SQL vs NoSQL
MongoDB
CRUD
● Systematic/organized collection of data
● Easily accessible and manageable
● SQL vs NoSQL
Database
MS Excel?
• SQL
○ Relational Database
○ Rows and columns
○ Pre-defined schema
○ Eg. MySQL, PostgreSQL
SQL vs NoSQL
Schema vs Schema-less
• NoSQL
○ Non-Relational Database
○ Documents
○ Dynamic schema
○ Eg. MongoDB, Redis
SELECT * FROM classroom WHERE id=1;
Need for ORM/ODM?
MySQL
MongoDB
db.classroom.find({id: 1})
SELECT
C.CUSTOMER_NAME, C.CITY, C.GRADE,
S.NAME AS "SALESMAN",
O.ORDER_NO, O.ORDER_DATE, O.PURCHASE_AMT
FROM CUSTOMER C
RIGHT JOIN SALESMAN S
ON S.SALESMAN_ID = C.SALESMAN_ID
LEFT JOIN ORDERS O
ON O.CUSTOMER_ID = C.CUSTOMER_ID
WHERE
O.PURCHASE_AMT >= 2000
AND
C.GRADE IS NOT NULL;
More complex query
We don’t write SQL or MongoDB Query Language in our project to access
DB. We use such mappers
ORM
● Object Relational Mapping
● Perform CRUD in Relational DB
ODM
● Object Document Mapping
● Perform CRUD in Non-Relational DB
ORM vs ODM
JS <-> Mapper <-> DB
● Dynamic schema
● Here instead of tables as in SQL DBs we have collections
MongoDB
NoSQL Database
user
{
“username”: “codadept”,
“scholarId”: 2012005
}
user
{
“firstName”: “Pratik”,
“scholarId”: 2012005
}
Stores data in
BSON - Binary Encoded JSON
MongoDB
Datatype
Has more data types than JSON
JSON
String, Boolean, Number,
Array, Object, null
BSON
String, Boolean, Number
(Integer, Float, Long,
Decimal128...), Array, null,
Date, BinData
MongoDB
ObjectId
Each document in the collection has _id field which acts as the unique
identifier for that document.
MongoDB
Query using the mongodb CLI
using my_database;
db.createCollection(“user”)
db.user.insert({“id”: 1, “name”: “Pratik”, “username”: “codadept”})
db.user.find()
Prisma
ORM/ODM
Prisma is a auto-generated query-builder for Node.js
Can be used both as ORM or ODM based on the database we use
Other alternatives
For SQL - sequelize
For MongoDB - mongoose
Prisma
Why?
● Think as objects and classes instead of complex queries
● Type-safe and auto-completion
● Easy to change databases
Prisma
Schema file prisma/schema.prisma
datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model Post {
id String @id @default(auto()) @map("_id") @db.ObjectId
title String
content String?
published Boolean @default(false)
author User? @relation(fields: [authorId], references: [id])
authorId String @db.ObjectId
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
email String @unique
name String?
posts Post[]
}
Prisma
Components
● Data source: Specifies your database connection (via an
environment variable)
● Generator: Indicates that you want to generate Prisma Client
● Data model: Defines your application models
Prisma
Data model
● Represent a table in relational databases or a collection in
MongoDB
● Provide the foundation for the queries in the Prisma Client
API
Prisma
Accessing your DB with @prisma/client
npm install @prisma/client
This invokes the prisma generate command which which reads
your Prisma schema and generates the Prisma Client code.
Prisma
Querying
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
// Run inside `async` function
const allUsers = await prisma.user.findMany()
Let’s code
// Run inside `async` function
const user = await prisma.user.create({
data: {
name: 'Alice',
email: 'alice@prisma.io',
posts: {
create: { title: 'Join us for Prisma Day
2020' },
},
},
})
Thank you

More Related Content

Similar to Switch to Backend 2023

Document Databases & RavenDB
Document Databases & RavenDBDocument Databases & RavenDB
Document Databases & RavenDBBrian Ritchie
 
Using Ajax In Domino Web Applications
Using Ajax In Domino Web ApplicationsUsing Ajax In Domino Web Applications
Using Ajax In Domino Web Applicationsdominion
 
Getting started with node JS
Getting started with node JSGetting started with node JS
Getting started with node JSHamdi Hmidi
 
RESTful applications: The why and how by Maikel Mardjan
RESTful applications: The why and how by Maikel MardjanRESTful applications: The why and how by Maikel Mardjan
RESTful applications: The why and how by Maikel MardjanJexia
 
Beginning MEAN Stack
Beginning MEAN StackBeginning MEAN Stack
Beginning MEAN StackRob Davarnia
 
GDSC Backend Bootcamp.pptx
GDSC Backend Bootcamp.pptxGDSC Backend Bootcamp.pptx
GDSC Backend Bootcamp.pptxSaaraBansode
 
Networked APIs with swift
Networked APIs with swiftNetworked APIs with swift
Networked APIs with swiftTim Burks
 
Introduction to Web Architecture
Introduction to Web ArchitectureIntroduction to Web Architecture
Introduction to Web ArchitectureChamnap Chhorn
 
JavaOne 2009 - TS-5276 - RESTful Protocol Buffers
JavaOne 2009 - TS-5276 - RESTful  Protocol BuffersJavaOne 2009 - TS-5276 - RESTful  Protocol Buffers
JavaOne 2009 - TS-5276 - RESTful Protocol BuffersMatt O'Keefe
 
Simple REST with Dropwizard
Simple REST with DropwizardSimple REST with Dropwizard
Simple REST with DropwizardAndrei Savu
 
WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!
WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!
WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!Evan Mullins
 
Dojo - from web page to web apps
Dojo - from web page to web appsDojo - from web page to web apps
Dojo - from web page to web appsyoavrubin
 
Android App Development 06 : Network &amp; Web Services
Android App Development 06 : Network &amp; Web ServicesAndroid App Development 06 : Network &amp; Web Services
Android App Development 06 : Network &amp; Web ServicesAnuchit Chalothorn
 
IRJET- Rest API for E-Commerce Site
IRJET- Rest API for E-Commerce SiteIRJET- Rest API for E-Commerce Site
IRJET- Rest API for E-Commerce SiteIRJET Journal
 
Web Service and Mobile Integrated Day I
Web Service and Mobile Integrated Day IWeb Service and Mobile Integrated Day I
Web Service and Mobile Integrated Day IAnuchit Chalothorn
 

Similar to Switch to Backend 2023 (20)

Cqrs api
Cqrs apiCqrs api
Cqrs api
 
Document Databases & RavenDB
Document Databases & RavenDBDocument Databases & RavenDB
Document Databases & RavenDB
 
Using Ajax In Domino Web Applications
Using Ajax In Domino Web ApplicationsUsing Ajax In Domino Web Applications
Using Ajax In Domino Web Applications
 
Getting started with node JS
Getting started with node JSGetting started with node JS
Getting started with node JS
 
RESTful applications: The why and how by Maikel Mardjan
RESTful applications: The why and how by Maikel MardjanRESTful applications: The why and how by Maikel Mardjan
RESTful applications: The why and how by Maikel Mardjan
 
Cqrs api v2
Cqrs api v2Cqrs api v2
Cqrs api v2
 
Beginning MEAN Stack
Beginning MEAN StackBeginning MEAN Stack
Beginning MEAN Stack
 
GDSC Backend Bootcamp.pptx
GDSC Backend Bootcamp.pptxGDSC Backend Bootcamp.pptx
GDSC Backend Bootcamp.pptx
 
Networked APIs with swift
Networked APIs with swiftNetworked APIs with swift
Networked APIs with swift
 
Introduction to Web Architecture
Introduction to Web ArchitectureIntroduction to Web Architecture
Introduction to Web Architecture
 
JavaOne 2009 - TS-5276 - RESTful Protocol Buffers
JavaOne 2009 - TS-5276 - RESTful  Protocol BuffersJavaOne 2009 - TS-5276 - RESTful  Protocol Buffers
JavaOne 2009 - TS-5276 - RESTful Protocol Buffers
 
Simple REST with Dropwizard
Simple REST with DropwizardSimple REST with Dropwizard
Simple REST with Dropwizard
 
WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!
WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!
WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!
 
Day01 api
Day01   apiDay01   api
Day01 api
 
Dojo - from web page to web apps
Dojo - from web page to web appsDojo - from web page to web apps
Dojo - from web page to web apps
 
Android App Development 06 : Network &amp; Web Services
Android App Development 06 : Network &amp; Web ServicesAndroid App Development 06 : Network &amp; Web Services
Android App Development 06 : Network &amp; Web Services
 
Ajax
AjaxAjax
Ajax
 
My Saminar On Php
My Saminar On PhpMy Saminar On Php
My Saminar On Php
 
IRJET- Rest API for E-Commerce Site
IRJET- Rest API for E-Commerce SiteIRJET- Rest API for E-Commerce Site
IRJET- Rest API for E-Commerce Site
 
Web Service and Mobile Integrated Day I
Web Service and Mobile Integrated Day IWeb Service and Mobile Integrated Day I
Web Service and Mobile Integrated Day I
 

More from Google Developer Students Club NIT Silchar (9)

Switch to Svelte | GDSC NIT Silchar | Speaker Session | SvelteKit
Switch to Svelte | GDSC NIT Silchar | Speaker Session | SvelteKitSwitch to Svelte | GDSC NIT Silchar | Speaker Session | SvelteKit
Switch to Svelte | GDSC NIT Silchar | Speaker Session | SvelteKit
 
Switch to Backend 2023 | Day 2 Part 1
Switch to Backend 2023 | Day 2 Part 1Switch to Backend 2023 | Day 2 Part 1
Switch to Backend 2023 | Day 2 Part 1
 
Switch to Backend 2023 | Day 1 Part 2
Switch to Backend 2023 | Day 1 Part 2Switch to Backend 2023 | Day 1 Part 2
Switch to Backend 2023 | Day 1 Part 2
 
Flutter Festival - Intro Session
Flutter Festival - Intro SessionFlutter Festival - Intro Session
Flutter Festival - Intro Session
 
Roadmap to Development
Roadmap to DevelopmentRoadmap to Development
Roadmap to Development
 
Android Study Jams - Info Session
Android Study Jams - Info SessionAndroid Study Jams - Info Session
Android Study Jams - Info Session
 
30 days of cloud: Info session
30 days of cloud: Info session30 days of cloud: Info session
30 days of cloud: Info session
 
Flutter Bootcamp
Flutter BootcampFlutter Bootcamp
Flutter Bootcamp
 
Intro to Git & GitHub
Intro to Git & GitHubIntro to Git & GitHub
Intro to Git & GitHub
 

Recently uploaded

ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxsqpmdrvczh
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 

Recently uploaded (20)

ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptx
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 

Switch to Backend 2023

  • 1. Switch to Backend Getting started with backend development By Siddharta Shankar Paul Core Member, GDSC
  • 2. Switch to backend Day 1 Topic structure What is Fullstack Development? Frontend vs Backend Node.js & NPM How web works What is backend? HTTP requests Static vs Dynamic Websites
  • 3. Full stack development is the end-to-end development of applications. It includes both the front end and back end of an application. The front end is usually accessed by a client, and the back end forms the core of the application where all the business logic is applied. What is Fullstack Development ? Full Stack = FrontEnd + BackEnd
  • 4.
  • 5. "Backend" refers to any part of a website or software program that users do not see. Blah blah blah... What is Backend ?
  • 6.
  • 7. "Backend" refers to any part of a website or software program that users do not see. Blah blah blah... What is Backend ?
  • 8. How web works Payload (Request) DB Query Response Data Business Logic Resides here HTM L CSS Javascript
  • 9.
  • 10. What is the need to Switch to Backend ???
  • 11. ●HTTP (Hyper Text Transfer Protocol) ●HTTPS (HTTP, but its Secure) ●TCP (Transmission Control Protocol) ●IP (Internet Protocol) ●API (Application Programming Interface) Afraid of Buzzwords?
  • 13. Node. js is a single-threaded, open-source, cross-platform runtime environment for building fast and scalable server-side and networking applications. It runs on the V8 JavaScript runtime engine, and it uses event- driven, non-blocking I/O architecture, which makes it efficient and suitable for real-time applications. ● What is node JS in simple words? ● Is node JS for frontend or backend? ● What is Benefits of NodeJs?
  • 14. What is REST API??
  • 15. APIs are mechanisms that enable two software components to communicate with each other using a set of definitions and protocols. 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. REST stands for representational state transfer The primary goal of API is to standardize data exchange between web services. Depending on the type of API, the choice of protocol changes. On the other hand, REST API is an architectural style for building web services that interact via an HTTP protocol.
  • 16.
  • 17. When a client makes a request via a RESTful API, it transfers the information/representation of the request or response from user to Webservice or vice versa through HTTP format. REST APIs faster and more lightweight, with increased scalability—perfect for Internet of Things (IoT) and mobile app development. Request Method: The request action should be indicated by the HTTP request method. The most common methods include GET, POST, PUT, and DELETE.· ● GET retrieves resources. (From the above example: Get the menu list or food) ● POST submits new data to the server.(Order new food item to your order list) ● PUT updates existing data.(Changing from one variety to another like veg to non-veg) ● DELETE removes data.(Cancelling an item if it takes more time) Response Method: We can develop REST API, programming them to send the response according to the input header of the HTTP request. There is a Media-Type attribute in the header which can be used in such cases and the response can be sent accordingly. REST API can return both XML or JSON as response message, depending upon the Media-Type attribute in the HTTP request. REST API must always return an appropriate Status code to the user/client so that the user/client can know the actual issue and process accordingly.
  • 18. HTTP Status Code Description: ● 1xx: Informational: It represents the request that has been received, and it is in the continuing process. ● 2xx: Success: Success represents the HTTP Server response that the server has successfully received and understood the request. ● 3xx: Redirection: It indicates that further action must be taken to fulfil the request. ● 4xx: Client Error: It represents an error when the request has incorrect syntax or cannot complete the request. ● 5xx: Server Error: The server has failed to fulfil a valid request.
  • 21. How does express help you? ● Less code ● Promotes a better project structure ● Widely used. Has lots of plugins
  • 23. Your machine is the localhost Hostname: localhost IP Address: 127.0.0.1
  • 24.
  • 26. import express from "express"; const app = express(); app.get("/", (req, res)=>{ return res.send("Home"); } app.listen(5000, ()=>{ console.log("Listening on PORT 5000"); }); Get the default export from the express package Create an Express application Set up your routes Set the server up to listen To HTTP requests
  • 27. import fetch from 'node-fetch'; app.get("/post/rand", (req, res)=>{ const response = await fetch('https://dummyjson.com/posts'); const posts = await response.json(); const rand = Math.random() * posts.length; for (let i = posts.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); const temp = posts[i]; posts[i] = posts[j]; posts[j] = temp; } const randomPosts = posts.subarray(0, rand); return res.json({posts: randomPosts); });
  • 28. . ├── src/ │ └── routers/ │ └── hello.js └── server.js Structure your code
  • 30. Specificity Be more Specific As you go up app.get("/:hello/world", (_req, res)=>{ res.send('YO MAMA!'); }); app.get("/:hello/", (_req, res)=>{ res.send('SO!'); }); app.get("/", (_req, res)=>{ res.send('FAT!'); });
  • 31. . ├── src/ │ ├── routers/ │ │ ├── hello.js │ │ ├── post.js │ │ └── index.js │ └── controllers/ │ ├── hello/ │ │ └── get.js │ ├── post/ │ │ ├── get.js │ │ └── post.js │ └── index.js └── server.js Structure your code Again!
  • 32. Extras You don’t need them now, but you will
  • 33. Middlewares Router Middleware 1 Middleware 2 {could be more} Controller
  • 34. Cookies and Sessions ● Cookies are used to store data on the client side. Who am I speaking to? ● Sessions are used to store data on the server side.
  • 36. Switch to Backend Pratik Majumdar @codadept MongoDB & Prisma
  • 37. Recap
  • 38. Today’s Agenda Database Prisma ORM vs ODM Error Handling SQL vs NoSQL MongoDB CRUD
  • 39. ● Systematic/organized collection of data ● Easily accessible and manageable ● SQL vs NoSQL Database MS Excel?
  • 40. • SQL ○ Relational Database ○ Rows and columns ○ Pre-defined schema ○ Eg. MySQL, PostgreSQL SQL vs NoSQL Schema vs Schema-less • NoSQL ○ Non-Relational Database ○ Documents ○ Dynamic schema ○ Eg. MongoDB, Redis
  • 41. SELECT * FROM classroom WHERE id=1; Need for ORM/ODM? MySQL MongoDB db.classroom.find({id: 1})
  • 42. SELECT C.CUSTOMER_NAME, C.CITY, C.GRADE, S.NAME AS "SALESMAN", O.ORDER_NO, O.ORDER_DATE, O.PURCHASE_AMT FROM CUSTOMER C RIGHT JOIN SALESMAN S ON S.SALESMAN_ID = C.SALESMAN_ID LEFT JOIN ORDERS O ON O.CUSTOMER_ID = C.CUSTOMER_ID WHERE O.PURCHASE_AMT >= 2000 AND C.GRADE IS NOT NULL; More complex query
  • 43. We don’t write SQL or MongoDB Query Language in our project to access DB. We use such mappers ORM ● Object Relational Mapping ● Perform CRUD in Relational DB ODM ● Object Document Mapping ● Perform CRUD in Non-Relational DB ORM vs ODM JS <-> Mapper <-> DB
  • 44. ● Dynamic schema ● Here instead of tables as in SQL DBs we have collections MongoDB NoSQL Database user { “username”: “codadept”, “scholarId”: 2012005 } user { “firstName”: “Pratik”, “scholarId”: 2012005 }
  • 45. Stores data in BSON - Binary Encoded JSON MongoDB Datatype Has more data types than JSON JSON String, Boolean, Number, Array, Object, null BSON String, Boolean, Number (Integer, Float, Long, Decimal128...), Array, null, Date, BinData
  • 46. MongoDB ObjectId Each document in the collection has _id field which acts as the unique identifier for that document.
  • 47. MongoDB Query using the mongodb CLI using my_database; db.createCollection(“user”) db.user.insert({“id”: 1, “name”: “Pratik”, “username”: “codadept”}) db.user.find()
  • 48. Prisma ORM/ODM Prisma is a auto-generated query-builder for Node.js Can be used both as ORM or ODM based on the database we use Other alternatives For SQL - sequelize For MongoDB - mongoose
  • 49. Prisma Why? ● Think as objects and classes instead of complex queries ● Type-safe and auto-completion ● Easy to change databases
  • 50. Prisma Schema file prisma/schema.prisma datasource db { provider = "mongodb" url = env("DATABASE_URL") } generator client { provider = "prisma-client-js" } model Post { id String @id @default(auto()) @map("_id") @db.ObjectId title String content String? published Boolean @default(false) author User? @relation(fields: [authorId], references: [id]) authorId String @db.ObjectId } model User { id String @id @default(auto()) @map("_id") @db.ObjectId email String @unique name String? posts Post[] }
  • 51. Prisma Components ● Data source: Specifies your database connection (via an environment variable) ● Generator: Indicates that you want to generate Prisma Client ● Data model: Defines your application models
  • 52. Prisma Data model ● Represent a table in relational databases or a collection in MongoDB ● Provide the foundation for the queries in the Prisma Client API
  • 53. Prisma Accessing your DB with @prisma/client npm install @prisma/client This invokes the prisma generate command which which reads your Prisma schema and generates the Prisma Client code.
  • 54. Prisma Querying import { PrismaClient } from '@prisma/client' const prisma = new PrismaClient() // Run inside `async` function const allUsers = await prisma.user.findMany()
  • 55. Let’s code // Run inside `async` function const user = await prisma.user.create({ data: { name: 'Alice', email: 'alice@prisma.io', posts: { create: { title: 'Join us for Prisma Day 2020' }, }, }, })