Handling HTTP PUT Requests
A PUT request asks the server to update an existing resource by replacing it with the data sent in the request body. In an Express API it is how a client says "here is the new version of book 3". A PUT handler finds the resource by its id from the URL, validates the incoming data, applies the update and sends back the result, or an error if something is wrong.
The steps a PUT handler performs
- Read the id from the route parameter.
- Look up the resource. If it does not exist, respond with 404.
- Validate the request body. If it is invalid, respond with 400.
- Update the resource.
- Return the updated resource, usually with status 200.
Checking existence before validation, or the other way round, is a design choice. Many APIs check existence first so a client learns about a wrong id before fixing body errors.
A working example
const express = require('express');
const app = express();
app.use(express.json()); // parses JSON bodies into req.body
const books = [
{ id: 1, title: 'Wings of Fire', author: 'A. P. J. Abdul Kalam' },
{ id: 2, title: 'The Guide', author: 'R. K. Narayan' },
];
function validateBook(body) {
if (typeof body.title !== 'string' || body.title.trim().length < 2) {
return 'title must be at least 2 characters';
}
if (typeof body.author !== 'string' || body.author.trim() === '') {
return 'author is required';
}
return null;
}
app.put('/api/books/:id', (req, res) => {
const book = books.find((b) => b.id === Number(req.params.id));
if (!book) {
return res.status(404).json({ error: 'Book not found' });
}
const error = validateBook(req.body);
if (error) {
return res.status(400).json({ error });
}
book.title = req.body.title.trim();
book.author = req.body.author.trim();
res.json(book);
});
app.listen(3000);
You can test it from a terminal with curl -X PUT http://localhost:3000/api/books/2 -H "Content-Type: application/json" -d "{\"title\":\"Malgudi Days\",\"author\":\"R. K. Narayan\"}", or with an API client such as Postman or the REST Client extension in VS Code.
In a real application, the books array would be replaced by a database query, and validation would often use a library such as Joi or Zod. The flow of the handler stays the same.
PUT, PATCH and idempotency
PUT means "replace". The client sends the whole resource, and fields missing from the body are expected to be cleared or reset. PATCH means "modify", sending only the fields that change. Many APIs are relaxed about this, but if you call an endpoint PUT, validate that all required fields are present.
PUT is also idempotent: sending the same request once or five times leaves the resource in the same state. That is why clients and proxies can safely retry a failed PUT. POST, which creates new items, is not idempotent, because repeating it can create duplicates.
Mistakes that break PUT handlers
req.body is undefined. Express does not parse bodies by default. Without app.use(express.json()) registered before the route, req.body is undefined and accessing req.body.title crashes. The client must also send the Content-Type: application/json header, or the parser skips the body.
Missing return after an error. If you write res.status(404).json(...) without return, the function keeps going and tries to send a second response, triggering "Cannot set headers after they are sent to the client". Always return when sending early.
Comparing ids of different types. req.params.id is a string. Comparing it with === to a numeric id always fails, so every request gets 404. Convert with Number() first, as above.
Copying the whole body into the record. Writing Object.assign(book, req.body) lets a client overwrite fields like id or add unexpected ones. Copy only the fields you allow.
Checklist
- Register
express.json()before routes. - 404 for a missing id, 400 for invalid data, 200 with the updated resource on success.
- Return after every early response and update only allowed fields.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.