简体   繁体   English

通过REST API设置状态

[英]Setting state through REST API

Is there a convention for exposing a state update function to the API consumer? 是否有向API使用者公开状态更新功能的约定?

I have a /orders endpoint, where each order can have some states eg: 1 - Submitted 2 - Pending 3 - Shipped 我有一个/ order端点,其中每个订单可以具有一些状态,例如:1-提交2-待处理3-已发货

Customers can submit orders, but then staff will eventually have their own GUI to change order state. 客户可以提交订单,但是工作人员最终将拥有自己的GUI来更改订单状态。

I'm wondering, for a particular order eg /orders/123 , would it be better to consume the API using PUT /orders/123 with {state: 2} . 我想知道,对于特定的订单(例如/orders/123 ,最好使用带有{state: 2} PUT /orders/123来使用API​​。

Or would it be better to expose some convenience functions such as GET /orders/pending that would handle setting state for the API consumer? 还是最好公开一些方便的功能,例如GET /orders/pending ,这些功能可以处理API使用者的设置状态?

The common practice is to use GET requests as read-only data access, and PUT requests to set state, updates, and other data write operations. 通常的做法是使用GET请求作为只读数据访问,并使用PUT请求设置状态,更新和其他数据写入操作。

Aside from being common, this practice has the added benefit of being intuitive, and relays the intent of the API and client code that's accessing the API really well. 除了通用之外,这种做法还具有直观的附加好处,并且传达了API和意图很好地访问API的客户端代码的意图。

Note, however, that PUT verb is really meant to replace a resource in full, not for updating any single property of a resource. 但是请注意, PUT动词实际上是要完全替换资源,而不是用于更新资源的任何单个属性。 There's another HTTP verb for that - PATCH - which would be better suited for your case. 还有另一个HTTP动词PATCH更适合您的情况。

Rather than creating yet another copy of HTTP verbs reference, I'd like to refer you to this tutorial , which I found quite excellent and thorough. 我想给您介绍本教程 ,而不是创建HTTP动词引用的另一个副本,我发现它非常出色而透彻。 Take a look at both PUT and PATCH verbs to make a decision for your implementation. 看看PUTPATCH动词,为您的实现做出决定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM