大家好,
我是REST和Web API的新手.我对如何为我的资源设计URI感到困惑.
鉴于我有一个包含以下资源的域:博客,帖子和用户.
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}