Versioning
Part of the REST APIs section of Coddy's Node.js journey. Lesson 15 of 18.
Changing the shape of an answer breaks every client already using it. A version in the path lets old and new clients live side by side: /api/v1/orders today, /api/v2/orders when the shape changes. Paths that move answer a redirect:
GET /api/orders/5 → 308 Location: /api/v1/orders/5
POST /api/orders → 308 Location: /api/v1/orders301 and 302 let clients repeat a POST as a GET, which drops the body. 308 says "repeat the same request there", method and body included. Inside a mounted middleware, req.url has lost the mount path, while req.originalUrl keeps all of it:
// in app.use('/api/orders', ...) for GET /api/orders/5?full=1
req.url // '/5?full=1'
req.originalUrl // '/api/orders/5?full=1'Challenge
Easy- Mount the tasks router at
/api/v1/tasks. - Every old
/api/taskspath answers 308 to the same path under/api/v1, query included. - New tasks get
Location: /api/v1/tasks/<id>.
Send GET /api/tasks/2, POST /api/tasks with { "title": "Order new chairs" }, then GET /api/v1/tasks/2.
Try it yourself
import express from 'express';
import { sendError } from './errors.js';
import taskRoutes from './routes/tasks.js';
const BOARD_ORIGIN = 'https://board.example.com';
const app = express();
app.use(express.json());
// Lets pages on BOARD_ORIGIN call this API from the browser.
app.use((req, res, next) => {
res.set('Access-Control-Allow-Origin', BOARD_ORIGIN);
res.set('Access-Control-Allow-Credentials', 'true');
if (req.method === 'OPTIONS') {
res.set('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE');
res.set('Access-Control-Allow-Headers', 'Content-Type');
return res.status(204).end();
}
next();
});
app.use(express.static('public'));
app.use('/api/tasks', taskRoutes);
// Errors from the routes end here. A body that is not valid JSON is the
// client's mistake (400); anything else is ours (500).
app.use((err, req, res, next) => {
if (err.type === 'entity.parse.failed') {
return sendError(res, 400, 'invalid_json', 'The body is not valid JSON');
}
console.error(err);
sendError(res, 500, 'server_error', 'Something went wrong');
});
app.listen(3000, () => {
console.log('Task tracker API on port 3000');
});