Search code examples
jsonsingle-page-application

Should the server respond one JSON for all content data on the page in SPA or is better to split it?


I'm building API for SinglePageApplication, which is handled by Angular in frontend. One thing is not clear to me.
Suppose the web application has detail journal page which displays journal, some articles which belongs to this journal and some cool authors which can be not connected to this journal.
Should I build my API URLs based on each need page content, for example:

from url /api/journal/<journal_id>

send json:

{
"journal": {
       "id": 10,
       "name": "new_journal",
       "articles": [
                      {
                      "name": "cool_article",
                      "id": 42
                       },
                       {
                      "name": "another_cool_article",
                      "id": 43
                       }
                   ]
 },
 "authors": [
        {
           "name": "some_name",
           "id": 42
         },
         {
           "name": "another_name",
           "id": 43
          }
            ]
}

Or I should build my API be based on concrete objects and related objects of them.
With URLs like this:

/api/journals/<journal_id>
/api/authors/

And frontend side build this page with two GET requests for fetching content.
Sorry if my question too broad, I just want to find best practice for building API to SinglePageApplications. Does it have any difference of building API endpoints for external web-apps and what I should do if page need to display more objects, which not belong together? Which of the options above is better?


Solution

  • There isn't really a universal right answer for this. It largely depends on the use case for that data you're fetching. I would say to err on the side of splitting this into multiple requests as it grants you flexibility and efficiency in terms of partial updates to the page. That approach also makes exposing an API to the public much easier in terms of being able to just expose what you already have.

    If you're dealing with a potentially large (an intentionally relative term) number of concurrent requests though, you may build some composites of related data to mitigate that.

    Of course, you could also do a combination of the two as well (first load makes 1 large request, subsequent updates are segmented).