O'Reilly logo

RESTful Web Services Cookbook by Subbu Allamaraju

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

10.4. How to Implement Conditional PUT Requests in Servers

Lax implementation or lack of concurrency control for PUT requests can cause lost updates. This recipe shows how to use Last-Modified and/or ETag headers to implement conditional PUT requests in servers for optimistic concurrency control.

Problem

You want to know how to implement concurrency control for PUT requests.

Solution

If the resource does not exist yet and if the server supports resource creation via PUT, create a new resource at the URI specified by the client. If the server does not support resource creation, return 404 (Not Found) status to the client.

If the resource exists, take the following steps:

  • If the client does not include If-Unmodified-Since and/or If-Match headers, return 403 (Forbidden). Explain why in the body of the response.

  • If the supplied If-Unmodified-Since or If-Match headers do not match the actual modified date-time and ETag values of the representation on the server, return error code 412 (Precondition Failed).

  • If the clients submits a conditional PUT request and if the supplied conditions match, update the resource, and return 200 (OK) or 204 (No Content).

    You can optionally include updated Last-Modified and/or ETag headers provided the response also includes a Content-Location header with the URI of the updated resource.

See Figure 10-1 for an overview of the checks that the server needs to make.

Figure 10-1. Implementing conditional PUT requests

To make this work, make sure to include Last-Modified ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required