如何为非 CRUD 的“命令"设计 REST API像激活和停用资源? [英] How to design REST API for non-CRUD "commands" like activate and deactivate of a resource?

查看:49
本文介绍了如何为非 CRUD 的“命令"设计 REST API像激活和停用资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我决定问这个问题之前,我已经搜索了很长时间的答案,但没有找到满意的答案.(例如 最好的 SOAP/REST/RPC Web API 示例?你为什么喜欢它们?它们有什么问题?)

Before I decided to ask this question I have searched quite a long for the answer but I haven't found any satisfactory. (e.g. Examples of the best SOAP/REST/RPC web APIs? And why do you like them? And what's wrong with them?)

问题其实很简单.我有一个名为 Account 的对象/资源.我的 REST API 支持所有带有 GET、POST、PUT 和 DELETE 的 CRUD,并具有正确的错误处理、状态代码等.

And the problem is actually quite simple. I have an object/resource named Account. My REST API supports all CRUDs with GET, POST, PUT and DELETE already with proper error handling, status codes etc.

此外,我想公开一个 API(命令")来激活和停用选定的帐户资源.即使isActive"是帐户的属性,我不想只使用整个帐户的 CRUD 中的更新.

Additionally however I want to expose an API ("command") to activate and deactivate selected Account resource. Even if the "isActive" is a property of the Account I don't want to use just the Update from my CRUD of the whole Account.

我知道很容易违反 REST 原则并使用这样的设计进行 RPC 样式设计:

I know it is easy to violate REST principles and make RPC style design with such design like this:

PUT/api/account/:accountId/activate

PUT /api/account/:accountId/activate

PUT/api/account/:accountId/deactivate

PUT /api/account/:accountId/deactivate

那么这个用例的最佳解决方案是什么?

So what is the best solution for this use case?

我目前的想法是像这里提议的那样使用 PUT 和 DELETE 动词(将其视为子资源)http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api#restful:

My current idea is to use PUT and DELETE verbs like this (to treat it as a sub-resource) as proposed here http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api#restful:

PUT/api/account/:accountId/isActive//用于激活

PUT /api/account/:accountId/isActive // for activate

DELETE/api/account/:accountId/isActive//用于停用

DELETE /api/account/:accountId/isActive // for deactivate

您的解决方案是什么?

推荐答案

为您要修改的功能想出一个名词如何 - 在本例中为状态".这将成为父实体的子资源.因此,对于您的情况,我会按如下方式对 URI 进行建模:

How about coming up with a noun for the feature you want to modify - 'status' in this instance. This would then become a sub resource of the parent entity. So for your case I would model the URI as follows:

/api/accounts/{accountId}/status

如果更新"语义是幂等的,那么 PUT 将是最合适的,否则就需要是一个 POST(例如,如果涉及随机数并被服务无效).实际负载将包含新状态的描述符.

If the 'update' semantics are idempotent then PUT would be most appropriate, else that would need to be a POST (e.g if nonces are involved and are invalidated by the service). The actual payload would include a descriptor for the new state.

请注意,我将帐户"设为复数,因为您可以拥有多个帐户,但状态是单数,因为您的帐户只能有一个状态.

Note, I pluralized 'accounts' since you can have multiple of those, but status is singular since your account can have only one state.

这篇关于如何为非 CRUD 的“命令"设计 REST API像激活和停用资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆