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 :
{
"id": 1,
"title": "test",
"id_author": 1,
"author": {
"id": 1,
"firstname": "nico",
"lastname": "dupond"
},
"id_category": {
"id": 2,
"category": "news"
}
}
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 :)
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