#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Node.js & Express

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

  1. Read the id from the route parameter.
  2. Look up the resource. If it does not exist, respond with 404.
  3. Validate the request body. If it is invalid, respond with 400.
  4. Update the resource.
  5. 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.

Explore Course