REST APIs with Complex Requests

I am not quite clear on how to create complex requests with REST API on the backend and basic web application on the frontend. Let's say I have a table user

that is related to a table user_group

:

user.group_ref => user_group.id

      

If I do GET

on /api/v1/user/1/?format=json

, it does something like SELECT * FROM users WHERE id = 1

. Right, okay, now ... how about if I wanted JOIN

with mine user_group

where to user.group_ref = user_group.id

instantly access the data at user_group

. I don't want to make an additional request to go and get this data.

Maybe I got the whole idea ... Is there an easier way?

+3


source to share


3 answers


REST is a collection of conventions. It does not provide automatic request matching, so you need to define the service endpoint and then implement it to return whatever you want.

In your case, the typical way to construct a URL would be something like:

GET /groups/(groupid)/users

      

That is, "give me all the users in this group." As an alternative:



GET /users?group=(groupid)

      

Which is less "RESTful" in style, but does not overly advertise the group as a top-level resource.

In any case, Backbone does not provide an OOTB way to populate collections from more complex resources. For anything other than a simple CRUD, you will have to implement the service call yourself, or create a separate read-only collection url

that will appear in your service. Something like:

var UserGroupCollection = Backbone.Collection.extend({
  url: function() { return "groups/" + this.options.groupId + "/users"; }
});

var group = new UserGroupCollection({groupId:1});
group.fetch();

      

+1


source


The REST API can be implemented separately, without any interface relationship, it can be designed as you need it.

In your case, if you always get user_group.id with a query for a user, then you must constantly change your SQL to JOIN statements: SELECT * FROM users WHERE id = 1 JOIN user_group WHERE user.group_ref = user_group.id.

If you want both requests with and without user_group info. You can create two REST methods, like (GET / api / v1 / user / 1? Format = json) without group information, and (GET / api / v1 / userwithgroup / 1? Format = json) for those who have information about the group.



And on Magin, you can have two different Models representing the two.

If you don't have millions of users in the table, the SQL with group information should be pretty fast and it would be easier to just have group information with it.

0


source


There is a python library called slubmber ( http://slumber.in/ ) that is built on top of requests for the explicit purpose of the REST API.

0


source







All Articles