CHAPTER SIX
CHAPTER SIX
Ch. 6
RESTFULL API
1
API
• The API (Application Programming Interface) is a set
communicate.
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..
•
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' });
}
// Default route
app.get('/', (req, res) => {
res.send('Welcome to my User Registration and Login API!');
});