REST API Best Practice
As a general rule of thumb, should you always provide the same data for a resource back, if in one form it is an array, and the other is just that one resourse?
For example, if I have courses.
I could have a
/course
GET route that gets me back all of the courses for the user
I could have a /course/:id
GET route that gets me back a specific course
Should the /course
response contain an array of /course/:id
responses?
Think of a dashboard, where all of the user courses are displayed (/course
route is used). I am unsure if I should only return what the page uses, or everything?
Thanks!11 Replies
So for example, I have a card like this for each course. Currently my
/course
route is only returning the owner name, course name, code, and member count. This is the only spot this route will be used, so I think it is ok? Once the user actually clicks this course, the /course/:id
route will be used to get all of the details for that course.
hi again
@caxco93 hey 😆
first of all, if you want good practices then your endpoints should be in plural for each resource.
yeah you have several options here. what you say is indeed a way to go. if you are sure indeed you will only end up using that endpoint there you can leave it like that.
however, in theory, you have 2 other options.
1. add the ability to specify which fields you want for each resource. that way you can do something like
/resources?fields=id,name,code,owner_name
. this is basically one of the things GraphQL aims to solve (not recommending you to use it. i'm just stating it)
2. create 2 different endpoints. 1 for your homepage where you get just a bunch of the fields you need e.g /homepageResources
and then another endpoint that returns all the fields as usual eg /resources
however you can see how the option 1 seems more robust. the solution you propose and the solution 2 I propose are probably only good if you want to ship fast. in theory the option 1 here is the "acceptable" response
but yeah you always have to question yourself. do you want to ship or do you want to make lots of abstractions that you will only end up using oncemandatory xkcd
ah damn I should do plural here
/courses
and /courses/:id
are much better
Did not think of option 1, that is definitely smart'
So many choices, but I guess if I do not do option 1 there is no need for me to change to option 2yeah if you are certain you will just use it for that page then just go ahead
small technical debt if you ever end up needing to add a new endpoint
At the moment I am 80% sure - so I guess if I need to change it in the future I will create option 1
Yep exactly
for different fields or w/e
Appreciate the help!!
😉