我正在研究一个REST API
并且我正在尝试了解如何处理分层资源。
背景
让我们从一个简单的例子开始。在我的 API 中,我有用户、用户个人资料和评论。
- 用户必须关联一个用户配置文件(一个用户配置文件只对应一个用户)
- 用户可能有关联的评论(评论仅对应一个用户)
用户的资源表示应该是:
User: {
"u1": "u1value", // User's attributes
"u2": "u2value",
...
"links": [{
"rel": "profile",
"href": "http://..." // URI of the profile resource
}, {
"rel": "review",
"href": "http://..." // URI of the review resource
}]
}
用户配置文件资源表示应该是:
UserProfile: {
"p1": "p1value", // Profile attributes
"p2": "p2value",
...
"links": [{
"rel": "owner",
"href": "http://..." // URI of the user resource
}]
}
评审资源表示应该是:
Review: {
"r1": "r1value", // Review attributes
"r2": "r2value",
...
"links": [{
"rel": "owner",
"href": "http://..." // URI of the user resource
}]
}
资源 URI 可以是:
http://api.example.com/users/{userid}
: 访问用户资源http://api.example.com/users/{userid}/profile
:访问用户的个人资料资源http://api.example.com/users/{userid}/review
: 访问用户的评论资源
资源创建:创建用户的正确方法是什么?
现在我想创建一个新用户:
POST http://api.example.com/users {"u1": "bar", "u2": "foo"}
我取回了新的用户 ID = 42POST http://api.example.com/users/42/profile {"p1": "baz", "p2": "asd"}
PUT http://api.example.com/users {"u1": "bar", "u2": "foo", links: [{"rel": "profile", "href": "http://api.example.com/users/42/profile"]}
我的担忧:
- 如果在 1 和 2 或 2 和 3 之间出现中断怎么办?
- 在 3) 中,服务器是否应该自动更新http://api.example.com/users/42/profile中的链接以指向正确的所有者?
- 更新链接字段是创建关系的正确方式吗?还是应该跳过第 3 步)让系统根据 URI 约定猜测关系?(我在几本书上读到 URI 应该被认为是不透明的。)