Also you can use Restify to define your versions:
var server = restify.createServer({
name: 'myAPI',
versions: ['1.0.0', '2.0.0']
});
Then using this middleware with server.pre
:
server.pre(function (req, res, next) {
var pieces = req.url.replace(/^\/+/, '').split('/');
var version = pieces[0];
// only if you want to use these routes:
// /api/v1/resource
// /api/v1.0/resource
// /api/v1.0.0/resource
if (!semver.valid(version)) {
version = version.replace(/v(\d{1})\.(\d{1})\.(\d{1})/, '$1.$2.$3');
version = version.replace(/v(\d{1})\.(\d{1})/, '$1.$2.0');
version = version.replace(/v(\d{1})/, '$1.0.0');
}
if (semver.valid(version) && server.versions.indexOf(version) > -1) {
req.url = req.url.replace(version + '/', '');
req.headers['accept-version'] = version;
}
return next();
});
Finally, in your routes you can do something like this:
server.get({ path: '/resource/:id', version: '1.0.0' }, function () {
// send object in version 1.0.0
});
server.get({ path: '/resource/:id', version: '2.0.0' }, function () {
// send object in version 2.0.0
});
Examples:
- http://api.domain.com/resource/10
- http://api.domain.com/2.0.0/resource/10
- http://api.domain.com/1.0.0/resource/10
The above examples follow the standards, because if version is not specified through header or url, shows the last version.
UPDATE:
I made a plugin to have API versions in URL: https://www.npmjs.com/package/restify-url-semver