Chapter8:METHOD SAFETY AND METHOD IDEMPOTENCY

8 METHOD SAFETY AND METHOD IDEMPOTENCY

Before we start with the Create, Update, and Delete actions, we should explain two important principles in the HTTP standard. Those standards are Method Safety and Method Idempotency.
在开始创建、更新和删除操作之前,我们应该解释 HTTP 标准中的两个重要原则。这些标准是方法安全和方法幂等性。

We can consider a method a safe one if it doesn’t change the resource representation. So, in other words, the resource shouldn’t be changed after our method is executed.
如果一种方法不改变资源表示,我们可以认为它是安全的。因此,换句话说,在我们的方法执行后,不应更改资源。

If we can call a method multiple times with the same result, we can consider that method idempotent. So in other words, the side effects of calling it once are the same as calling it multiple times.
如果我们可以多次调用一个方法并得到相同的结果,我们可以认为该方法是幂等的。因此,换句话说,调用一次的副作用与多次调用它的副作用相同。

Let’s see how this applies to HTTP methods:
让我们看看这如何应用于 HTTP 方法:

HTTP Method Is it Safe? Is it Idempotent?
GET Yes Yes
OPTIONS Yes Yes
HEAD Yes Yes
POST No No
DELETE No Yes
PUT No Yes
PATCH No No

As you can see, the GET, OPTIONS, and HEAD methods are both safe and idempotent, because when we call those methods they will not change the resource representation. Furthermore, we can call these methods multiple times, but they will return the same result every time.
如您所见,GET、OPTIONS 和 HEAD 方法既安全又幂等,因为当我们调用这些方法时,它们不会更改资源表示形式。此外,我们可以多次调用这些方法,但它们每次都会返回相同的结果。

幂等(idempotent、idempotence)是一个数学与计算机学概念,常见于抽象代数中。在编程中一个幂等操作的特点是其任意多次执行所产生的影响均与一次执行的影响相同。幂等函数,或幂等方法,是指可以使用相同参数重复执行,并能获得相同结果的函数。

The POST method is neither safe nor idempotent. It causes changes in the resource representation because it creates them. Also, if we call the POST method multiple times, it will create a new resource every time.
POST 方法既不安全也不幂等。它会导致资源表示形式发生变化,因为它会创建它们。此外,如果我们多次调用 POST 方法,它每次都会创建一个新资源。

The DELETE method is not safe because it removes the resource, but it is idempotent because if we delete the same resource multiple times, we will get the same result as if we have deleted it only once.
DELETE 方法不安全,因为它会删除资源,但它是幂等的,因为如果我们多次删除相同的资源,我们将得到与只删除一次相同的结果。

PUT is not safe either. When we update our resource, it changes. But it is idempotent because no matter how many times we update the same resource with the same request it will have the same representation as if we have updated it only once.
PUT也不安全。当我们更新资源时,它会发生变化。但它是幂等的,因为无论我们用相同的请求更新同一资源多少次,它都会具有相同的表示形式,就好像我们只更新了一次一样。

Finally, the PATCH method is neither safe nor idempotent.
最后,PATCH 方法既不安全也不幂等。

Now that we’ve learned about these principles, we can continue with our application by implementing the rest of the HTTP methods (we have already implemented GET). We can always use this table to decide which method to use for which use case.

现在我们已经了解了这些原则,我们可以通过实现其余的 HTTP 方法(我们已经实现了 GET)来继续我们的应用程序。我们始终可以使用此表来决定将哪种方法用于哪个用例。

发表评论