robjbrain
138
1
Lumen

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

Posted 8 months ago by robjbrain

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?

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.