057
LVL 03 — MID DEVELOPER SESSION 057 DAY 57

EXPRESS API

🎫 PIXELCRAFT-044
Feature | 🟠 Hard | Priority: 🔴 Critical

The raw http module is too low-level for 20+ routes. Use Express.js to build a proper REST API for PixelCraft: CRUD operations for images.
CONCEPTS.UNLOCKED
🚂
Express.js
Web framework for Node.js. Handles routing, request parsing, middleware, and error handling. The most popular Node.js framework — powers millions of APIs.
📐
REST Architecture
Resources (nouns) + HTTP methods (verbs). GET /images = list images. POST /images = create. PUT /images/:id = update. DELETE /images/:id = remove. Consistent and predictable.
🛤
Routes
app.get('/api/images', handler), app.post(...), app.put(...), app.delete(...). Each route maps a URL + method combination to a handler function.
🔑
Route Parameters
/api/images/:id — the colon marks a dynamic segment. req.params.id extracts the value. /api/images/42 → req.params.id === '42'.
Middleware
Functions that process requests before your handler. Logging, CORS, JSON parsing, authentication — all middleware. Runs in order, calls next() to continue.
📦
Request / Response
req: params, body, query, headers. res: json(), status(), send(), end(). The request carries data IN, the response sends data OUT.
HANDS-ON.TASKS
01
Set Up Express
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;
02
Build the CRUD API
// 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(); });
03
Add Middleware
// 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') );
04
Test with curl
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}'
curl is a command-line HTTP client. It sends requests to your API and prints the response. Postman is the visual alternative. Both are essential backend development tools.
05
Implement Error Responses

Implement proper error responses for all edge cases: missing fields (400), not found (404), server errors (500). Every response has a clear error message.

06
Close the Ticket
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 ✅
CS.DEEP-DIVE

Middleware is a pipeline pattern.

Each request flows through a chain of functions. The same pattern you've seen before.

// The pipeline pattern everywhere:

Express         → logger → cors →
                   jsonParser → auth →
                   routeHandler → errorHandler
PixelCraft      → brightness → contrast
                   → saturation (Session 28)
Unix pipes      → cat | grep | sort
                   (Session 3)

// Chain-of-responsibility: one of the
// most versatile patterns in software.
"API Lab"
[A] Add query parameters: GET /api/images?format=png&sort=date filters by format and sorts by creation date. Use req.query to extract parameters.
[B] Add a request-timing middleware that logs how long each request takes: "GET /api/images — 12ms". Use Date.now() before and after next().
[C] Connect the React frontend to this API: replace localStorage with fetch() calls to your Express server. The frontend reads from the API, writes to the API.
REF.MATERIAL
ARTICLE
Express.js Team
Official Express guide: hello world, routing, static files, middleware, and error handling. The definitive starting point.
EXPRESSOFFICIALESSENTIAL
VIDEO
Fireship
Ultra-fast Express overview: routing, middleware, request/response, and why it dominates Node.js backends.
EXPRESSQUICK
ARTICLE
Express.js Team
Complete routing reference: route methods, parameters, route handlers, express.Router, and route chaining.
ROUTINGOFFICIAL
ARTICLE
Wikipedia
REST architecture: resources, HTTP methods, statelessness, uniform interface. The architectural style that defines modern APIs.
RESTARCHITECTURECS
VIDEO
Traversy Media
Full Express API tutorial: setup, CRUD routes, middleware, error handling, and testing with Postman.
EXPRESSTUTORIAL
// LEAVE EXCITED BECAUSE
You built a complete REST API. Your React frontend can now talk to YOUR server. You control both halves of the application.