New version Angular 9
AngularJS Tutorial - 2, APIs
In this part we will call an API to fill a list through a button.

Download
The source for this part is here: 02_apis.zip.
The samples can be run with Firefox, in general or by running, into the directory,
- If you have Python 2.x: python -m SimpleHTTPServer 8000
- If you have Python 3.x: python -m http.server 8000
- If you have Perl:
- cpan HTTP::Server::Brick # install dependency
- perl -MHTTP::Server::Brick -e '$s=HTTP::Server::Brick->new(port=>8000); $s->mount("/"=>{path=>"."}); $s->start'
- If you are under windows: "C:\Program Files (x86)\IIS Express\iisexpress.exe" /path:%CD% /port:8000
Http Service
To make http queries to services a dependency should be added to our controller: $http.
Real usage
It contains two methods:
- get('url')
- post('url',jsonObject)
The two functions returns a promise that can handle error and succes, with specific
callback functions taking the following parameters
- data: the json content of the response
- status: the http status code (e.g.200)
- headers: the response headers
- config: the configuration (at the moment useless)
for example:
$http.get('http://test/com')
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
The API we will be using
In our test, since we don't have any webservice available we will
use a "fake" rest server. It's composed by several parts (that must all be included!):
- sinon-server.js: That overwrites the XmlHttpRequest see http://sinonjs.org/
- fakerest.min.js: That mimicks a true API server with support
for CRUD operations see https://github.com/marmelab/FakeRest - api-server.js: The implementation for our sample (give it
a look if you want!
Look at the notes to see how it works
The API exposed actually respond to GET requests to the url '/customers'
The object returned contains:
- id
- first_name
- last_name
Show me the data!
Setting up the controller
We will include sinon-server, fakerest and api-server to let the APIs work
Then angular.min and the bootstrap.css file to have a nicer style!
We will create a new application with its controller. The controller, when
loading will create an empty array of customers. Then will declare a
function that will call the "/customers" API retrieving its data and filling
the customers array.
The get function will return asynchronously and will invoke the success callback
passing
- data: The data returned by the API call
- status: The http status code
- headers: The list of headers
- config: The request data
var app = angular.module('customersModule',[]);
app.controller('CustomersController',['$scope','$http',function($scope,$http){
$scope.customers = [];
$scope.loadData = function(){
$http.get(/customers)
.success(function(data, status, headers, config) {
$scope.customers=data;
});
}
}]);
Preparing the visualization
We will set the body with the right module and the controller.
Then we will create a button. The buttons contains the ng-clik attribute.
The function called on the ng-click atribute will be a function inserted
on the $scope by the CustomersController.
A "template" is present to iterate on the all customers. This is declared
through the "ng-repeat" attribute (an Angular directive)
Then all the data inside a single customer is shown
<body ng-app="customersModule">
<div ng-controller="CustomersController">
<button type="button" class="btn btn-default" ng-click="loadData()">Load</button>
<table class="table">
<tr><th>Id</th><th>First Name</th><th>Last Name</th></tr>
<tr ng-repeat="customer in customers">
<td>{{customer.id}}</td><td>{{customer.first_name}}</td><td>{{customer.last_name}}</td>
</tr>
</table>
</div>
</body>
Clicking on the Load button the data will be...hem...loaded!
Notes
FakeRest
FakeRest uses a standard REST flavor, described below.
GET /fooreturns a JSON array. It accepts three query parameters:filter,sort, andrange. It responds with a status 200 if there is no pagination, or 206 if the list of items is paginated. The response contains a mention of the total count in theContent-Rangeheader.
GET /books?filter={author_id:1}&sort=['title','desc']&range=[0-9]
HTTP 1.1 200 OK
Content-Range: items 0-1/2
Content-Type: application/json
[
{ id: 3, author_id: 1, title: 'Sense and Sensibility' },
{ id: 2, author_id: 1, title: 'Pride and Prejudice' }
]
POST /fooreturns a status 201 with aLocationheader for the newly created resource, and the new resource in the body.
POST /books
{ author_id: 1, title: 'Emma' }
HTTP 1.1 201 Created
Location: /books/4
Content-Type: application/json
{ "author_id": 1, "title": "Emma", "id": 4 }
GET /foo/:idreturns a JSON object, and a status 200, unless the resource doesn't exist
GET /books/2
HTTP 1.1 200 OK
Content-Type: application/json
{ id: 2, author_id: 1, title: 'Pride and Prejudice' }
-
PUT /foo/:idreturns the modified JSON object, and a status 200, unless the resource doesn't exist -
DELETE /foo/:idreturns the deleted JSON object, and a status 200, unless the resource doesn't exist