Reputation: 177
Im currently facing the following scenario in designing an api and i'm curious what is the best choice. We have multiple levels in our routes e.g.:
GET group/:id
GET group/type/
The problem here occurs when someone is doing a GET-request on e.g. group/type
, the ../type
is intrepreted as the id. Which does make sense if you consider the GET on group/ only refers to a single group. Then the correct route for the type would be group/:id/type.
However, a group can have multiple types and we need a route to simply query all group types.
What is the restful way of implementing this.
Should one do a GET /grouptypes route or some nasty regex stuff to test if /group/gibberish
is a subroute or id ?
I don't ask for some hacky ways of implementing a solution, i'm just asking what would be the best design choice if we design a restful api.
I am tagging this as Express.js question since we do implement the api in express. Nevertheless i think the above behaviour is what one would expect from a routing mechanism in frameworks of such kind.
Upvotes: 1
Views: 39
Reputation: 7455
I assume you routing code looks like this example, or somewhat very similar to:
...
router.get('/group/:id', middleware, controller, ...);
router.get('/group/type', middleware, controller, ...);
...
So the only thing you need to make it work, just swap these lines with each other:
...
router.get('/group/type', middleware, controller, ...);
router.get('/group/:id', middleware, controller, ...);
...
The reason is that express uses the first matching route among registered routes. Taking that fact, it is quite easy to understand that since request to the /group/type
route matches both schemes - the first registered will be used.
From the REST perspective, having /group/:id
for getting information about particular group is completely good. Also it is completely OK to have some specific routes like /group/total
or /group/stats
or whatever else for getting some general data related to all groups.
I don't know what is the actual functionality of your /group/type
route, but if it is endpoint for getting, for example, stats about types of all groups - that is fine.
Upvotes: 1