Express.js Mastery / Express: Let’s Start Building The Natours API!

Handling DELETE Requests

πŸ“– Context

The final CRUD operation to implement is DELETE. Just like with PATCH, the actual deletion logic won't be implemented in the route handler β€” this is because the app is only working with a JSON file, not a real database, so actually removing data isn't necessary for what this section is teaching.


πŸ”Ή Step 1: Building the DELETE Handler

The handler is copied from the PATCH handler and modified slightly:

app.delete('/api/v1/tours/:id', (req, res) => {
  if (req.params.id * 1 > tours.length) {
    return res.status(404).json({
      status: 'fail',
      message: 'Invalid ID'
    });
  }

  res.status(204).json({
    status: 'success',
    data: null
  });
});

πŸ’‘ Why each part works:

  • πŸ”„ Method changed from patch to delete

  • πŸ†” Still needs :id in the route β€” the app needs to know which tour to delete

  • βœ… ID validation logic reused exactly as before (checks if ID is out of range β†’ 404, fail)

  • 🟒 Status code changed to 204 (No Content) β€” the standard response for a successful delete

  • 🚫 data: null β€” since the resource no longer exists, there's nothing to send back; null represents that emptiness

  • βœ… status: 'success' β€” the operation still succeeded, even though there's no data returned

πŸ’‘ This is actually the same pattern used in real-world APIs β€” a real delete endpoint would send back this same 204/null response.


πŸ”Ή Step 2: Testing in Postman

  • πŸ—‘οΈ Set the method to DELETE

  • 🎯 Target a tour ID (e.g., tour number 7) β€” again, this won't actually delete anything since the logic isn't implemented

  • πŸ“€ Send the request β†’ Postman shows 204 No Content, and doesn't even display a response body, since none was meaningfully sent

  • πŸ’Ύ Save the request as "Delete Tour" β€” it now appears alongside the other saved requests in the collection


βœ… Key Takeaway

  • πŸ—‘οΈ DELETE requests conventionally return 204 No Content with data: null, since the deleted resource no longer exists.

  • βœ… The response still marks status: 'success' β€” a successful delete simply has nothing to return.

  • πŸ” The ID-validation pattern (req.params.id * 1 > tours.length β†’ 404 fail) has now been reused across GET-single, PATCH, and DELETE β€” a consistent approach across all ID-based routes.

  • πŸŽ‰ This completes the full CRUD set:

    • βž• Create (POST) β†’ 201

    • πŸ“– Read (GET) β†’ 200

    • ✏️ Update (PATCH) β†’ 200

    • πŸ—‘οΈ Delete (DELETE) β†’ 204


➑️ What's Next

  • 🧹 The next step is to clean up and reorganize the code, applying best practices to make it less messy.