Skip to main content

Versioning REST API routes in Express.js

Over the past few months I have been building a RESTful web service that is to be consumed from both the web as well as an HTML5 hybrid mobile app powered by the Ionic framework. The web consumer doesn’t present much of a problem since the API will only be consumed by a first-party web client. On the other hand, I cannot leave mobile app users dead in the water if they decide against upgrading.
The clear solution to this problem is API versioning. It works as simply as offering different versions of your API to consumers while still allowing you to add new features and (potentially) break stuff in the process.
I have been writing the API in Javascript using Express.js and was looking for a clean and easy way to implement versioning. The method that was inspired by a few hours of reading is to simply have the version specified in the request URI, with the default version being the latest. So, say I have a couple of routes:
  • GET /v1/user/:id
  • GET /v2/user/:id
  • GET /user/:id -> GET /v2/user/:id
Two versions of the API exist (in this example, a REST call for consuming a single user record), version 1 & 2. Since version 2 is the latest version, any call to the default API version (latest) is simply redirected* to the latest implementation of that REST call in my API; in this case, version 2.
Express, being as awesome as it is, is actually very easily configured for this sort of thing. The implementation of the above routes are as follows:
var express = require('express');
var http = require('http');
var app = express();
// Simple user controller implementation.
var users = [
  { username: 'jamsesso', age: 20, gender: 'M' },
  { username: 'bettycrocker', age: 20, gender: 'F' }
];
// Version 1 (Old)
function findUser(req, res) {
  res.json(users[req.params.id]);
}
// Version 2 (New & improved)
function findUser2(req, res) {
  if(!users.hasOwnProperty(req.params.id)) {
    res.send(404);
  }
  else {
    res.json(users[req.params.id]);
  }
}
// Set up the routing.
var v1 = express.Router();
var v2 = express.Router();
v1.use('/user', express.Router()
  .get('/:id', findUser));
v2.use('/user', express.Router()
  .get('/:id', findUser2));
app.use('/v1', v1);
app.use('/v2', v2);
app.use('/', v2); // Set the default version to latest.
// Setup server.
http.createServer(app).listen(8081, function () {
  console.log('Magic is happening on port 8081');
});
With this approach, it is also possible to implement different middleware depending on the API version which is quite a powerful capability — think beta user authentication, etc…
Hopefully this is of some use to any future developers working on an Express.js REST 

Comments

Popular posts from this blog

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...