Skip to content

Usage with Backbone.js

jeff-h edited this page Nov 5, 2015 · 5 revisions

For a full example app which uses Backbone.Marionette to connect to a RESTful Drupal instance, check out todo_restful.

Implement parse()

RESTful.module responses contain a data element, which contains the model data. Backbone.js by default assumes the entire response will be the model data, so your models and collections will need to implement the parse() method, to give Backbone just the response's data element.

Example user resource response
{
  "data": [
    {
      "id": "5",
      "label": "Barry",
      "self": "http://drupalsite.local/api/v1.1/users/5",
      "mail": "[email protected]"
    }
  ],
  "self": {
    "title": "Self",
    "href": "http://drupalsite.local/api/v1.1/users/5"
  }
}
Example Backbone.js model
var User = Backbone.Model.extend({
  urlRoot : function() {
    return restBasePath + '/api/users/';
  },

  // Modify the response that RESTful.module gives us.
  parse: function(response, options) {
    if (response.data) {
        // RESTful sends models buried inside a data element.
        return response.data[0];
    }
    return response;
  },

});
Example Backbone.js collection
var Users = Backbone.Collection.extend({
  
  model: User,
  
  url : restBasePath + '/api/users/',

  // RESTful sends models buried inside a data element.
  parse: function(response) {
    return response.data;
  },
});

Add auth headers to every request

You'll need to add headers to every request that needs to be authenticated. When using cookie auth, you'll want to add the X-CSRF-Token and when using token auth you'll need to add the access_token.

This can neatly be achieved in Backbone using underscore's _.wrap method. For example:

      // Make all our AJAX requests send the access_token in a header.
      self.addAuthHeaders({
        'X-CSRF-Token': self.get("X-CSRF-Token")
      });

or

      // Make all our AJAX requests send the access_token in a header.
      self.addAuthHeaders({
        'access_token': self.get("access_token")
      });

and

  addAuthHeaders: function(authHeaders) {
    Backbone.ajax = _.wrap(Backbone.ajax, function(originalFunc, params) {
       params.headers = _.extend({}, params.headers, authHeaders);
       return originalFunc(params);
    });
  }
Clone this wiki locally