Search code examples
restapi-design

restful sub-object best practices for GET method


I'm facing with a frequent restful api design issue, and i'm not sure about what to do. Actually i can't find any best practice/clue to know how to proceed...

for GET routes, for example, I have : api/v1/posts/1/ which returns a JSON representation of the resource with id: 1 :

{
    "id": 1,
    "title": "test",
    "id_author": 1,
    "id_category": 2
}

with sub-objects such as author, category...

To present my data on the frontend (actually Nuxt3/VueJS with pinia stores), I need to show author name, avatar, and category label (and potentially others single sub-objects). I don't know if :

  • I can/have to return author details + category details in the response to save 2 calls :
{
    "id": 1,
    "title": "test",
    "id_author": 1,
    "author": {
        "id": 1,
        "firstname": "nico",
        "lastname": "dupond"
    },
    "id_category": {
        "id": 2,
        "category": "news"
    }
}
  • or if i have to make 2 more calls to get author details and category details (but i need to get the first api response to call the 2 others in async mode and wait for their returns to show data on the page)
  • is it better to load all categories and users data at the start of the app and then get them in the built lists (acceptable because we have few users & categories)? But what about the data freshness / missing user in list (if i return sub-object my response will be bigger but consistent and up-to-date)?
  • a mix of 1st and/or 2nd and/or 3rd solution ?

What do you think about these solutions? I think it depends on the context of the frontend, but i think that a good api does not have to depend on the frontend app because it will be potentially exposed to many others app... Is there a golden rule for restful APIs on that topic ?

thank you for your help :)


Solution

  • By default, always load the entire tree.

    Using reference ids (or preferably navigable links) is, in essence, an optimisation. If you do find that loading the entire tree causes API performance problems (you probably will) or freshness problem then prune the tree down where needed.

    Starting with a pruned tree is a premature optimisation which is bad