[英]REST API: Should single API have multiple responsibilities?
We have classified goods website where we do not have login but users can view products listed by other users.我们有分类商品网站,我们没有登录但用户可以查看其他用户列出的产品。 To view details of other users, they have to provide their contact details.要查看其他用户的详细信息,他们必须提供他们的联系方式。 To verify if user has provided the correct mobile number, we send back OTP code to the number.为了验证用户是否提供了正确的手机号码,我们将 OTP 代码发送回该号码。 The API flow looks like: API 流程如下所示:
POST /api/lead/ POST /api/lead/
{
"stockId": 123,
"mobile": 9890384328
}
Response of API if "mobile" is already verified (Response code: 200):如果已验证“移动”,则 API 的响应(响应代码:200):
{
"sellerName": "xyz",
"sellerMobile": "+123232312",
"sellerAddress": "21, park street, new york"
}
Response if "mobile" is NOT already verified (Response code: 403):如果“移动”尚未验证,则响应(响应代码:403):
{
"OTP verification required. OTP is sent to the mobile number."
}
Request Payload:请求有效载荷:
{
"stockId": 123,
"mobile": 9890384328,
"otp": 1234
}
It sends back seller details in response if OTP is correct.如果 OTP 正确,它会发回卖家详细信息作为响应。 If OTP provided is not correct, the response is:如果提供的 OTP 不正确,则响应为:
{
"Incorrect OTP."
}
I see few issues in this API design:我在这个 API 设计中看到了几个问题:
Can someone suggest which approach is better?有人可以建议哪种方法更好吗?
Simple answer: no .简单的回答:没有。
It is called single responsibility principle for a reason.它被称为单一责任原则是有原因的。
Allowing for more than one responsibility in the your public API means that the API "endpoint" has to understand the different responsibilities to "dispatch" to the "correct" implementation for each of these aspects.在您的公共 API 中允许多个责任意味着 API“端点”必须了解不同的责任,以便“分派”这些方面中的每一个的“正确”实现。 Or you allow your dual-responsibility API design to corrupt your implementation by having a single thing providing that implementation.或者您允许您的双重职责 API 设计通过提供该实现的单一事物来破坏您的实现。
And beyond that: when you have different responsibilities, the range of OK/error return codes simply turns more complicated.除此之外:当你有不同的职责时,OK/error 返回码的范围会变得更加复杂。 That simply makes "everything" harder.这只会让“一切”变得更加困难。 For you to write tests - but also for the clients using your API.为您编写测试 - 也为使用您的 API 的客户编写测试。
In your case, the user does:在您的情况下,用户执行以下操作:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.