content

DELETE

Understanding DELETE is essential for completing the REST API “CRUD” (Create, Read, Update, Delete) operations.

Method Purpose Description
GET Read Retrieve data
POST Create Add new data
PUT Replace Update all fields
PATCH Modify Update some fields
DELETE Remove Delete a record

Code

// **NEW** removes one student
app.delete("/students/:id", (req, res) => {
  const id = parseInt(req.params.id);
  const pos = students.findIndex(s => s.id === id);

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

  // Removes the student at the pos position
  students.splice(pos, 1);
  // No content is returned 
  return res.status(204).send(); // No Content
});

students.splice(pos, 1);

students.splice(pos, 1) removes one element from the students array at index pos.

Part Meaning
students An array that holds all the student objects. Example: [{ id: 1, name: "Anna" }, { id: 2, name: "Ben" }, { id: 3, name: "Clara" }]
.splice() A built-in JavaScript array method that can remove, replace, or insert elements in an array.
pos The index (position) in the array where the change should start. You usually get this with .findIndex().
1 The number of elements to remove starting at that position.

return res.status(204).send();

The request was successful, but there’s no content to send back.

Part Meaning
res The response object provided by Express — used to send data (or status) back to the client.
.status(204) Sets the HTTP status code to 204, which means “No Content.”
.send() Sends the response to the client (in this case, without any body).
return Ends the function immediately — no further code below it will run.

Test

curl -X DELETE http://localhost:3000/students/3 -i

GIT

Do not forget.

Azure

Deploy