PUT is used to replace an entire resource. It’s like saying “take this complete new version and replace the old one.”

How PUT Works

Now we’ll use app.put() to create routes that handle PUT requests.

Route Parameters: We looked at route params in Lesson 2. The :id in /users/:id is a placeholder that captures the user ID from the URL. When someone visits /users/1, the :id captures 1 and makes it available as req.params.id.

From the frontend:

fetch("/users/1", {
  method: "PUT",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    name: "John Updated",
    email: "john.updated@example.com",
  }),
});

On the API side:

app.put("/users/:id", (req, res) => {
  const userId = Number(req.params.id);

  // Check if ID is a valid number
  if (isNaN(userId)) {
    return res.status(400).json({ error: "Invalid user ID" });
  }

  const { name, email } = req.body;

  if (!name || !email) {
    return res.status(400).json({ error: "Name and email are required" });
  }

  const userIndex = users.findIndex((user) => user.id === userId);

  if (userIndex === -1) {
    return res.status(404).json({ error: "User not found" });
  }

  users[userIndex] = { id: userId, name, email };
  res.json(users[userIndex]);
});

Key Points About PUT

  1. Route parameters - :id in the route becomes req.params.id
  2. Convert and validate ID - Use Number() to convert string to number, check isNaN() for invalid IDs
  3. Validate request body - Check that required fields (name, email) are provided
  4. Find the resource - Use findIndex() to locate the user in the array
  5. Handle missing resources - Return 404 if user not found
  6. Replace entire resource - Replace the entire user object with new data
  7. Return the updated resource - Send back the new version with 200 OK

PUT vs POST

  • POST - Creates new resources (you don’t know the ID yet)
  • PUT - Replaces existing resources (you know the ID)

Security note: In a real application, this route would also require proper authentication and authorization, which we’ll cover in Module 3.



Repo link

Tags: