0% found this document useful (0 votes)
15 views

CHAPTER SIX

The document provides an overview of RESTful APIs, explaining the concept of APIs, the REST architecture, and its benefits such as separation of client and server, ease of use, and scalability. It also covers HTTP methods commonly used in REST, introduces Axios for making API requests, and discusses CORS for handling cross-origin requests. Additionally, it includes examples of CRUD operations using Express.js and MongoDB, along with user registration and login functionality using JWT for authentication.

Uploaded by

hananfajuge
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

CHAPTER SIX

The document provides an overview of RESTful APIs, explaining the concept of APIs, the REST architecture, and its benefits such as separation of client and server, ease of use, and scalability. It also covers HTTP methods commonly used in REST, introduces Axios for making API requests, and discusses CORS for handling cross-origin requests. Additionally, it includes examples of CRUD operations using Express.js and MongoDB, along with user registration and login functionality using JWT for authentication.

Uploaded by

hananfajuge
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 27

JUST UNIVERSITY

Ch. 6
RESTFULL API

1
API
• The API (Application Programming Interface) is a set

of commands, functions, or protocols that act as an

intermediary that enables two applications to

communicate.

• An application programming interface is a way for

two or more computer programs to communicate

with each other. It is a type of software interface,


Concept of API
• Whenever you visit a restaurant, the waiter helps you
place your order. After taking your order, the waiter
asks the chef to cook the dish you’d like. When the
meal is ready, the waiter brings it to you. A waiter
serves as an intermediary between the chef and the
customer in this situation. The waiter receives a
request (order) from the customer(client), conveys the
request to the chef (server), and fetches the prepared
dish (response).
REST
• REST: REST stands for
Representational State Transfer.
Interconnected networks make up the web. A web
service is a set of open protocols and standards
used for exchanging data between client-server
applications. Web services that follow the REST
architecture are known as RESTful web services.
REST
Representational State
Transfer (REST)
• Client & Server: Client requests a resource, and the server
responds.
• Resource: Something owned by the server (e.g., data or object).
• Representation: The server sends a Representation of the
resource (e.g., JSON, XML).
• State: A resource’s state at a specific point in time.
• Transfer: The process of sending this resource's state (data)
from server to client.
• Format: Common formats for transfer include JSON, HTML,
XML, or plain text.
• Why JSON: It’s easy for both humans and machines to read.
Why REST
• Separation of Client & Server:
• Client and server are independent and can evolve
separately.
• Example: Client and server don’t depend on each
other's software choices.
• Easy to Use & Learn:
• REST is simple and straightforward for developers.
• Platform & Language Independence:
• Works across different platforms (e.g., Windows,
macOS) and programming languages.
• Adaptable to various development environments.
Flexibility &
Scalability in REST
• Scalable Architecture:
• Separation of client and server allows independent
scaling.
• Server doesn’t need to keep track of client requests.
• Flexible Data Formats:
• Not limited to one data format.
• Can use JSON or XML for data serialization.
• Network Optimization:
• HTTP caching improves network efficiency and
performance.
HTTP Methods
• Following four HTTP methods are
commonly used in REST based
architecture.
• GET − This is used to provide a read only
access to a resource.
• PUT − This is used to create a new
resource.
• DELETE − This is used to remove a
resource.
• POST − This is used to update a existing
resource or create a new resource.
Axios
• Axios is a promise-based HTTP library that lets developers
make requests to either their own or a third-party server to
fetch data.
• Axios can "get" data from a server API using a GET request.
An HTTP get request is made with the axios.get() method.
• It offers different ways of making requests such as GET ,
POST , PUT/PATCH , and DELETE
• Axios is used to communicate with the backend
and it also supports the Promise API that is
native to JS ES6.
• It is a library which is used to make requests to
an API, return data from the API, and then do
things with that data in our React application.
cors
• CORS stands for Cross-Origin Resource Sharing .
It allows us to relax the security applied to an API.
This is done by bypassing the Access-Control-Allow-
Origin headers, which specify which origins can
access the API.
• CORS is typically required to build web
applications that access APIs hosted on a different
domain or origin. You can enable CORS to allow
requests to your API from a web application hosted
on a different domain.
API Testing Tools
• Postman:
• API Testing Platform: Simplifies testing of HTTP requests
and responses.
• GUI for Testing: Provides a user-friendly interface to
validate API responses.
• API Lifecycle Support: Helps build, test, and collaborate
on APIs faster.
• Insomnia REST Client:
• Powerful API Client: Organizes, stores, and executes
RESTful API requests.
• Cross-Platform: Available for Windows, Mac, and Linux.
• Free & Fast: A free tool for testing RESTful applications.
Examples of API For CRUD
• import express from 'express'
• import mongoose from 'mongoose'
• import dotenv from 'dotenv'
• import CreateRouter from './routersf/createRouter.js';
• import EmpRouter from './routersf/empRouter.js';
• const app = express();

dotenv.config();

app.use(express.json())
• app.use(express.urlencoded({extended:true}));
• app.use('/api/seed/',CreateRouter)
• app.use('/api/employe/',EmpRouter)

mongoose.connect(process.env.MONGODB_URL).then(()=>{
• console.log("connected to db");
• }).catch((err)=>{
• console.log(err.message);
• })

const port = process.env.port || 5000;

app.listen(port,()=>{
• console.log(`server is running on port http://localhost:${port}`);

})
Creating Model Schema
• import mongoose from "mongoose";
• const CreateSchema = mongoose.Schema({
• EmployeName:{type:String , require:true},
• MotherName:{type:String , require:true},
• Telphon:{type:Number , require:true},
• Title:{type:String , require:true},
• Degree:{type:String , require:true},

},{

timetamps:true
• })

const System = mongoose.model("System" , CreateSchema )
• export default System;
inserting Data into
Collection
• SeedRouter.get('/' , async(req ,
res)=>{
• await System.removeAllListeners({})
• const kudar = await
System.insertMany(data.emp)
• res.send({kudar});

})

export default SeedRouter;
Example of Read Data
API
• // reading data
• ReadRouter.get("/all", async(req,
res)=>{
• const sodar = await
Shaqlee.find()
• res.send(sodar);
• })
Example of POST Data

ReadRouter.post("/add", async(req,
res)=>{
• const kudar = new Shaqaale ({
• empname: req.body.empname,
• mothername: req.body.mothername,
• tell : req.body.tell,
• adress : req.body.adress
• });
• await kudar.save()
• res.send("save success");
• })
Example of PUT (Update)
• //update
• ReadRouter.put("/:id", async(req, res)=>{
• console.log(req.params.id);
• Shaqlee.findByIdAndUpdate({_id:req.params.id},{
• $set:{
• empname:req.body.empname,
• mothername:req.body.mothername,
• tell:req.body.tell,
• adress: req.body.adress
• }
• })
• .then(result=>{
• res.status(200).json({
• update:result
• })
• })
• .catch(err=>{
• console.log(err);
• res.status(500).json({
• Error:err
• })
• })
• })
Example of Delete
• //delete
• ReadRouter.delete("/:id", async(req, res)=>{

Shaqlee.remove({_id:req.params.id}).then(result
=>{
• res.status(200).json({
• message:"data deleted",
• result:result
• })
• })
• .catch(err=>{
• res.status(500).json({
• Error:err
• })
• })
• })
Building a Secure User Registration
and Login API with
Express.js ,MongoDB and JWT
• Responsive user Registration and Login (SignIn &
SignUp) Form functionality using React, NodeJS,
ExpressJS and MongoDB and Bootstrap.
Continue..

// Importing required modules


const express = require('express');
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');

// Creating an Express application instance


const app = express();
const PORT = 3000;

// Connect to MongoDB database


mongoose.connect('mongodb://localhost:27017/mydatabase');
.then(() => {
console.log('Connected to MongoDB');
})
.catch((error) => {
console.error('Error connecting to MongoDB:', error);
});
Continue…
// Define a schema for the User collection
const userSchema = new
mongoose.Schema({
username: String,
email: String,
password: String
});

// Create a User model based on the


schema
const User = mongoose.model('User',
userSchema);

Continue…
// Middleware to parse JSON bodies
app.use(express.json());

// Middleware for JWT validation


const verifyToken = (req, res, next) => {
const token = req.headers['authorization'];
if (!token) {
return res.status(401).json({ error: 'Unauthorized' });
}

jwt.verify(token, 'secret', (err, decoded) => {


if (err) {
return res.status(401).json({ error: 'Unauthorized' });
}
req.user = decoded;
next();
});
};
Continue…
• // Route to register a new user
app.post('/api/register', async (req, res) => {
try {
// Check if the email already exists
const existingUser = await User.findOne({ email: req.body.email });
if (existingUser) {
return res.status(400).json({ error: 'Email already exists' });
}

// Hash the password


const hashedPassword = await bcrypt.hash(req.body.password, 10);

// Create a new user


const newUser = new User({
username: req.body.username,
email: req.body.email,
password: hashedPassword
});

await newUser.save();
res.status(201).json({ message: 'User registered successfully' });
} catch (error) {
res.status(500).json({ error: 'Internal server error' });
}
});
Continue..
• // Route to authenticate and log in a user
app.post('/api/login', async (req, res) => {
try {
// Check if the email exists
const user = await User.findOne({ email: req.body.email });
if (!user) {
return res.status(401).json({ error: 'Invalid credentials' });
}

// Compare passwords
const passwordMatch = await bcrypt.compare(req.body.password, user.password);
if (!passwordMatch) {
return res.status(401).json({ error: 'Invalid credentials' });
}

// Generate JWT token


const token = jwt.sign({ email: user.email }, 'secret');
res.status(200).json({ token });
} catch (error) {
res.status(500).json({ error: 'Internal server error' });
}
});
Continue..
• // Protected route to get user details
app.get('/api/user', verifyToken, async (req, res) => {
try {
// Fetch user details using decoded token
const user = await User.findOne({ email: req.user.email });
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
res.status(200).json({ username: user.username, email: user.email });
} catch (error) {
res.status(500).json({ error: 'Internal server error' });
}
});

// Default route
app.get('/', (req, res) => {
res.send('Welcome to my User Registration and Login API!');
});

// Start the server


app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
END
27

You might also like