Senior
What is an idempotent operation and which REST methods are idempotent?
sobes.tech AI
Answer from AI
An idempotent operation is an operation that can be performed multiple times in succession with the same result and without side effects after the first call. That is, a repeated call will not further change the system's state.
In the context of REST API, the following methods are considered idempotent:
- GET — retrieving a resource does not change the server's state.
- PUT — updating a resource with the same data multiple times results in the same state.
- DELETE — deleting a resource multiple times after the first call does not change the state (the resource is already deleted).
- HEAD, OPTIONS, TRACE — are also considered idempotent as they do not change the state.
Example:
// Example of an idempotent PUT request in Go
func updateUser(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPut {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// Parse the request body and update the user
// Repeated calls with the same data will not change the state
}