content

PUT

In REST, PUT is one of the main HTTP methods — just like GET, POST, PATCH, and DELETE.

Each method describes what kind of action the client wants the server to perform.

Method Action Description
GET Read Retrieve data
POST Create Add new data
PUT Replace Update an existing resource completely
PATCH Modify Update part of an existing resource
DELETE Remove Delete a resource

PUT is used to update or replace an existing record with new data.

How It Works

  1. The client sends a PUT request to /api/students/1.

  2. The server finds the student with ID = 1.

  3. The server replaces that student’s data with the new data.

  4. The server returns the updated student object as JSON.

Code

// **NEW** replaces the student's data
app.put("/students/:id", (req, res) => {
  const id = parseInt(req.params.id);
  const { name, course } = req.body;

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

  // Returns the index of the student with the id.
  const pos = students.findIndex(s => s.id === id);
  if (pos === -1) {
    return res.status(404).json({ error: "Student not found" });
  }

  // update an existing student; replace the object
  students[pos] = { id, name, course };
  res.json(students[pos]);
});

const pos = students.findIndex(s => s.id === id);

Returns the index of the student with the id.

  • .find() → “Give me the student.”

  • .findIndex() → “Tell me where that student is in the array.”

Part Meaning
students An array of student objects — for example: [{ id: 1, name: "Anna" }, { id: 2, name: "Ben" }]
.findIndex() A JavaScript array method that searches the array and returns the index (position) of the first element that matches a condition.
s => s.id === id An arrow function that defines the search condition — here, it checks if a student’s id equals the given id variable.
const pos = ... Saves the found index number into the variable pos.

students[pos] = { id, name, course };

That line is a key part of how you update an existing object (like a student) inside an array in JavaScript.

Part Meaning
students An array that holds all the student objects. Example: [{ id: 1, name: "Anna" }, { id: 2, name: "Ben" }]
pos The index (position) in the array of the student you want to update. Usually found using .findIndex().
= The assignment operator, which replaces the existing item at that position.
{ id, name, course } A new object containing the updated student data. This uses object shorthand, so it’s the same as { id: id, name: name, course: course }.

Test

Local:

curl -X PUT http://localhost:3000/students/3 \
  -H "Content-Type: application/json" \
  -d '{"name":"Clara Becker","course":"Data Science"}'
001.png

GIT

Do not forget.

Azure

Deploy and test.