DELETE Requests in Node.js
Learn how to delete existing resources from a REST API using the DELETE HTTP method in Node.js and Express.
In a REST API, the DELETE method is used to remove an existing resource. For example, an application may allow users to delete a product using its ID.
Suppose a product has ID 1. When the client sends a DELETE request for that product, the server finds the product and removes it if it exists.
1. What Is a DELETE Request?
A DELETE request asks the server to remove a resource identified by the request URL. In a product API, the product ID is commonly passed as a route parameter.
DELETE http://localhost:3000/api/products/1
In this example, the server attempts to delete the product whose ID is 1. If the deletion succeeds, the API can return a success message or an empty response, depending on its design.
2. Understanding the DELETE Route
Express provides the app.delete() method to handle
DELETE requests. We can define a route containing an ID parameter
and use that ID to locate the resource.
app.delete('/api/products/:id', (req, res) => {
const id = Number(req.params.id);
// Find the product using its ID
// Delete the product if it exists
// Return an appropriate response
});
Here is what each part means:
| Code | Purpose |
|---|---|
app.delete() |
Registers a route for DELETE requests. |
/api/products/:id |
Defines a URL containing a product ID parameter. |
req.params.id |
Reads the ID supplied in the URL. |
res.status() |
Sets the HTTP response status code. |
res.json() |
Sends a JSON response to the client. |
3. Complete Example: Deleting a Product
The following example creates an Express server with an in-memory product array. The DELETE route searches for a product by ID and removes it if found.
const express = require('express');
const app = express();
app.use(express.json());
let products = [
{ id: 1, name: 'Laptop', price: 50000 },
{ id: 2, name: 'Mobile', price: 20000 },
{ id: 3, name: 'Keyboard', price: 1500 }
];
// GET: Retrieve all products
app.get('/api/products', (req, res) => {
res.status(200).json(products);
});
// DELETE: Remove a product by ID
app.delete('/api/products/:id', (req, res) => {
const id = Number(req.params.id);
if (!Number.isInteger(id) || id <= 0) {
return res.status(400).json({
message: 'Invalid product ID'
});
}
const index = products.findIndex(
product => product.id === id
);
if (index === -1) {
return res.status(404).json({
message: 'Product not found'
});
}
const deletedProduct = products[index];
products.splice(index, 1);
res.status(200).json({
message: 'Product deleted successfully',
product: deletedProduct
});
});
app.listen(3000, () => {
console.log('Server running at http://localhost:3000');
});
4. How Does the DELETE Request Work?
When the client sends a DELETE request, Express executes the matching route. The server reads the ID, validates it, searches for the product, and removes the matching record.
Sends DELETE request with product ID
Reads the ID from req.params
Checks the ID and searches for the product
Remove the product and return success
Return 404 Not Found
Sends the result to the client
5. Testing the DELETE Request
Start the Node.js server and open Postman to test the API. Select the DELETE method and enter the product URL.
node app.js
Expected terminal output:
Server running at http://localhost:3000
In Postman, configure the request as follows:
| Setting | Value |
|---|---|
| Method | DELETE |
| URL | http://localhost:3000/api/products/1 |
| Request body | Not required for this example |
Expected response with status code 200 OK:
{
"message": "Product deleted successfully",
"product": {
"id": 1,
"name": "Laptop",
"price": 50000
}
}
To confirm the deletion, send a GET request to
http://localhost:3000/api/products.
The product with ID 1 will no longer appear in the returned array.
6. Handling Errors in DELETE Requests
A good REST API should handle invalid IDs and missing resources instead of returning a success response for every request.
| Status Code | Meaning | Example |
|---|---|---|
| 200 OK | Deletion succeeded | The product was removed and a JSON response is returned. |
| 204 No Content | Deletion succeeded without a response body | The product was removed, and no response content is sent. |
| 400 Bad Request | The supplied ID is invalid | The ID is not a positive integer. |
| 404 Not Found | The requested product does not exist | No product matches the supplied ID. |
For example, requesting an unknown product:
DELETE http://localhost:3000/api/products/99
Example response with status code 404 Not Found:
{
"message": "Product not found"
}
7. Important Points to Remember
- Use
app.delete()to create a DELETE route in Express. - Use
req.params.idto read an ID from the URL. - Validate the ID before attempting deletion.
- Check whether the resource exists before deleting it.
- Return 404 when the requested resource does not exist.
- Use 200 OK when returning a response body after deletion.
- Use 204 No Content when the deletion succeeds and no body is returned.
- Protect deletion routes with appropriate authentication and authorization.
- Use a database for persistent data in real applications.
Summary
The DELETE HTTP method removes an existing resource from a REST API.
In Express, we use app.delete() to define the route,
req.params to read the resource ID, and appropriate
HTTP status codes to communicate the result.
In the next lesson, we will learn how to validate incoming requests before processing them in a REST API.