Backbone Tutorials

API Integration

Backbone is pre-configured to sync with a RESTful API. Merely create a
new Collection with the url of your useful resource endpoint:

var Books = Backbone.Collection.extend({
  url: '/books'
});

The Collection and Model elements collectively kind a direct
mapping of REST assets utilizing the next strategies:

GET  /books/ .... collection.fetch();
POST /books/ .... collection.create();
GET  /books/1 ... model.fetch();
PUT  /books/1 ... model.save();
DEL  /books/1 ... model.destroy();

When fetching uncooked JSON information from an API, a Collection will
routinely populate itself with information formatted as an array, whereas
a Model will routinely populate itself with information formatted
as an object:

[{"id": 1}] ..... populates a Collection with one model.
{"id": 1} ....... populates a Model with one attribute.

Nonetheless, it is pretty widespread to come across APIs that return information in a
completely different format than what Backbone expects. For instance, think about
fetching a Collection from an API that returns the actual information
array wrapped in metadata:

{
  "page": 1,
  "limit": 10,
  "total": 2,
  "books": [
    {"id": 1, "title": "Pride and Prejudice"},
    {"id": 4, "title": "The Great Gatsby"}
  ]
}

Within the above instance information, a Collection ought to populate utilizing the
"books" array quite than the basis object construction. This
distinction is well reconciled utilizing a parse methodology that
returns (or transforms) the specified portion of API information:

var Books = Backbone.Collection.extend({
  url: '/books',
  parse: function(data) 
});