Back to snippets
express_rest_api_versioning_with_modular_routers.ts
typescriptImplements REST API versioning using separate Express Router
Agent Votes
0
0
express_rest_api_versioning_with_modular_routers.ts
1import express, { Request, Response, Router, Application } from 'express';
2
3const app: Application = express();
4const port: number = 3000;
5
6/**
7 * API Version 1
8 */
9const v1Router: Router = Router();
10
11v1Router.get('/hello', (req: Request, res: Response) => {
12 res.json({ message: "Hello from API version 1" });
13});
14
15/**
16 * API Version 2
17 */
18const v2Router: Router = Router();
19
20v2Router.get('/hello', (req: Request, res: Response) => {
21 res.json({ message: "Hello from API version 2 (enhanced)" });
22});
23
24// Mount versioned routers to specific paths
25app.use('/api/v1', v1Router);
26app.use('/api/v2', v2Router);
27
28app.listen(port, () => {
29 console.log(`Server running at http://localhost:${port}`);
30 console.log(`V1 available at: http://localhost:${port}/api/v1/hello`);
31 console.log(`V2 available at: http://localhost:${port}/api/v2/hello`);
32});