http://api.whatever.com/v1/jobs
By the time I realized this the API I had been building with node.js was basically already complete, so I was a little bit sad that I'd have to come up with some complicated versioning scheme.
After a bit of fretting I realized that express can handle this super easy using an interesting feature of the express() instance that it can be mounted to another route using app.use().
This means that your routes don't know which version they are!
Here's your main app file.
app.js file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// define the versions | |
var VERSIONS = {'Pre-Production': '/v0', 'Version 1': '/v1'}; | |
// route to display versions | |
app.get('/', function(req, res) { | |
res.json(VERSIONS); | |
}) | |
// versioned routes go in the routes/ directory | |
// import the routes | |
for (var k in VERSIONS) { | |
app.use(VERSIONS[k], require('./routes' + VERSIONS[k])); | |
} |
Then you'll put each version of your API in the routes/ folder named after the version.
routes/v0.js file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Version 0 | |
var express = require('express'); | |
var contacts = require('../control/contacts') | |
var customAuth = require('../lib/customAuth') | |
var app = module.exports = express(); | |
// middleware that only applies to this version of the API | |
app.use(customAuth()); | |
// normal routes, all will be pre-fixed by the version | |
app.get('/contacts', contacts.index) // /v0/contacts |