Andrii_Sushko Andrii_Sushko - 2 months ago 22
reST (reStructuredText) Question

REST API for main page - one JSON or many?

I'm providing RESTful API to my (JS) client from (Java Spring) server.
Main site page contains a number of logical blocks (news, last comments, some trending stuff), each of them has a corresponding entity on server. Which way is a right one to go, handle one request like

/api/main_page/ ->
{
news: {...}
comments: {...}
...
}


or let the client do a few requests like

/api/news/
/api/comments/
...


I know in general it's better to have one large request/response, but is this an answer to this situation as well?

Answer Source

I think in general multiple requests can be justified, when the requested resources reflect parts of the system state. (my personal rule of thumb, still WIP).

i.e. if a news gets displayed in your client application a lot, I would request it once and reuse it wherever I can. If you aggregate here, you would need to request for it later, maybe some of them never get actually displayed, and you have some magic to do if the representation of a news differs in the aggregation and /news/{id}-resource. This approach would increase communication if the page gets loaded for the first time, but decrease communication throughout your client application the longer it runs. The state on the server gets copied request by request to your client or updated when needed (Etags, last-modified, etc.).

In your example it looks like /news and /comments are some sort of latest or since last visit, but not all. If this is true, I would design them to be a resurce as well, like /comments/latest or similar. But in any case I would them only have self-links to the /news/{id} or /comments/{id} respectively. Then you would have a request to /comments/latest, what results in a list of news-self-links, for what I would start a request only if I don't already have that news (maybe I want to check if the cached copy is still up to date).

It is also possible to trigger the request to a /news/{id} only if it gets actually displayed (scrolling, swiping).

Probably the lifespan of a news or a comment is a criterion to answer this question. Meaning the caching in the client it is not that vital to the system, in opposite of a book in an Book store app.