API call to get data

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.

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

apiCall.html

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

<div>

<h4>API call toget data</h4>

<p>

<b>API endpoint</b>:http://swapi.co/api/starships/9/

</p>

</div>

<div ng-show="apiCall">

<b>Making API call...</b>

</div>

<div ng-if="apiSuccess"ng-show="!apiCall">

<p>

<b>Details of starship9</b>

</p>

<ul>

<li>

<b>Name:</b>{{charJson.name}}

</li>

<li>

<b>Model:</b>{{charJson.model}}

</li>

<li>

<b>Starship Class:</b>{{charJson.starship_class}}

</li>

<li>

<b>Cargo Capacity:</b>{{charJson.cargo_capacity}}

</li>

<li>

<b>Length:</b>{{charJson.length}}

</li>

</ul>

</div>

<div ng-if="!apiSuccess"ng-show="!apiCall">

<b>Error:</b>{{charJson}}

</div>

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.