PUT and PATCH Requests in Node.js
Learn how to update existing resources in a REST API using PUT and PATCH requests in Node.js.
In a REST API, we use HTTP methods to perform different operations on resources. The PUT and PATCH methods are mainly used to update existing data on the server.
For example, suppose we have a product with an ID of 1. If we want to update its name and price, we can use PUT. If we want to update only its price, we can use PATCH.
1. What Is a PUT Request?
A PUT request is used to update or replace an existing resource. The client usually sends the complete representation of the resource that it wants to save.
For example, the existing product is:
{
"id": 1,
"name": "Laptop",
"price": 50000
}
Now, suppose we want to change the product name and price. We send a PUT request with the updated product data.
{
"name": "Gaming Laptop",
"price": 75000
}
In a typical PUT implementation, the server replaces the existing resource representation with the supplied data. The exact handling of fields such as the ID depends on the API design.
2. What Is a PATCH Request?
A PATCH request is used to update only selected fields of an existing resource. The client does not need to send every field.
Suppose the existing product is:
{
"id": 1,
"name": "Laptop",
"price": 50000
}
If we want to change only the price, we can send the following data in a PATCH request.
{
"price": 60000
}
The updated product will be:
{
"id": 1,
"name": "Laptop",
"price": 60000
}
3. Difference Between PUT and PATCH
| Feature | PUT | PATCH |
|---|---|---|
| Purpose | Replace or fully update a resource | Update selected fields |
| Request body | Usually contains the complete resource representation | Contains the fields or changes to apply |
| Unsent fields | May be reset or removed, depending on the API contract | Usually remain unchanged |
| Example | Update product name and price together | Update only the product price |
| Common success status | 200 OK or 204 No Content | 200 OK or 204 No Content |
4. Creating PUT and PATCH Routes
We can create PUT and PATCH routes in an Express application. The following example uses an in-memory array to demonstrate how existing product data can be updated.
const express = require('express');
const app = express();
app.use(express.json());
let products = [
{ id: 1, name: 'Laptop', price: 50000 },
{ id: 2, name: 'Mobile', price: 20000 }
];
// PUT: Replace the product details
app.put('/api/products/:id', (req, res) => {
const id = Number(req.params.id);
const index = products.findIndex(
product => product.id === id
);
if (index === -1) {
return res.status(404).json({
message: 'Product not found'
});
}
const { name, price } = req.body;
if (
typeof name !== 'string' ||
name.trim() === '' ||
typeof price !== 'number' ||
!Number.isFinite(price) ||
price < 0
) {
return res.status(400).json({
message: 'Valid name and price are required'
});
}
products[index] = {
id,
name: name.trim(),
price
};
res.status(200).json({
message: 'Product replaced successfully',
product: products[index]
});
});
// PATCH: Update selected product fields
app.patch('/api/products/:id', (req, res) => {
const id = Number(req.params.id);
const product = products.find(
product => product.id === id
);
if (!product) {
return res.status(404).json({
message: 'Product not found'
});
}
const { name, price } = req.body;
if (Object.keys(req.body).length === 0) {
return res.status(400).json({
message: 'At least one field is required'
});
}
if (
Object.hasOwn(req.body, 'name') &&
(typeof name !== 'string' || name.trim() === '')
) {
return res.status(400).json({
message: 'Name must be a non-empty string'
});
}
if (
Object.hasOwn(req.body, 'price') &&
(
typeof price !== 'number' ||
!Number.isFinite(price) ||
price < 0
)
) {
return res.status(400).json({
message: 'Price must be a non-negative number'
});
}
if (Object.hasOwn(req.body, 'name')) {
product.name = name.trim();
}
if (Object.hasOwn(req.body, 'price')) {
product.price = price;
}
res.status(200).json({
message: 'Product updated successfully',
product
});
});
app.listen(3000, () => {
console.log('Server running at http://localhost:3000');
});
5. Understanding the PUT Route
The PUT route uses the product ID from the URL to locate the existing product. It then validates the request body and replaces the product with the supplied name and price.
app.put('/api/products/:id', (req, res) => {
// Find the product
// Validate the complete replacement data
// Replace the existing product
});
Example request:
PUT http://localhost:3000/api/products/1
Content-Type: application/json
Request body:
{
"name": "Gaming Laptop",
"price": 75000
}
Example response with status code 200 OK:
{
"message": "Product replaced successfully",
"product": {
"id": 1,
"name": "Gaming Laptop",
"price": 75000
}
}
6. Understanding the PATCH Route
The PATCH route finds the product and updates only the fields supplied in the request body. Fields that are not supplied remain unchanged.
Example request:
PATCH http://localhost:3000/api/products/1
Content-Type: application/json
Request body:
{
"price": 80000
}
Example response with status code 200 OK:
{
"message": "Product updated successfully",
"product": {
"id": 1,
"name": "Gaming Laptop",
"price": 80000
}
}
7. PUT and PATCH Request Flow
Both methods follow a similar process, but the update operation differs.
Sends PUT or PATCH request
Reads the ID and request body
Checks whether the product exists and data is valid
Replaces the product representation
Updates selected fields
Returns updated data or an error message
8. Common HTTP Status Codes
| Status Code | Meaning | When to Use |
|---|---|---|
| 200 OK | Request completed successfully | When returning the updated resource or a success message |
| 204 No Content | Request completed without a response body | When the update succeeds and no content needs to be returned |
| 400 Bad Request | Request data is invalid | When required fields or validation rules fail |
| 404 Not Found | Resource does not exist | When the supplied product ID cannot be found |
Important Points to Remember
- PUT is generally used to replace a resource representation.
- PATCH is generally used to update selected fields.
- Use
req.params.idto read the product ID from the URL. - Use
req.bodyto access the parsed request body. - Use
express.json()to parse incoming JSON request bodies. - Validate request data before changing existing records.
- Return 404 when the requested product does not exist.
- Use a database for persistent application data.
Summary
PUT and PATCH are HTTP methods used to update resources in a REST API. PUT generally replaces the resource representation, while PATCH modifies selected fields. Express routes can handle both methods by reading the URL parameters, validating the request body, updating the resource, and returning an appropriate HTTP response.
In the next lesson, we will learn how to delete resources using the DELETE request.