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

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


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.


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.


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


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 ‘’ 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 ‘’ to ‘charJson’.
  • We will be using the ‘apiCall’ & ‘apiSuccess’ variables and the ‘charJson’ object in our HTML template.

And now finally our HTML


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