我认为关键是评论是否被帖子资源“包含”。请记住,RESTful url 应该是永久链接,因此在所有场景下,特定评论的终点不得更改。听起来它已包含在内,因此 url 模式可以将评论嵌套在帖子中。如果不是这种情况(例如,评论可能会移动到另一个帖子,如果嵌套会更改网址),那么您需要一个更扁平的结构,其中包含帖子资源引用的 /comment/{id} 网址)。
关键是如果它是一个 RESTful “超媒体 API”,那么它就像网络一样,它会不断链接到嵌套或引用的资源。它不依赖于客户端必须理解 REST 模式或关于什么端点保存引用或包含的特殊知识
资源。
http://blog.steveklabnik.com/posts/2012-02-23-rest-is-over
如果“评论”是“帖子”资源下的资源:
([httpVerb] /url)
得到一个帖子:
[get] /posts/{id}
body has a couple options - either it contains the full deep comments array
(depends on how much data, chat pattern)
{
id:xxx,
title:my post,
comments: [...]
}
... or it just contains the post resource with a url reference to the comments e.g.
{
id: xxx,
title: my post,
commentsUrl: /posts/xxx/comments
}
could also have an option like this (or other options to control depth):
[get] /posts/{id}?deep=true
获取帖子中的 cmets 集合:
[get] /posts/{id}/comments
returns 200 and an array of comments in the response body
为帖子创建评论:
[post] /posts/{id}/comments
body contains json object to create
returns a 201 created
在帖子下编辑评论:
[patch|post] /posts/{id}/comments/{id}
body contains json object with subset of fields/data to update
returns a 200
替换帖子:
[put] /posts/{id}/comment/{id}
body contains json object to *replace*
returns a 200
如果每个帖子有大量 cmets,您还可以考虑分页模式:
{
id: xxx,
title: myPost,
pages:6,
commentsUrl:/posts/xxx/comments/page/1
}
然后:
/posts/{id}/comments/pages/{pageNo}
{
nextPage: /posts/xxx/comments/2,
pages:7,
comments:
[ { ...,...,}]
}
每个页面都会引用下一页、页面计数和该页面的 cmets 数组。如果您使用分页模式,那么数组中的每个评论都会有一个指向单个评论的引用 url。
如果您发现自己在 url 中添加了一个操作,那么您可能做错了什么。好读:http://blog.steveklabnik.com/posts/2011-07-03-nobody-understands-rest-or-http