Introduction to POSTMAN for REST API's
HTML-код
- Опубликовано: 10 сен 2024
- Hey Everyone, In this video, we will build our own REST API using Node and Express frameworks.
Fake Data API: www.mockaroo.com/
► Complete Full Stack Web Developer RoadMap 2023: • Complete Full Stack We...
► Master NodeJS Playlist: • Master NodeJS
Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. It allows developers to run JavaScript on the server side, creating server-side applications with JavaScript.
► My Website: www.piyushgarg...
My Gears
► My Girlfriend: amzn.to/3WD6FRp
► Apple MacBook Laptop: amzn.to/3WBJgQn
► Anker USB Hub: amzn.to/3GhZSr0
► Blue Yeti Microphone: amzn.to/3YKZ9FT
► External 27” Monitor: amzn.to/3Vp3xaO
► Logitech MK295 Wireless Keyboard and Mouse: amzn.to/3DuL1bB
► Seagate Expansion 1TB External HDD: amzn.to/3QMm5Q8
► Tripod: amzn.to/3S4OwK4
► Ring Light: amzn.to/3YLf8DR
Disclaimer: All the links above are affiliate links.
Social Links
► Twitter - / piyushgarg_dev
► LinkedIn - / piyushgarg195
Video Titles
What is NodeJS?
What is REST API?
How to design restful API?
REST API Best Practices
Tags
#nodejs #javascript #expressjs #mernstack #developer #api #https #server #javascriptinhindi #webdevelopment #webapp #realtimeapp #serverside #nonblockingio #tech
The way you simplify things 🔥>>>>
"Making difficult concepts easy" is the quality that differentiats Piyush from other trainers
Hey Piyush
I really liked your Node.js backend tutorials! You have explained very clearly and step-by-step. Now I can confidently use Node.js in my projects. I have truly become a big fan of your hard work and dedication. Thanks a lot for sharing your knowledge
You are simplifying many things and making them freely accessible to a lot of people. No amount of gratitude can truly suffice. 💙🙏🙌
Have you made Piyush Garg's Node.js notes? I've been through the whole playlist, but my notebook is misplaced. Got an interview in two days, and I'm a bit stuck. Any chance you could share your notes?
patch method:
const id = Number(req.params.id);
const body = req.body;
const user = users.find((user) => user.id === id)
const updatedUser = { ...user, ...body };
updatedUser.id=id;
users[id-1]=updatedUser
fs.writeFile('MOCK_DATA.json', JSON.stringify(users), (err, data) => {
return res.json({ status: "Success", updatedUser })})
purpose of this line?
updatedUser.id=id;
@@siddharthjaiswal9942 This line ensures that the id of the updated user matches the id extracted from the request URL.
no use
users[id-1]=updatedUser
meaning of this line?
@@shubhambera2942 we have to do it because we use array here indexing start with 0 if we give id= 1001 in header its work as a array index so users[1001] add new user not updating the data. you can console log this to check. ex: user[1000] will give you //the 999th user's data. he use spread operator to add two array of object into a single object and spread operator overwritten the values if two keys in the passing objects are same. so user's data will be overwritten by the body's data and store into new object updatedUser.
watched some videos from other youtubers on backend when i was starting was not able to understand from them their teaching was difficult to understand but you made it seem so easy thanks for this playlist i will watch all the videos 👌👌
u'r awosome..........
most underrated play list
This is called quality content.
teach everything what you can
😭
Another level simplification 🧡
Glad you think so! 🚀
Also you can use thunder client instead of postman. It is an extension of vs code
Bro you are best at teaching .. Continue helping us forever
both assignments completed
finally learnt how to use splice method in array.
First of all I must say awesome teaching.I found you first on Codedman in Redux Toolkit Module then I search in youtube.I completed Codedamn basic nodejs course but things were not clear than I continue your nodejs series.Thanks a lot for this.
I Tried Patch Api but index value was undefined then what should i do
Hey, First of all, Thanks a lot.
Second: I didn't got your doubt, please mention more details
Have you made Piyush Garg's Node.js notes? I've been through the whole playlist & have made my notes but my notebook is misplaced. Got an interview in two days, and I'm a bit stuck. Any chance you could share your notes?
Do you need them now?@@varunupadhyay2488
@@varunupadhyay2488 How was your interview?
If anyone is facing difficulties in writing the updated object on json file with patch method, then try overwriting the json file manually and change the file to overwrite mode then we can update or write on the file from fs.writeFile method.
Thanks bhaiya. You are a great teacher.
Amazingly explained. Thank you 💙
DELETE request:
app.delete("/api/users/:id", (req, res) => {
//Get the id of the user
const id = Number(req.params.id);
//Find out the index of the user with above id from the array "users"
const userIdx = users.findIndex((user)=> user.id === id);
//Get the deleted user object using splice. Mind we need to get the object and not array as returned by splice method, so '[0]' satisfies this requirement. The resulting object is just for the sake of displaying, you may neglect storing it if you don't want to display.
const delUser = users.splice(userIdx, 1)[0];
//Write the changes into the json file.
fs.writeFile("./MOCK_DATA.json", JSON.stringify(users), (err, data) => {
return res.json({ status: "success", delUser });
});
})
thank u for code!! It
helps
hey@@pavant4391can you tell me how [0] helps solve this object problem???
@@madmax180users.splice contains an array with one object... So that's why we are using [0]
After this there must be a change in POST as well, as new user being created will have glitch in ID, if any middle element is deleted from array.
as POST included users.length + 1 as new userID
Amazing Video.... Great Explaination... Thank you soo much
You are most welcome 😇
for anybody whose program is not creating new entry in user.json,
1.) Try to console.log() the users after pushing the new entry.
2.) If you see the new entry there, and the code doesn't have syntax mistake then the problem is directory path of user.json
copy this code and paste it in the program,
const file_path = __dirname + '/users.json';
put this file_path in fs.writefile and try again.
for me only the new ids are getting added in the data and not the entire user info ...anything you could suggest?
@@shrutipawar4794 did you tried pasting the code in chatgpt?
@@shrutipawar4794 had the same problem make sure selecting body in postman while filling the data
Thanku bahut badiya explanation I have ever seen
You are the greatest of all time, Thank you so much for sharing this gold!
Awesome teaching style
Thanks 😇
@@piyushgargdev Please MongoDB bhi cover kar dena brother.
Aaj aache se Rest API samajh me aayi meko.Thank you bhaiya .
You gained a subscriber, keep up the nice work. :)
"Node Js made easy" perfect name for this series.
solute for great mind❤❤❤❤
homework done , this is best series of nodeJs
Great explanation , thank you
To all the people installing postman on their system, Now Postman is also available as a extension in vscode, So i think their is no need to switch a tab and you are good to go:)
Better use thunder client extension
@@deshbhaktaadmi6580 yeahh, another competitor of postman👍
Superb content 🎉
amaazinnggglyy explained oofe...💯💥
thank you sir best teaching
love you soo much soo owesome explanation always😍
awesome bhaiya thank you got it all
Bhaiya aap esme file write kr rhe ho wo v 1000 + new data esse server pr jada burden nhi jaega
In place of File write again again can we use apendfile operation to reduce the burden on server if yes so please reply 🙏
Step 1 File write with 1000 users
Step 2 Append new user so first copy 1000 users and add new one also with deleting 1000 users from file
Step 3 rewrite the file with 1001 users
Thanks a lottt
lost of love from nepal . you deserve more subscribe . you content is too much good
lots* 😅
❤
Thunder client, a vs code extension is the best alternative to Postman.
when I am using post method an error occured (cannot post/api/users)
name of vs code extension for node js??
Sir post request problem kya aaraha he ki postman par data dikha Raha hai lekin json file mai data fetch nahi ho raha hai please help
Abb lgg rha hai..backend padh rha hu👌🥲
Good One
Kindly make a playlist of api
hi piyush , my post thing is not working , on the url i am getting can not get /api/user, could you please help
push k andr ...body kyun? dots k bina bhi body likh saqty naaa?
Because id ko khudse dal raha hai hum
Without dot kroga toh bi ho jayega push but id nahi aayega
So to give id hum spread kr rha hai apna object ko
so we used fs module to write to the file, but did not use it to read the file.. why?
Thanks bro
super
Which theme you are using ?
plz sir can you say your vs code theme name. btw, very good video. all not this one.
🔥🔥
guru jiiiiiiii
12:35 I got the issue beforehand😅 so removed +1
TypeError: Cannot read properties of undefined (reading 'json')
I am getting this error while returning the res.json({status:"success"})
instead of res.json({status:"success"}) use res.send({status:"success"})
not able to delete using fs.unlink but some error
sir ly ❤
after adding multiple users, the mock users.json file is not getting updated. Is this supposed to happen or is my server failing? I can only see the first entry and after that it shows on postman but not in my mock json file
// Do This 👍👍
app.post('/api/users', (req, res) => {
const body = req.body;
users.push({...body, id: users.length + 1})
fs.writeFile('./MOCK_DATA.json', JSON.stringify(users), (err, data) => {
return res.json({status: "Success", id: users.length})
})
})
@@Aitool-r3q Video mai same code haina ?
for me data of new user is getting updated on localhost:8000/api/users but not in MOCK_DATA.json file in vs code . pls help.
fs.writeFile("./MOCK_DATA.json", JSON.stringify(users), (err, data) => {
return res.json({ status: "success" });
});
Have you made Piyush Garg's Node.js notes? I've been through the whole playlist & have made my notes but my notebook is misplaced. Got an interview in two days, and I'm a bit stuck. Any chance you could share your notes?
please make a crash course on mern stack
👌👍👍👌👌👍
ThunderClient use karne se aur aasan hota
kos ->king of simplifier
doing POST i got error 404 not found
Your video was very helpful!
But I've got problem with the patch request I am making. The data I want to update is returned as it is. Its not getting updated. I am giving my code for reference.
app.patch('/api/users/:id',(req, res) => {
const id = Number (req.params.id)
let user = users.find (user => user.id === id)
const idx = users.indexOf (user);
const newObj = Object.assign (user , req.body)
users[idx] = newObj;
fs.writeFile ('./MOCK_DATA.json',JSON.stringify(users) , (err,data) => {
return res.json ({
status: "success",
users: user
})
})
})
I am passing raw data in body in postman such as {"job_title": "Data Analyst"} but no updation is happening. Can anyone please help?
I am unable to go forward in the playlist since my doubt remains uncleared. Thought I would watch this playlist completely... Thankyou for uplaoding good videos.
@@khushijain6993 same problem i have invested 2 hrs, but still not resolved. Did you get it resolved please tell
app.use(express.json()); we have to use this middleware finally it ran 😭
@@itsd2388 thankyou for telling 🥲
sur voice bahut kam ati hai apki
Mere ko to a rhi hai ,Yes he has High pitch
const id = Number(req.params.id);
let user = users.find((user) => user.id === id);
if (!user) {
return res.status(404).json({
status: "fail"
})
}
console.log(user);
const ind = users.indexOf(user);
const body = req.body
console.log(body);
Object.assign(user, body );
console.log(user);
users[ind]=user;
fs.writeFile("./MOCK_DATA.json",JSON.stringify(users),(err,data)=>{
return res.json({status: "succuess",data: { user}})
})
it s not updating for patch i have tried everyway
delete method:
.delete("/api/users/:id", (req, res) => {
const id = Number(req.params.id);
const index = users.findIndex((index) => index.id === id);
if (index !== -1) {
users.splice(index, 1);
}
return res.json({status: "Successfully Removed"});
})
alert('chatgpt ????????????????)
## The same code below did not work before I shut down my laptop; however, it worked after I did so. Before that, I was wondering what was wrong with it ##
app.patch("/api/users",(req, res) => {
// Edit user with id
const body = req.body;
console.log("Body:", body);
const editedUser = users.map((user) =>
user.id == body.id
? {
...user,
first_name: body.first_name,
last_name: body.last_name,
email: body.email,
job_title: body.job_title,
}
: user
);
fs.writeFile(
"./MOCK_DATA.json",
JSON.stringify(editedUser),
(error, data) => {
if (error) {
console.log("Error:", error);
return res.json({ status: "Error" });
} else {
return res.json({ status: "Update" });
}
}
);
});)
🫡🫡🫡🇮🇳❤️
Here is a Solution for the Patch request
Hope it Helps
app.route("/api/users/:id")
.patch((req, res) => {
// getId stores the Id from the given Parameters in the URL.
const getId = Number(req.params.id);
// body stores the body in which we've to make changes.
const body = req.body;
// Finding the user Id from the user array.
const userIndex = users.findIndex((user) => user.id === getId);
// If we found a user with its Id then gotUser stores that object.
const gotUser = users[userIndex];
// Here gotUser has the user Object and body has the changes we have to made.
const updatedUser = { ...gotUser, ...body};
// After Merging them, Update the users Array.
users[userIndex] = updatedUser;
// Lastly, write the changes into the json file.
fs.writeFile('./users_mock_data.json', JSON.stringify(users), (err, data) => {
return res.json({ status: "Success", updatedUser});
})
})
Thanks!, this solution is very readable and clear
this can be done using map easily,
//you should update this logic:
.patch((req, res) => {
const id = Number(req.params.id);
const { last_name } = req.body;
const newUsers = users.map((user) => {
if (user.id === id) {
return { ...user, last_name };
} else {
return user;
}
});
fs.writeFile('./MOCK_DATA.json', JSON.stringify(newUsers), (err, data) => {
return res.json({ status: 'successfully edited user', id });
});
})
but time complexity is very high if we are using map function@@hidev4615
@@hidev4615 will it update the users array??
.delete((req,res)=>{
//TODO: Delete the user with id
const id = Number(req.params.id)
if(id!=-1 && users.length>=id){
users.splice(id-1,1);
fs.writeFile("./MOCK_DATA.json",JSON.stringify(users),(err,data)=>{
if(!err){
return res.status(200).json({success:"User delete"});
}else{
res.status(500).json({error:"Failed to delete user"});
}
});
}else{
return res.status(404).json({error:"User not found"});
}
});
app.delete("/api/users/:id", (req, res) => {
let { id } = req.params;
//let's delete our user
users = users.filter((user) => user.id !== parseInt(id));
//converting users into JSON compatible format
users = JSON.stringify(users);
//writing into users.json file
fs.writeFile("./user_data/users.json", users, (error) => {
if (error) {
return res.status(500).json({ error: "delete operation failed!" });
}
return res.json({ success: "user_details deleted successfully!" });
});
});