Web services 对于具有关联资源的REST服务,正确的URI设计是什么
大家好 我不熟悉REST和Web API。我对如何为我的资源设计URI有点困惑 假设我有一个包含以下资源的域:博客、帖子和用户Web services 对于具有关联资源的REST服务,正确的URI设计是什么,web-services,rest,asp.net-web-api,Web Services,Rest,Asp.net Web Api,大家好 我不熟悉REST和Web API。我对如何为我的资源设计URI有点困惑 假设我有一个包含以下资源的域:博客、帖子和用户 Blog (1) ------ (0..*) Post (0..*) ------ (1) User 一个博客可以有很多帖子,每个帖子都与一个博客相关联。一个用户可以有许多帖子,每个帖子都与一个用户关联 对于博客和用户资源,URI如下所示: GET /blogs - get list of all blogs GET /blogs/{id} - get blog b
Blog (1) ------ (0..*) Post (0..*) ------ (1) User
一个博客可以有很多帖子,每个帖子都与一个博客相关联。一个用户可以有许多帖子,每个帖子都与一个用户关联
对于博客和用户资源,URI如下所示:
GET /blogs - get list of all blogs
GET /blogs/{id} - get blog by id
POST /blogs - create new blog
PUT /blogs/{id} - update blog
DELETE /blogs/{id} - delete blog
GET /users- get list of all users
GET /users/{id} - get user by id
POST /users - create new user
PUT /users/{id} - update user
DELETE /users/{id} - delete user
但是关于邮政资源呢?如何处理关联?我正在考虑以下备选方案——哪些是正确的,为什么
--通过博客获取所有帖子
1. GET /blogs/{id}/posts
or
2. GET /posts?blogid={id}
--在博客中创建新帖子
3. POST /blogs/{id}/posts
or
4. POST /posts (here I would then in the payload send the IDs of the resources this post is associated with. BlogId and UserId)
--按博客和用户获取所有帖子
5. GET /blogs/{id}/posts?userid={id}
or
6. GET /posts?blogid={id}&userid={id}
如果有人能给我指出正确的方向,我将不胜感激。因为帖子总是与博客和用户ID相关联,我会选择选项1、3和5:
GET /blogs/{id}/posts
POST /blogs/{id}/posts
GET /blogs/{id}/posts?userid={id}
您应该问自己的第一个问题是,API真正的RESTful对您来说有多重要?事实上,这比它看起来要实现的要复杂得多
{
"Id" : 1,
"Identifier" : "123's First Blog",
"links" : [
{
"rel": "http://myapi/res/posts",
"href": "http://myapi/blog/1/posts"
},
{
"rel": "http://myapi/res/users",
"href": "http://myapi/user/123"
}
]
}
rel是指向资源的摘要\定义的链接,href应该指向api本身
无论如何,所有这些的要点是,如果您确实想要真正的RESTful,那么就让资源和URI之间的链接决定设计。想想你将如何从一个单一的起点发现每个调用的细节,这个结构应该像通过TDD进行的软件设计一样显示出来
如果你不需要休息,事情就会变得简单得多。只需以最自然的方式为您、您的体系结构和您的开发人员设计API。如果您正确地记录事情,那么这将导致一个更高效的API,并且可以更快地根据它进行开发
马里奥对这个问题的回答是正确的,我也更倾向于那些选项。我只是觉得你应该知道伴随着这样一个决定而来的整个故事
如果这没有意义,或者您想了解更多信息,请发表评论,我会尽力提供帮助:)如果您想进一步了解API中REST的优点和细节,也可以查看此处