Express: Product Catalog
Create an Express.js application that manages a catalog of products. Start with a predefined array of products, each having the properties id, name, price, and stock.
Implement a
PUT
route at/products/:id
that updates an existing product’s details. The request body may contain any combination of the three updatable fields: name, price, and stock.Your application should update only the fields provided in the request and leave the rest unchanged.
If a product with the given ID is not found, return a 404 status with a message indicating that the product does not exist.
Ensure the use of
express.json()
middleware to process JSON bodies and return structured JSON responses that confirm the update and show the latest state of the product. Keep the application implementation in a single JavaScript file, without using a database or external files.
app.js
import express from 'express';
const app = express();
const PORT = 3000;
// Middleware to parse JSON bodies
app.use(express.json());
// In-memory product catalog
let products = [
{ id: 1, name: 'Laptop', price: 1200, stock: 15 },
{ id: 2, name: 'Keyboard', price: 75, stock: 50 },
{ id: 3, name: 'Mouse', price: 25, stock: 100 }
];
// --- Routes ---
// PUT /products/:id - Update an existing product
app.put('/products/:id', (req, res) => {
const productId = parseInt(req.params.id, 10);
const { name, price, stock } = req.body;
const product = products.find(p => p.id === productId);
// Handle case where product is not found
if (!product) {
return res.status(404).json({ message: 'Product not found' });
}
// Update only the fields that are provided in the request body
if (name !== undefined) {
product.name = name;
}
if (price !== undefined) {
product.price = price;
}
if (stock !== undefined) {
product.stock = stock;
}
res.json({ message: 'Product updated successfully', product });
});
// GET route to view and test
app.get('/products', (req, res) => {
res.json(products);
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
$ curl -X PUT -H "Content-Type: application/json"
-d '{"name": "Charlie Brown", "price":
"Char@mail.com", "stock": 13}'
http://localhost:3000/products/1
Test the API with Postman
Update an existing product (PUT
)
Open Postman and create a new request.
Set the method to PUT.
Enter the URL for a specific product, for example:
http://localhost:3000/products/2
.Go to the Body tab, select raw, and choose JSON from the dropdown.
In the text area, enter only the fields you want to update. For example, to update just the price and stock of the keyboard:
{
"price": 80,
"stock": 45
}
- Click Send. You will see a success message and the fully updated product object in the response.
Attempt to update a non-existent product (PUT
)
In the same request, change the URL to an ID that doesn't exist, like:
http://localhost:3000/products/99
.Click Send. The API will return a 404 Not Found status with the message
"Product not found"
.