Alex Rivera | Logout

What's the best way to handle a REST API's 'create' response in Backbone.js

Asked 2011-05-21T13:15:26.393
12

I'm using backbone.js to interact with a REST API that, when posting to it to create a new resource, responds with a status of 201, a 'Location' header pointing to the resource's URI, but an empty body.

When I create a new model at the moment, its successful, but the local representation of the model only contains the properties I explicitly set, not any of the properties that would be set on the server (created_date, etc.)

From what I understand, Backbone would update its representation of the model with data in the body, if there were any. But, since there isn't, it doesn't.

So, clearly, I need to use the location in the Location header to update the model, but what's the best way to do this.

My current mindset is that I would have to parse the url from the header, split out the id, set the id for the model, then tell the model to fetch().

This seems really messy. Is there a cleaner way to do it?

I have some influence over the API. Is the best solution to try to get the API author to return the new model as the body of the response (keeping the 201 and the location header as well)?

Thanks!

Edit
Report

1 Answer

7

Sounds like you will have to do a little customization. Perhaps override the parse method and url method of your model class inherited from Backbone.Model.

The inherited functions are:

url : function() {
  var base = getUrl(this.collection);
  if (this.isNew()) return base;
  return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + this.id;
},
parse : function(resp) {
  return resp;
},

and you could try something like:

parse: function(resp, xhr) {
    this._url = xhr.getResponseHeader('location')
    return resp
}
url: function() {
    return this._url
}
answered 2011-05-23T21:36:54.070

Your Answer