Updating and Deleting Data
Swipe to show menu
In addition to creating data, APIs often need to update and delete existing records.
To update data, you can use PUT or PATCH requests.
app.put('/users/:id', (req, res) => {
const id = Number(req.params.id);
const updatedData = req.body;
const user = users.find(u => u.id === id);
if (user) {
user.name = updatedData.name;
res.json(user);
} else {
res.send('User not found');
}
});
To delete data, you use a DELETE request:
app.delete('/users/:id', (req, res) => {
const id = Number(req.params.id);
users = users.filter(u => u.id !== id);
res.send('User deleted');
});
Examples:
PUT '/users/1': updates user with id 1;DELETE '/users/1': deletes user with id 1.
These operations allow you to modify and remove data in your application.
Everything was clear?
Thanks for your feedback!
Section 1. Chapter 14
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Section 1. Chapter 14