Martín Coll
Martín Coll

Reputation: 3794

Concurrency checking on a REST API?

I'm starting a REST API to make a Web Application.

Most web sites tell you to delete resources issuing a DELETE HTTP request to an URI like /{resource}/{resource-id}. I'm afraid of deleting some resource that could have been updated since I retrieved it, or even a wrong resource.

Would it be OK to require sending the resource's timestamp along with the request? I haven't seen it anywhere, but I think it could be really useful. It would check for concurrency and prevent deleting random resources without even retrieving them before.

Upvotes: 3

Views: 1499

Answers (1)

user647772
user647772

Reputation:

Use the HTTP headers of ETag and If-Match with your DELETE request.

The client GETs the resource:

GET /things/42

The server responds:

200 OK
ETag: "foo-bar-baz"

The client wants to DELETE the resource:

DELETE /things/42
If-Match: "foo-bar-baz"

Case 1: thing 42 was not changed, it can be deleted. The server responds:

410 Gone

Case 2: thing 42 was changed and does not match the ETag: "foo-bar-baz". It is not deleted, the server reponds:

409 Conflict

Variant:

You can also use the headers Last-Modified and If-Unmodified-Since instead of or in addition to ETag and If-Match.

See the Hypertext Transfer Protocol (HTTP) Status Code Registry.

Upvotes: 7

Related Questions