In our last post, we saw how to get data from a JSON file. In this post, we will see how to make an API call to get data. We will still be using ‘$http’, ‘$q’ & ‘promise’ and also learn error handling while making an http call.

The Star Wars API (SWAPI)‘ provides lots of API end-points to fetch star wars data. You can head over to the documentation to get more details. The best part is that there is no complex authentication to get started and who doesn’t like star wars 🙂

This is the fourth post in a series of posts about fetching data in angularjs. Here are the topics covered in this series.

Here is the folder structure. We have added three files to the ‘apiCall’ folder.

API call to get data

API call to get data

As always, let’s start by updating the ‘index.html’ file :

index.html


        Fetching Data In Angularjs
        
  1. Data In Controller
  2. Fetch data stored in a service
  3. Data In A JSON File
  4. API call to get data
  5. Resolve

Changes that we have made :

  • First we add a link to the fourth ‘li’ – ‘API call to get data'(‘/apicall’ is the fourth route we will define).
  • Finally we add two more scripts files – ‘acController.js’, ‘acService.js’.

Next we update the ‘appModule.js’ file.

appModule.js

var fetchDataApp = angular.module( 'fetchDataApp', [
	'ngRoute',
	'dataInControllerCntrl',
	'dataInServiceCntrl',
	'dataInJsonCntrl',
	'apiCallCntrl'
] );
fetchDataApp.config( [ '$routeProvider', function( $routeProvider ) {
	$routeProvider.
	when( '/dataincontroller', {
		templateUrl: 'modules/dataInController/dataInController.html',
		controller: 'dicCntrl'
	} )
	.when( '/datainservice', {
		templateUrl: 'modules/dataInService/dataInService.html',
		controller: 'disCntrl'
	} )
	.when( '/datainjson', {
		templateUrl: 'modules/dataInJsonFile/dataInJson.html',
		controller: 'dijCntrl'
	} )
	.when( '/apicall', {
		templateUrl: 'modules/apiCall/apiCall.html',
		controller: 'acCntrl'
	} );
} ] );

Here is what is going on :

  • First we tell angular that there is one more module called ‘apiCallCntrl’.
  • Next we define our fourth route ‘/apicall’.
  • Lastly we tell angular what html file to use for the view and the controller to be used for this route.

API call to get data

We will start with the service file.

acService.js

fetchDataApp.service( 'acService', function( $http, $q ) {
  var deferred = $q.defer();
  $http.get( 'http://swapi.co/api/starships/9/' ).then( function( response ) {
	  deferred.resolve( response );
  }, function( response ) {
	  deferred.reject( response );
  } );
  return deferred.promise;
} );

The service here is almost similar to the one in our previous post Fetch data from a json file. The two major differences are :

  • First instead of making a call to the JSON file we are making a call to an API.
  • Second we have a second anonymous function inside the ‘then’ method to handle API call failure.

Now let’s have a look at the controller

acController.js

var apiCallCntrl = angular.module( 'apiCallCntrl', [] );
apiCallCntrl.controller( 'acCntrl', [ '$scope', 'acService', function( $scope, acService ) {
  $scope.apiCall = true;
  acService.then( function( response ) {
    $scope.apiSuccess = true;
    $scope.apiCall = false;
    $scope.charJson = response.data;
  }, function( response ) {
    $scope.apiSuccess = false;
    $scope.apiCall = false;
    $scope.charJson = response.statusText;
  } );
} ] );

Again our controller is almost similar to our previous post. But here we are also handling the error part. So here is what is going on :

  • If the promise returns a success, the first anonymous function inside the ‘then’ method is used. And in the function we are setting ‘apiSuccess’ to ‘true’ and then assigning ‘resonse.data’ to ‘charJson’.
  • Incase the promise returns a failure, the second anonymous function inside the ‘then’ method is called. In this function we are setting ‘apiSuccess’ to ‘false’ and then assigning ‘resonse.data’ to ‘charJson’.
  • We will be using the ‘apiCall’ & ‘apiSuccess’ variables and the ‘charJson’ object in our HTML template.

And now finally our HTML

apiCall.html

API call to get data

API end point: http://swapi.co/api/starships/9/

Making API call...

Details of starship 9

  • Name : {{charJson.name}}
  • Model : {{charJson.model}}
  • Starship Class : {{charJson.starship_class}}
  • Cargo Capacity : {{charJson.cargo_capacity}}
  • Length : {{charJson.length}}
Error : {{charJson}}

Alright, here is what’s going on in our HTML :

  • We have three ‘divs’: first one to some text while the API call is happening. Second to show data when API call is a success and third to show an error when the API call fails.
  • The ‘ng-if’ directive is used to decide which ‘div’ to show. The ‘apiCall’ variable is set to true when the module loads and set to false once we get some response from the API call. The ‘apiSuccess’ variable is set to true or false depending on if the API call status.
  • Now if you remember in our controller, we set ‘apiSuccess’ to ‘true’ on successful API call and to ‘false’ on failure.
  • There you go, now go make your own API calls. May the force be with you.

    You can find the code on Github