Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REST : Return complex nested data vs. multiple calls [closed]

I have a REST api served by NodeJS to an AngularJS fronts.

I work with users :

GET  /api/users  #Returns all users
POST /api/users  #Create  new user

GET   /api/users/:id   #Return a user
PUT   /api/users/:id   #Edit a user
DELTE /api/users/:id   #Delete a user

This is a user :

{
  login : "admin"
  email : "[email protected]"
  pass  : "hashedpassword"
  ...
}

My user can belong to groups

GET   /api/users/:id/groups   #Return the groups of a user

They can also have constraints or can inherits constraints form their groups

GET   /api/users/:id/constraints   #Return the constraints of a user
GET   /api/groups/:id/constraints   #Return the constraints of a group

The problem :

I'm making an admin page, displaying All the users, their groups, their constraints.

Should I :

  1. Make many requests in a for loop in the javascript (Angular) front ?

Something like :

$http.get(/api/users).then(function(result) {
  result.data.forEach(function(user) {
    $http.get('/api/users/'+user.data.id+'/groups).then(function(groups) {
      groups.forEach(function(group) {
        $http.get('/api/groups/'+group.data.id+'/constraints)
      })
    })
  })
})
  1. Create a path /api/users/withConstraintsAndGroups

That would return a big list of all the users with their groups and their constraints.


I find solution 1 to be very nice, maintenable, easy, and generic but I'm affraid of very bad performance

I find solution 2 to be ugly, hard to maintain, hard to code, not generic but with good performance

Which solution should I choose?

like image 962
IggY Avatar asked Jan 07 '16 13:01

IggY


1 Answers

Your question basically boils down to:

Which is better, one big HTTP request, or many small ones?

One thing to keep in mind is the expected network latency (ping time) between your clients and your server. In a high-latency situation with otherwise good bandwidth, many small requests will perform significantly worse than one large one.

Also, having one big request gives you better efficiency for compressing the response, and avoids the overhead of the extra HTTP requests and response headers.

Having said all that, I would still advise you to start with option 1, solely because you stated it is very easy for you to code. And then see if it meets your requirements. If not, then try option 2.

And as a final note, I generally prefer one big request to many small requests because that makes it easy to define each request as a transaction which is either completely applied or rolled back. That way my clients do not run into a state where some of their many small requests succeeded while others failed and they now have an inconsistent local copy of the data my API supplied.

like image 102
Idos Avatar answered Sep 20 '22 16:09

Idos