3

I have an existing RESTful API wich can't be changed. Now, i'm working on the webclient.

I would like to use a library like backbone.js (for the first time).

Here is the design of the existing API

1.) GET /persons - Returns the whole collection of persons

2.) GET /persons?p1=a&p2=b (e.g.) - Returns a subset of the complete collection which matches the criteria specified by the query parameters

3.) GET /persons/[id] - Returns a person by id

4.) POST /persons - modifies the collection (e.g. creates a new person) and returns the specific result

Issues:

  • The problem with #1 (and #2): The output format is like this: {size: 1, persons: [{'id': 1, 'firstname': 'foo', 'lastname': 'bar'}]}

  • The problem with #2: how to map such a requst to backbone.js?

Any suggestions?

Tadeck
  • 132,510
  • 28
  • 152
  • 198
kalamar
  • 933
  • 1
  • 11
  • 27

2 Answers2

3

For #1, you would override parse. For example, in your Persons collection you would put the following method:

parse: function(response) {
    return response.persons;
}

You are basically instructing the collection which attribute the models can be found in ('persons' in our case).

For #2, (as previously mentioned) it looks like you'll need to update sync. Hunter provided a good link in his response that should be really helpful.

robmisio
  • 1,066
  • 2
  • 12
  • 20
2

For an API that doesn't follow backbone's exact structure, you usually end up overriding some combination of fetch parse and sync within backbone. Backbone was designed so that overriding these things would be easy, since it's a common need:

Community
  • 1
  • 1
hunterloftis
  • 13,386
  • 5
  • 48
  • 50