6

我正在构建一个 REST API,其中有“书籍”和“用户”。他们只能存在一本独特的书。尽管一个用户可以拥有几本书,而不同的用户可以拥有同一本书(或引用相同的书)。用户可以向书籍添加附加信息(例如评级)。

我的问题是:当用户使用自己的设置“扩展”已经存在的 Book 资源时,映射资源的正确方法是什么?

示例:第一次使用的用户没有书,但他们可以创建书。如果这本书不存在,它就会被创建,如果它存在,他们就可以访问它。尽管他们可以向其中添加自己的私人附加信息。

这是正确的方法吗?

//所有具有基本所需信息的书籍都可以在 /books/:id 上找到 示例:/books/1

{
    "id":1,
    "title":"The Empire",
    "description":"Description about the book",
    "serial":1234
}

//如果用户创建书“帝国”(序列号:1234),他们正在扩展现有的书,但他们添加了额外的信息,所以它实际上是一个新的 URL,但指的是书的 ID。

示例:/users/421/books/1/

{
    "id":1,
    "title":"The Empire",
    "description":"Description about the book",
    "serial":1234,
    "rating":5.5,
    "note":"I liked the book but it was too long."
}

甚至:

{
    "book": {
        id":1,
        "title":"The Empire",
        "description":"Description about the book",
        "serial":1234,
    }
    "rating":5.5,
    "note":"I liked the book but it was too long."
}

甚至是像 /users/421/books/1/settings/ 这样的 URL

{
    "rating":5.5,
    "note":"I liked the book but it was too long."
}
4

1 回答 1

4

我建议允许“评论”与多个父母(书籍、用户)相关联,然后为评论提供规范资源,如下所示:

/books/{book-id}

{
"id":1,
"title":"The Empire",
"description":"Description about the book",
"serial":1234
}

一本书的评论/books/{book-id}/reviews

{[
{
"id":1,
"userId":user1,
"bookId":1,
"rating":5.5,
"note":"I liked the book but it was too long.",
"url":http://server/reviews/1
},
{
"id":2,
"userId":user2,
"bookId":1,
"rating":1,
"note":"boo, i didn't like it!",
"url":http://server/reviews/2
}
]}

用户评论/users/{user-id}/reviews

{[
{
"id":1,
"userId":user1,
"bookId":1,
"rating":5.5,
"note":"I liked the book but it was too long.",
"url":http://server/reviews/1
},
{
"id":2,
"userId":user2,
"bookId":1,
"rating":1,
"note":"boo, i didn't like it!",
"url":http://server/reviews/2
},
{
"id":5,
"userId":user1,
"bookId":3,
"rating":2,
"note":"I like to read",
"url":http://server/reviews/5
}
]}

用于审查的规范资源/reviews/{review-id}

{[
{
"id":1,
"userId":user1,
"bookId":1,
"rating":5.5,
"note":"I liked the book but it was too long.",
"url":http://server/reviews/1
},
{
"id":5,
"userId":user1,
"bookId":3,
"rating":2,
"note":"I like to read",
"url":http://server/reviews/5
}
]}

创建新评论可以是用户/评论、书籍/评论或评论资源的帖子,这些 POST 服务的服务器实现会酌情默认用户 ID 或书籍 ID。

url链接的实现有atom:link等一些选择。

此外,请考虑不要将书籍、用户和评论的原始 id 公开给这些服务的客户/消费者,而是将 id 作为 URI 公开。

于 2012-04-24T15:29:23.150 回答