0
0
Expressframework~5 mins

PUT and PATCH route handling in Express

Choose your learning style9 modes available
Introduction

PUT and PATCH let your server update data sent by users. They help keep information fresh and correct.

When you want to replace an entire item with new data.
When you want to change only some details of an item.
When building APIs that let users edit their profiles or settings.
When updating a product's information in an online store.
When fixing or correcting data without deleting it.
Syntax
Express
app.put('/path/:id', (req, res) => {
  // Replace entire item with req.body
});

app.patch('/path/:id', (req, res) => {
  // Update parts of item with req.body
});

PUT expects the full new data for the item.

PATCH expects only the fields to change.

Examples
Use PUT to replace the entire user info.
Express
app.put('/users/:id', (req, res) => {
  // Replace whole user data
});
Use PATCH to update only some user details.
Express
app.patch('/users/:id', (req, res) => {
  // Update some user fields
});
PUT replaces the whole product data.
Express
app.put('/products/:id', (req, res) => {
  // Replace product info
});
PATCH changes just the price or other parts.
Express
app.patch('/products/:id', (req, res) => {
  // Change product price only
});
Sample Program

This example shows a simple server with users data. PUT replaces the whole user info except the id. PATCH changes only the fields sent in the request.

Express
import express from 'express';
const app = express();
app.use(express.json());

let users = [
  { id: '1', name: 'Alice', age: 25 },
  { id: '2', name: 'Bob', age: 30 }
];

// PUT replaces entire user
app.put('/users/:id', (req, res) => {
  const { id } = req.params;
  const index = users.findIndex(u => u.id === id);
  if (index === -1) {
    return res.status(404).send('User not found');
  }
  // Replace whole user data, keep id same
  users[index] = { id, ...req.body };
  res.send(users[index]);
});

// PATCH updates parts of user
app.patch('/users/:id', (req, res) => {
  const { id } = req.params;
  const user = users.find(u => u.id === id);
  if (!user) {
    return res.status(404).send('User not found');
  }
  // Update only given fields
  Object.assign(user, req.body);
  res.send(user);
});

app.listen(3000, () => console.log('Server running on port 3000'));
OutputSuccess
Important Notes

PUT is like replacing a whole book page; PATCH is like editing a few words.

Always check if the item exists before updating.

Use express.json() middleware to read JSON data from requests.

Summary

PUT replaces the entire resource with new data.

PATCH updates only specific fields of a resource.

Both are used to update data on the server in APIs.