Last updated on July 11, 2023
To version your Express.js REST APIs, you can prefix the routes with a version number or a specific identifier. This approach allows you to introduce changes to your API while maintaining backward compatibility for existing clients. Here’s an example of how you can version your Express.js APIs:
To version your Express.js REST APIs, you can prefix the routes with a version number or a specific identifier. This approach allows you to introduce changes to your API while maintaining backward compatibility for existing clients. Here’s an example of how you can version your Express.js APIs:
- Create a folder structure for your API versions:
- Create a
v1
folder for version 1 of your API. - Create a
v2
folder for version 2 of your API. - Place your route files inside the respective version folders.
- Create a
- Define your routes for each version:
- In the
v1
folder, create aroutes.js
file to define version 1 routes. - In the
v2
folder, create aroutes.js
file to define version 2 routes.
- In the
Example v1/routes.js
:
const express = require('express');
const router = express.Router();
// Version 1 routes
router.get('/users', (req, res) => {
res.send('Version 1: Get users');
});
module.exports = router;
Example v2/routes.js
:
const express = require('express');
const router = express.Router();
// Version 2 routes
router.get('/users', (req, res) => {
res.send('Version 2: Get users');
});
module.exports = router;
Update your main Express.js app file to include the route versions:
const express = require('express');
const app = express();
// Version 1 routes
const v1Routes = require('./v1/routes');
app.use('/v1', v1Routes);
// Version 2 routes
const v2Routes = require('./v2/routes');
app.use('/v2', v2Routes);
// Start the server
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
In this example, the v1
routes are accessible at /v1/users
, and the v2
routes are accessible at /v2/users
.
By following this approach, you can make changes to the API routes in a new version folder without impacting existing clients relying on the previous version. This allows you to introduce backward-compatible changes or deprecate older versions gradually.
Remember to appropriately handle the migration process between versions and provide clear documentation for your API consumers to understand the available versions and any breaking changes introduced in new versions.