简体   繁体   中英

Structuring and ordering One to Many relationship client side from REST API

I'm having a bit of trouble wrapping my head around how I could pull a one to many relationship from a REST API and then display it all on a page using Javascript on the client-side.

As an example let's say I have posts and categories . I want my Page to display a list of categories, with the title and description of each post underneath it

Category 1
  - Post 1
  - Post 2
  - Post 3
Category 2
  - Post 4
  - Post 5

I'm trying to figure out how to structure my API and then organize the data. Would the best approach be to structure the API so that we hit:

/categories/ID/posts

To get a list of posts per categories? Or maybe just add a category filter to the posts endpoint itself, as in:

/posts?category=ID

Then on the client side, I would make a request to /categories/ to get a list of the categories, and make a single request for each one to get a list of posts for each.

Or would it be better to simply have an endpoint at /posts/ (or even /all/ which I've seen some places) that already organizes the data by category by grouping them together. I know that this is not RESTful, but is it the best approach? On the client side I would then just iterate through the list and group accordingly.

I think that the first option is the way to go, my only concern is that this can turn into a LOT of requests. If there are a dozen categories or more, I would have to make an individual request for each one, plus the initial one, at least 13. This seems pretty wasteful. The advantage is that once I get all the data this way, it's trivial to break it up and organize it into sub-views on the client side. So I'm wondering if there's another best practice way to handle this that I'm not seeing.

Every approach has pros and cons.

First approach: make a request for every category

These are a lot of requests but it can used to call and display categories one by one: let's assume the visualization of a category and its post list occupi the whole user screen: you could start by making a request for the first category and display it (so the user has something to look at without having to way all the data), then you make an API call for the second and so on..

The second approach is better if you are not passing a lot of data because you make only 1 request.

To recap:
One request for every category :

  • many requests
  • lightweight requests
  • Can display first category without waiting all data

One complete request :

  • Only one request
  • Request can be heavy for the server to process
  • Client display all categories together

Which one is better depends a lot on the specific situation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM