Reputation: 49047
I have created the paths:
POST /books/4/chapters
The Chapter
entity is part of the Book
composition. It can not exist in the system without a book. Now after creating a chapter by posting to the URI above, should I create another set of URIs for the answer resource for updating and getting a particular chapter?
GET /books/4/chapters/6
or GET /chapters/6
?
Remember that once you have the primary key for one level, you usually don't need to include the levels above because you've already got your specific object. In other words, you shouldn't need too many cases where a URL is deeper than what we have above /resource/identifier/resource.
From apigee Web API Design
This GET /chapters/6
would be more true to what the article says, however that also means that you object is not in scope of its parent anymore (since it is part of a composite object of class Book). However I feel that this is better since chapters could be a composition of other objects again meaning that you get long nested URIs
GET /books/4/chapters/5/paragrahps/5
if everything should be in scope of the parent.
What would be the preferred way of doing this
Edit
After more thinking it probably will be the best to have URIs like /books/4/chapters/9
etc since you don't have repositories etc in the code for retrieving a particular feedback without its parent because it is a composite?
Upvotes: 4
Views: 1424
Reputation: 8420
What I would do is definitely the way you mentioned. For example :
/books/4/chapters -- GET : Retrieve full list of chapters of the book
/books/4/chapters/9 -- GET : Retrieve the 9th chapter of book 4.
The important keyword is the of. It's a chapter OF a book and it's totally irrelevant to present it without its book. Just doing /chapters/9
is very unclear. You see it as a full entity, while it really is a subset of a book.
Using the way illustrated over you will have very clear URIs. You a retrieving a specific resource (chapter 9) which is a sub-resource of the other (and thus, you have to be mentioning the "super" resource).
I'd really advise you to take a look at this great presentation by David Zülke, a member of the Symfony team. It's a language-agnostic presentation about REST. More precisely it talks about URIs from 16min~ to 30min~, but the whole presentation is great and worth watching.
I've watched it today, and while I do agree with them, in most cases. There is one thing that I see here. While it might be great to be able to retrieve a chapter by
/chapter/{its id} -- GET
The problem is that, in some cases, you want the 9th chapter of a book, and not necessarily retrieve chapter 238723 (which is unclear that it is the 9th chapter). And in that case, it makes more sense to retrieve it by doing :
/books/4/chapters/9 -- GET
Upvotes: 4