Your First Resource (CRUD)
Let's put the principles into practice. We'll design a Productsresource following the industry-standard CRUD (Create, Read, Update, Delete) pattern.
The Standard Endpoint Map
| Method | URI | Result |
|---|
GET | /products | Find all products |
GET | /products/:id | Find one specific product |
POST | /products | Create a new product |
PUT | /products/:id | Replace a product entirely |
PATCH | /products/:id | Update parts of a product |
DELETE | /products/:id | Remove a product |
Implementation Pattern
A professional route handler should perform 4 steps: Parse, Validate, Execute, and Respond.
// POST /products Example (Express-like pseudo-code)
app.post('/products', (req, res) => {
const { name, price } = req.body; // Parse
if (!name || price < 0) { // Validate
return res.status(400).json({ error: 'Invalid data' });
}
const product = await Product.create({ name, price }); // Execute
res.status(201).json({ status: 'success', data: { product } }); // Respond
});
Key Insight: Notice how the response doesn't just send the data. It wraps it in a data property. This allows you to addMetadata (like pagination or timing) later without breaking clients.