Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Updating and Deleting Data | Section
Building APIs with Express.js

bookUpdating 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?

How can we improve it?

Thanks for your feedback!

Section 1. Chapter 14

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Section 1. Chapter 14
some-alt