We need to create two API endpoints for managing warehouse items:
A GET endpoint to retrieve all new items (not used) and a PUT endpoint to update existing items. Think of this like creating a system for managing inventory in a real warehouse where workers need to both check what's available and update item details as things change.
File: app.js
// Import necessary modules
const express = require('express');
const { WarehouseItem } = require('./db/models');
const app = express();
// Middleware to parse JSON bodies
app.use(express.json());
This endpoint returns all new (unused) warehouse items:
// GET /items - Return all new warehouse items
app.get('/items', async (req, res) => {
try {
// Query database for all items where isUsed is false
const items = await WarehouseItem.findAll({
where: {
isUsed: false
}
});
// Return items as JSON
res.json(items);
} catch (error) {
// Handle any unexpected errors
console.error('Error fetching items:', error);
res.status(500).json({ message: 'An error occurred while fetching items' });
}
});
This endpoint updates an existing warehouse item:
// PUT /items/:id - Update a warehouse item
app.put('/items/:id', async (req, res) => {
try {
const itemId = req.params.id;
// Find the item by ID
const item = await WarehouseItem.findByPk(itemId);
// If item doesn't exist, return 404
if (!item) {
return res.status(404).json({
message: 'Warehouse Item not found'
});
}
// Update the item with the request body
await item.update(req.body);
// Return the updated item
res.json(item);
} catch (error) {
console.error('Error updating item:', error);
res.status(500).json({ message: 'An error occurred while updating the item' });
}
});
Let's verify our implementation using different test scenarios:
// Example test using curl or Postman:
GET http://localhost:3000/items
// Expected successful response:
[
{
"id": 1,
"name": "Paint",
"price": 12.12,
"quantity": 12,
"isUsed": false
},
{
"id": 3,
"name": "Webcam",
"price": 50.5,
"quantity": 5,
"isUsed": false
}
]
// Example test:
PUT http://localhost:3000/items/2
Content-Type: application/json
{
"name": "Pen",
"price": 2.50,
"quantity": 4,
"isUsed": true
}
// Expected successful response:
{
"id": 2,
"name": "Pen",
"price": 2.50,
"quantity": 4,
"isUsed": true
}
// Expected error response (item not found):
{
"message": "Warehouse Item not found"
}
These API endpoints mirror real-world inventory management systems. Consider an actual warehouse:
Just as a warehouse worker needs to quickly see what new items are available, the GET endpoint provides a filtered view of all new inventory. This is similar to checking shelves for fresh stock in a retail store.
When items are sold, damaged, or their details change, warehouse staff need to update the inventory system. The PUT endpoint serves this purpose, like updating a product's price tag or marking items as used/sold.
Watch out for these common API development mistakes:
Missing error handling - Always prepare for things to go wrong. Like a warehouse needs procedures for handling damaged goods, your API needs proper error handling.
Inconsistent response formats - Just as warehouse labels need a standard format, API responses should follow consistent patterns.
Forgetting input validation - Like checking incoming shipments for damage, validate all input data before processing.
Not handling edge cases - Consider all scenarios, just as a warehouse must plan for both regular and unusual situations.
To deepen your understanding, try implementing these additional features:
Add query parameters to filter items by price range - Like allowing warehouse staff to find items within specific price brackets.
Implement pagination - Just as warehouse inventory might be viewed page by page in a catalog.
Add sorting options - Similar to organizing warehouse items by different criteria.
Create a search endpoint - Like having a system to locate specific items in the warehouse.
Remember these key principles when building APIs:
Use descriptive route names - Routes should clearly indicate their purpose, like clear aisle markers in a warehouse.
Implement proper status codes - Use appropriate HTTP status codes to indicate success or failure, like using different colored lights to indicate machine status.
Include meaningful error messages - Error responses should help users understand and fix the problem, like clear warning signs in a warehouse.
Document your API - Maintain clear documentation, just as warehouse staff need clear operating procedures.