Go back | Day 14

Good deals -- Angular and Groupon

In today's snippet, we're looking at how to connect our application to the great deals offered by the Groupon API.

The Groupon API requires a an api_key to authenticate the requesting user. Luckily, getting a Groupon api_key is really easy to do.

Head over to the Groupon API docs page at http://www.groupon.com/pages/api and click on the giant Get My Api Key button.

After we sign up, we get our API key. Let's hold on to this key for the time being.

Providing the API

Anytime that we are building a service that we'll want to configure, for example with an API key we'll want to use the .provider() function to create a service. This will allow us to craft a service that holds on to our key for future requests.

We'll write the service to be able to be configured with an api key. This can be accomplished like so:

angular.module('alGroupon', [])
.provider('Groupon', function() {
  // hold on to our generic variables
  var apiKey = '',
      baseUrl = '//api.groupon.com/v2';

  // A function to set the api key
  this.setApiKey = function(key) {
    apiKey = key || apiKey;
  }

  this.$get = [function() {
    // Service definition
  }]
});

In our app, we'll use this module by setting it as a dependency and then configuring our service inside of a .config() function. For example:

angular.module('myApp', ['alGroupon'])
.config(function(GrouponProvider) {
  GrouponProvider
    .setApiKey('XXXXXXXXXXXXXXXXXXX');
})

Defining the service

Now we haven't actually created any functionality for the Groupon service. Let's go ahead and create a function that will find some of the latest deals.

The API method to get the latest deals (can be found in the docs page) is at the route /deals.json. Luckily for us, the Groupon API supports JSONP fetching which allows us to fetch the deals without needing to concern ourselves with CORS.

Inside of our requests, we'll need to pass in two parameters for each one of our requests:

  • callback
  • client_id

As we have these already available to us in our service, we can create a small helper function that will create the request parameters we'll eventually use to make the service request:

// The service definition
this.$get = ['$q', '$http', 
  function($q, $http) {
    var prepareRequest = function(conf) {
      // Ensure we have a config option
      conf = conf || {}
      // Set the callback and the client_id
      // in the config object
      conf['callback'] = 'JSON_CALLBACK';
      conf['client_id'] = api_key
      return conf;
    }
    // ...
}]

With that set, let's create the function that gets some deals. This simply is a function that we can set up with the standard $http request:

this.$get = ['$q', '$http', 
  function($q, $http) {
    // ...
    var service = {
      getDeals: function(conf) {
        var d = $q.defer();
        conf = prepareRequest(conf);
        // Execute the request in the background
        $http({
          method: 'JSONP',
          url: baseUrl + '/deals.json',
          params: conf
        }).success(function(data) {
          d.resolve(data.deals);
        }).error(function(reason) {
          d.reject(reason);
        })
        return d.promise;
      }
    }
    return service;
}]

We're creating a custom promise in this example. Although this isn't necessary, it allows us to pass back custom data. In here, we're passing back not just data, but data.deals.

Now, we can simply inject this into our controller and call getDeals on the service as we would any other service.

angular.module('myApp', ['alGroupon'])
.controller('GrouponController', 
  function($scope, Groupon) {
    $scope.getDeals = function() {
      Groupon.getDeals()
      .then(function(deals) {
        $scope.deals = deals;
      });
    }
});

Notice in our function we allow the user pass in configuration for the requests. We can use this configuration object to customize our request to the Groupon API.

That's it. Connecting with Groupon is that easy with our configurable service.

The Groupon API documentation can be found here.

Enjoy this snippet?

Check out our book that's heading to print this week at ng-book.com

The 600+ page book is packed full of Angular content written and designed to get you up to speed with Angular from beginner to expert.

Independently published with content just like what you've just read.

Brought to you by the team behind ng-newsletter