Compass In Hand

Guiding The Geek In You

Category Archives: Mini-Gems


Multiple Restangular API Base URLs Made Easy

What is Restangular?

Restangular is a powerful, third-party AngularJS module designed to greatly simplify REST communication by abstracting specific transactional code from your application code. Restangular APIs offer a uniform approach to handling HTTP methods, as well as deliver results in a tidy Promise object while freeing developers from the need to use specific URLs. Configure Restangular at one end to wrestle with external APIs, and at the other to enjoy accessing data in a simple Promise-based fashion.

Installing Restangular is well-covered by the mgonto/restangular repo readme, but in summary is easy as:

bower install restangular

or

npm install restangular

Once installed, inject ‘restangular’ into your app as you would any third-party resource:

angular.module('yummyFruit', [
    'yummyFruit.services',
    'restangular'
]);

Using Restangular on “Basic” Mode

At first blush, configuring Restangular may seem daunting. The vast number of methods, and the equally vast number of ways to use them, can quickly make any “starter” Restangular project into a casserole of configuration mish mash. Therefore, the most sensible approach for configuring Restangular in a single API base URL scenario is by starting with the application config method:

.config(function(RestangularProvider) {
    RestangularProvider.setBaseUrl('https://api.tropical.com');
});

Restangular will now use https://api.tropical.com as the base URL for all API calls. Injecting Restangular as a dependency into your service(s) and configuring your API endpoints is simply a matter of:

angular.module('yummyFruit.services')
.service('FruitService', function(Restangular) {
    var FruitService = this,
    fruits = Restangular.all('/fruits');

        FruitService.getFruit = function() {
            return fruits.one('/').get();
        };
});

But Wait, We Use Multiple APIs!

The configuration detailed above works great in a single API scenario. However, most sophisticated web applications lean heavily upon multiple APIs, each with their own unique access requirements. Therefore, a more robust solution is required.

In a well-modularized application, global services should be contained within their own folder. To further improve modularity, I like using a separate file to create a global Service module. As it turns out, this file – _services.js – is an ideal place to configure Restangular to use multiple API base URLs.

angular.module('yummyFruit.services', [])
.factory("TropicalRestangularApi", ["Restangular",
function(restangular) {
	return restangular.withConfig(function(RestangularConfigurer) {
            RestangularConfigurer.setBaseUrl("https://api.tropical.com");
        });
}])

.factory("BerryRestangularApi", ["Restangular",
function(restangular) {
	return restangular.withConfig(function(RestangularConfigurer) {
            RestangularConfigurer.setBaseUrl("https://api.berries.com");
        });
}]);

Each factory is a self-encapsulated, Restangular instance, each featuring a unique base URL. Additionally, the factories are centrally located, affording easy reference for all team members. Exposure to the Restangular API factories is easily arranged via dependency injection:

angular.module('yummyFruit.services')
.service('FruitService', ['Restangular', 'BerryRestangularApi',
function(Restangular, BerryRestangularApi) {
    var berryFruitApiBase = BerryRestangularApi.all('/api');
}]);

Application services within the services module can now use one, some, or all the individual APIs at will, and without any more configuration necessary.

If you found this post useful, please share it on Twitter, Reddit, or your other favorite social media outlet! Questions? Hit me up on Twitter @jasonlunsford or leave your question in the comments below.

Thanks for reading!