Cover image by Marco Verch Professional Photographer and Speaker, on Flickr
Many questions arise when we start designing an API, especially if we ...
For further actions, you may consider blocking this person and/or reporting abuse
Thanks for the article! :)
I was creating an API just by myself for the first time recently and I stumbled upon this problem.
I had a
files
table, and a bunch of entities likereports
,comments
which had a relationship tofiles
. Now, there would not be a problem with a root/files
endpoint, but unfortunately, the permission to the files was only granted if you had permission to its parent (in this case aReport
,Comment
etc.). So I've created a/comments/:commentId/files/:fileId
. And then a similar one forReports
. And everything was cool, but...Later on, another entity needed a relationship to
files
. And another one. So I had to create another*/files/:fileId
endpoints, which would've been almost identical to the other ones (it just checked for different permissions).This felt totally wrong, those endpoints were a redundant duplication. So I've refactored it to have just a root
/files/:fileId
endpoint. The only downside of this was that I had to determine theFile
parent, so I needed to check all of the potential parent tables. But aside from that - it was a lot more readable and pleasant to use!What would be your approach to this problem?
Glad you liked the article! :D
About your problem.
I have no idea how your resources are linked together, but from what you are saying you're fighting a bit with redundancy.
One possible solution could be the creation of a root resource for
files
that handles all CRUD actions and then add nested resources for read actions only that just respond with redirects to the correspondingfiles
resource.That way you could read
/comments/1235/files
when needed and only had to implement something like/files?comment=1235
that is the target of the redirect.You're right, it's hard to say without the whole context :) But I won't describe the whole thing here as I don't think it's the right place to discuss complicated problems :D
Anyways, your article gave me some insight on the problem and some ideas on different approaches with nested resources :) Also thanks for the suggestion in your comment as I didn't think about this kind of solution!
You are welcome :)
Hmmm... I think having nested url of 3 depth can be challenging and documentation can be a pain so I usually stick with only 2.
But I do agree that having nested url has it's place for certain reasons.
Yes, I think 2 would be a good rule of thumb, but when your data forms a tree it's okay to go deeper.