[英]How to handle when REST resources are linked to and extending already existing resources?
我正在構建一個 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."
}
我建議允許“評論”與多個父母(書籍、用戶)相關聯,然后為評論提供規范資源,如下所示:
預訂/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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.