robjbrain's avatar

If you want multiple models from your API, do you make multiple http requests or just one?

I've been trying to Google this to find past experiences and best practices without much luck. So I thought i'd ask here.

When you have a page which requires lots of bits of data, do you make one request or multiple? For instance, imagine you have a dashboard which has four cards which list the 5 most recent categories, posts, comments and users

Do you do one request which knows what to return from the controller:

created () {
    axios.get('/api/dashboard').then(response => {
        this.categories = response.data.categories;
        this.posts = response.data.posts;
        this.comments = response.data.comments;
        this.users = response.data.users;
    }
}

Or do you do 4 separate requests?

created () {
    axios.get('/api/categories?limit=5&orderBy=recent').then(response => {
        this.categories = response.data;
    }
    axios.get('/api/posts?limit=5&orderBy=recent').then(response => {
        this.posts = response.data;
    }
    axios.get('/api/comments?limit=5&orderBy=recent').then(response => {
        this.commments = response.data;
    }
    axios.get('/api/users?limit=5&orderBy=recent').then(response => {
        this.users = response.data;
    }

}

The latter seems more in line with how Laravel is setup with its resource controllers.

However it's also likely to be slower and more resource intensive. If you have auth and guards and other such things they need to be run 4 times for each request.

I only say slower because presumably the lag, if there is any, is between the client and the server, rather than the server and its db. I guess the second example could also be faster.

So how do you do it and why? If there are predefined best practices could someone suggest some terminology that makes it easier to research through Google?

0 likes
1 reply
Vilfago's avatar

I don't have developper experience on this topic, but from an user point of view, I'll go with the latter (4 requests).

Maybe a bit slower (disadvantage), but you can show a loading icon on each dashboard, and you have the following advantages :

  • if a request fail (for some reason), only one dashboard is blank, but you can show data
  • user can refresh only the dashboard he wants, which give a better user experience (and you still can add a "refresh all" button)

And probably easier to maintain for you.

Please or to participate in this conversation.