Warm tip: This article is reproduced from stackoverflow.com, please click
entity-relationship rest updates

Update relationship between entities

发布于 2020-04-23 12:04:25

This is how you add a book to a author in my API:

PUT /authors/1/books/1/

I now want to change the book to another author.

How can I do that? I am thinking in the following options.

1- Making /authors and /books both top-level resources. Control what author a book is on using a property on the book, for example authorId: 2. For example, PUT /book/1 and set authorId: 2 in the body with other attributes.

2 - Perform PUT /authors/2/books/1/, changing the existing author's book to 2. With this method I should check if the book already exists. If exists I update the author and the other attributes, if not I would create a new book.

Which would be the best option in term of best practices? Is the second option a nonsense?

Questioner
Mr. Mars
Viewed
49
James 2020-02-09 05:07

Both are uniquely identifiable therefore both should be resources in their own right i.e.

GET /authors/1
GET /books/1

Therefore the second option you suggest IMO seems the most sensible i.e.

PUT /books/1

{ authorId: 2 }