Alexander Mills
Alexander Mills

Reputation: 99980

Backbone - built-in REST capability

I am confused by Backbone's built-in REST capability. I was under the impression that Backbone models, upon a model.save(), would automatically append the value identified by idAttribute to the end of the urlRoot. But I see a lot of examples online, like the one below, where the application imperatively appends the the id to the url. Why is that? Which one is better?

An example using RequireJS:

  define(function(require) {
        var Backbone = require('Backbone');

        return Backbone.Model.extend({
            urlRoot: 'http://rest-service.guides.spring.io/greeting',
            url: function() {
                return this.urlRoot + '?name=' + this.id;
            }
        });
    });

Upvotes: 1

Views: 46

Answers (2)

Trace
Trace

Reputation: 18859

When applying REST, the id is typically the unique identifier of an item that is contained by a collection (expressed in plural). The url /greeting/id doesn't seem to make a lot of sense to me.

Parameters sent via the query string (behind the question mark) serve as filters to the collection that is currently queried.

Upvotes: 1

Akos K
Akos K

Reputation: 7133

Backbone assumes that you were following some common REST practices while you were designing your REST API.

For instance, an API which updates a user should be exposed as:

PUT /users/:id

rather than

PUT /users?id=:id

Of course there are some edge cases when you must rewrite the default URL function but, in general, leaving it as is means you were following the best practices while designing your REST API.

One case I can think of when rewrites are necessary is when a sub-resource is identified by multiple IDs:

PUT /apps/:appId/schedules/:scheduleId

then the url function will be:

url: function () {
    return this.urlRoot + '/' + this.appId + '/schedules/' + this.id
}

Upvotes: 2

Related Questions