如何设计一个好的RESTFul web api 其中涉及到两个对象?

How to design a good RESTFul web api which involves two objects?

我想知道如何设计一个好的RESTFul api 涉及两个或多个对象?例如,很容易设计一个 api 来获得一本书的info 以及获取作者的信息,例如 /book/1/anthor/1,但是如何获取作者的所有书籍?
1.author/{author_id}/books
2.books/get_by_author?author_id=1
3.books/search?author_id=1
哪一个更好?谢谢~

选项 1 是一个不错的选择。使用作者而不是作者。您的 URL 将如下所示:

/authors/{author_id}/books

嗯,这真的取决于您的用例。 如果您尝试在搜索条件有限的书籍上提供搜索功能,我会选择

GET books?author_id=1&genre=fiction

如果您的搜索条件将来会增加,我会推荐 POST API 这样的

POST books/search
{
   "author_id": 1,
   "genre": "fiction",
   "year": 2012
}

但是,如果您总是要尝试获取特定作者的书籍 "only",请选择

authors/<author_id>/books