长版
对于某些人(包括我自己)来说,构建 REST API 过程中最痛苦、最令人头疼的部分之一是确定每个资源及其随附端点的名称。
当然,这取决于个人喜好;有些事情是受到社区鼓励的。例如,大多数人,包括我,都会将他们的资源名称复数:
GET /notifications
POST /posts
然而,在某些情况下,复数似乎并不正确。考虑以下示例,其中user
本质上代表登录的用户,而不是整个users
资源:
仅与经过身份验证的用户相关的端点
// Phone Verification
POST /user/phone/request
POST /user/phone/resend
POST /user/phone/verify
// User creation based on authenticated and verified phone
POST /user
// Update authenticated user's profile
PUT /user
// Delete the authenticated user
DELETE /user
// Add/remove the authenticated user's profile image
POST /user/image
DELETE /user/image
// Update the authenticated user's device token
PUT /device/token
访问整个用户资源的端点
GET /user
GET /user/{id|self}
在上面的例子中,对我来说,feels就像单数一样user
资源名称更适合在大多数端点上给出,user
指的是经过认证的user
,不是整个数据库users
。但是,另一方面,有GET /user
返回所有用户似乎完全错误......
结果,我现在左右为难user
and users
- 在我看来,两者都有强有力的论据,但非常欢迎其他人对此事的看法......
简洁版本
TLDR - 简而言之,请考虑以下两个端点:
// Get all users
GET /users
// Update the authenticated user's device token
PUT /user/device
以上两点在我看来都是正确的。上面的问题是我不可能两者兼得user
and users
,我认为必须是其中之一。
困境;我为什么要使用user
当资源引用整个用户数据库时?我为什么要使用users
当资源仅指经过身份验证的用户时?
我无法理解这个问题...有人对此有什么想法吗?或者,更好的是,我提出的端点结构的替代解决方案?
Update
经过一番深入思考,我想出了一个替代解决方案,但我仍然不是 100% 确定,因为我不太热衷于使用auth
资源名称。
考虑一下:
// auth = authenticated user
// users = users collection
POST /auth/request
POST /auth/resend
POST /auth/verify
POST /auth
PUT /auth
DELETE /auth
POST /auth/image
DELETE /auth/image
PUT /auth/device/token
GET /users
GET /users/{id}