npm install express cors
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(express.json());
// In-memory storage (temporary)
let images = [];
let nextId = 1;
// GET all images
app.get('/api/images', (req, res) => {
res.json(images);
});
// GET single image
app.get('/api/images/:id', (req, res) => {
const image = images.find(
img => img.id === parseInt(req.params.id)
);
if (!image) return res.status(404)
.json({ error: 'Image not found' });
res.json(image);
});
// POST new image
app.post('/api/images', (req, res) => {
const { name, width, height, format } = req.body;
if (!name) return res.status(400)
.json({ error: 'Name is required' });
const image = {
id: nextId++, name, width, height, format,
createdAt: new Date()
};
images.push(image);
res.status(201).json(image);
});
// PUT update image
app.put('/api/images/:id', (req, res) => {
const image = images.find(
img => img.id === parseInt(req.params.id)
);
if (!image) return res.status(404)
.json({ error: 'Image not found' });
Object.assign(image, req.body,
{ updatedAt: new Date() });
res.json(image);
});
// DELETE image
app.delete('/api/images/:id', (req, res) => {
const index = images.findIndex(
img => img.id === parseInt(req.params.id)
);
if (index === -1) return res.status(404)
.json({ error: 'Image not found' });
images.splice(index, 1);
res.status(204).end();
});
// Logging middleware
app.use((req, res, next) => {
console.log(
`${new Date().toISOString()} ` +
`${req.method} ${req.url}`
);
next();
});
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500)
.json({ error: 'Internal server error' });
});
app.listen(3001, () =>
console.log('API running on http://localhost:3001')
);
curl http://localhost:3001/api/images
curl -X POST http://localhost:3001/api/images \
-H "Content-Type: application/json" \
-d '{"name":"test.jpg","width":1920,"height":1080}'
Implement proper error responses for all edge cases: missing fields (400), not found (404), server errors (500). Every response has a clear error message.
git switch -c feature/PIXELCRAFT-044-express-api
git add server/ package.json
git commit -m "Build REST API with Express CRUD + middleware (PIXELCRAFT-044)"
git push origin feature/PIXELCRAFT-044-express-api
# PR → Review → Merge → Close ticket ✅
Middleware is a pipeline pattern.
Each request flows through a chain of functions. The same pattern you've seen before.