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 [Link]() 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/[Link]';
• import EmpRouter from './routersf/[Link]';
• const app = express();
•
[Link]();
•
[Link]([Link]())
• [Link]([Link]({extended:true}));
• [Link]('/api/seed/',CreateRouter)
• [Link]('/api/employe/',EmpRouter)
•
[Link]([Link].MONGODB_URL).then(()=>{
• [Link]("connected to db");
• }).catch((err)=>{
• [Link]([Link]);
• })
•
const port = [Link] || 5000;
•
[Link](port,()=>{
• [Link](`server is running on port [Link]
•
})
Creating Model Schema
• import mongoose from "mongoose";
• const CreateSchema = [Link]({
• 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 = [Link]("System" , CreateSchema )
• export default System;
inserting Data into
Collection
• [Link]('/' , async(req ,
res)=>{
• await [Link]({})
• const kudar = await
[Link]([Link])
• [Link]({kudar});
•
})
•
export default SeedRouter;
Example of Read Data
API
• // reading data
• [Link]("/all", async(req,
res)=>{
• const sodar = await
[Link]()
• [Link](sodar);
• })
Example of POST Data
•
[Link]("/add", async(req,
res)=>{
• const kudar = new Shaqaale ({
• empname: [Link],
• mothername: [Link],
• tell : [Link],
• adress : [Link]
• });
• await [Link]()
• [Link]("save success");
• })
Example of PUT (Update)
• //update
• [Link]("/:id", async(req, res)=>{
• [Link]([Link]);
• [Link]({_id:[Link]},{
• $set:{
• empname:[Link],
• mothername:[Link],
• tell:[Link],
• adress: [Link]
• }
• })
• .then(result=>{
• [Link](200).json({
• update:result
• })
• })
• .catch(err=>{
• [Link](err);
• [Link](500).json({
• Error:err
• })
• })
• })
Example of Delete
• //delete
• [Link]("/:id", async(req, res)=>{
•
[Link]({_id:[Link]}).then(result
=>{
• [Link](200).json({
• message:"data deleted",
• result:result
• })
• })
• .catch(err=>{
• [Link](500).json({
• Error:err
• })
• })
• })
Building a Secure User Registration
and Login API with
[Link] ,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
[Link]('mongodb://localhost:27017/mydatabase');
.then(() => {
[Link]('Connected to MongoDB');
})
.catch((error) => {
[Link]('Error connecting to MongoDB:', error);
});
Continue…
// Define a schema for the User collection
const userSchema = new
[Link]({
username: String,
email: String,
password: String
});
// Create a User model based on the
schema
const User = [Link]('User',
userSchema);
•
Continue…
// Middleware to parse JSON bodies
[Link]([Link]());
// Middleware for JWT validation
const verifyToken = (req, res, next) => {
const token = [Link]['authorization'];
if (!token) {
return [Link](401).json({ error: 'Unauthorized' });
}
[Link](token, 'secret', (err, decoded) => {
if (err) {
return [Link](401).json({ error: 'Unauthorized' });
}
[Link] = decoded;
next();
});
};
Continue…
• // Route to register a new user
[Link]('/api/register', async (req, res) => {
try {
// Check if the email already exists
const existingUser = await [Link]({ email: [Link] });
if (existingUser) {
return [Link](400).json({ error: 'Email already exists' });
}
// Hash the password
const hashedPassword = await [Link]([Link], 10);
// Create a new user
const newUser = new User({
username: [Link],
email: [Link],
password: hashedPassword
});
await [Link]();
[Link](201).json({ message: 'User registered successfully' });
} catch (error) {
[Link](500).json({ error: 'Internal server error' });
}
});
Continue..
• // Route to authenticate and log in a user
[Link]('/api/login', async (req, res) => {
try {
// Check if the email exists
const user = await [Link]({ email: [Link] });
if (!user) {
return [Link](401).json({ error: 'Invalid credentials' });
}
// Compare passwords
const passwordMatch = await [Link]([Link], [Link]);
if (!passwordMatch) {
return [Link](401).json({ error: 'Invalid credentials' });
}
// Generate JWT token
const token = [Link]({ email: [Link] }, 'secret');
[Link](200).json({ token });
} catch (error) {
[Link](500).json({ error: 'Internal server error' });
}
});
Continue..
• // Protected route to get user details
[Link]('/api/user', verifyToken, async (req, res) => {
try {
// Fetch user details using decoded token
const user = await [Link]({ email: [Link] });
if (!user) {
return [Link](404).json({ error: 'User not found' });
}
[Link](200).json({ username: [Link], email: [Link] });
} catch (error) {
[Link](500).json({ error: 'Internal server error' });
}
});
// Default route
[Link]('/', (req, res) => {
[Link]('Welcome to my User Registration and Login API!');
});
// Start the server
[Link](PORT, () => {
[Link](`Server is running on port ${PORT}`);
});
END
27