korolvs
korolvs

Reputation: 118

Moving child resource to another parent in REST

I have a REST service.

And now I need to have functionality to move some child resources from one parent to another, for example move a book from one author to another.

My variant is:

POST /api/books/x/moveto/y

But how to create such architect the RESTful way?

Upvotes: 5

Views: 1547

Answers (2)

Josh M.
Josh M.

Reputation: 27811

I think in this case updating the author as suggested in Cassio's answer is a good solution. For less obvious "actions" I use PATCH endpoints. Consider archiving a book:

PATCH /api/books/{bookId}/archive

The intent is obvious -- archive the book with this identifier. For more complex actions, include a body or use a query string parameter. For instance, moving a book out of one category and into another (assume a book can have 0-many categories):

PATCH /api/books/{bookId}/move

{
    fromCategoryId: 100,
    toCategoryId: 200
}

Or:

PATCH /api/books/{bookId}/move?fromCategoryId=100&toCategoryId=200

In the end, IMO, what matters most is readability and consistency. There is not necessarily a "right" way to do this sort of thing.

Upvotes: 1

cassiomolin
cassiomolin

Reputation: 131027

From a REST point of view, URLs should be used to locate the resources rather than expressing operations. To express operations, the existing HTTP verbs should be used.

Looks like your "move" operation is all about replacing the author of the book.

And the PUT method seems to be the way to go:

4.3.4. PUT

The PUT method requests that the state of the target resource be created or replaced with the state defined by the representation enclosed in the request message payload. [...]

So, you can have an endpoint like the following:

PUT /api/books/{bookId}/author

And the request payload will contain a representation of the new author.

Upvotes: 4

Related Questions