Consuming APIs with AngularJS 1.x

Consuming APIs allows you to retrieve data from a particular service. This service can be one that you made or something publicly available. Previously, we made an API to call our own. This post will show you how to create a front-end to consume that API!

Our front-end will focus on a single collection called Locations. We will have a map that plots our locations, a page to edit/delete a single location, and a page to create a new location.

This post will focus on creating the map page. Our flow will consist of loading the page, retrieving a list of locations from our API and populating a list will eventually link to a page to update/delete them.

Let’s start setting up our project! Our layout will be handled via Bootstrap. To manage our front-end dependencies, we will us Bower. To install Bower, open a command line and type

npm install -g bower

Once Bower is installed, you can then install Bootstrap and AngularJS by typing:

bower install bootstrap --save
bower install angular --save

At the time of this writing, this will install AngularJS 1.6.2 and Boostrap 3.3.7 into a www directory. These should do just fine for our particular project.

Within that www directory, you’ll want to create a blank HTML template with our Bootstrap and AngularJS files named index.html

<html>
<head>
 <!-- jQuery -->
 <script src="lib/jquery/dist/jquery.js"></script>

 <!-- Angular 1.6.2 -->
 <script src="lib/angular/angular.js"></script>

 <!-- Boostrap 3.3.7 -->
 <link rel="stylesheet" href="lib/bootstrap/dist/css/bootstrap.min.css">
 <script src="lib/bootstrap/dist/js/bootstrap.min.js"></script>

 <script src="js/app.js"></script>
</head>

<body ng-app="LocationApp">
 
 <div ng-controller="LocationCtrl" class="container">
 
  <div class="row" ng-repeat="location in locations">
   <div class="col-md-3">{{location.name}}</div>
   <div class="col-md-4">{{location.description}}</div>
  </div>
 </div>
</body>
</html>

Our last piece to setup will be our app.js file. This will contain the reference to our app (LocationApp) and our first controller (LocationCtrl).

(function () {
  'use strict';

  angular.module('LocationApp', [])
   .controller('LocationCtrl', function($scope, $http) {
    // Using Angular's $http module, we can retrieve the Location results
    $http.get('http://www.yourapi.com/locations')
     .then(function(result) {
      // Once the data is retrieved, set it to $scope.locations. This variable directly relates to the locations variable in the ng-repeat in the html
      $scope.locations = result.data;
     });
   });
}());

That is all that is needed to pull data from an API and display it on the front-end of your choosing. This practice can be used with public APIs as well. For example, you can use the OpenWeather API.

Leave a Reply

Your email address will not be published. Required fields are marked *