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.8. How to Make POST Requests Conditional

Unlike PUT or DELETE, the outcome of a POST request to a resource may not result in any changes to the resource at the request URI. The server may create a new resource (with response code 201) or identify the outcome with a different URI (with response code 303). For these cases, the client will not have a representation and the conditional headers stored locally. This recipe shows how to use links to make such POST requests conditional. You can apply this recipe to make POST requests conditional and nonrepeatable (i.e., used once-only).

Problem

You want to implement POST such that the server can detect and prevent duplicate submission by clients.

Solution

Let clients use a one-time URI supplied by the server via a link for each POST request. Use Recipe 10.9 to generate the one-time URI. This URI contains a token generated by the server that is valid for just one usage of the POST request. Store all used tokens in a transaction log on the server.

When the client submits a POST request, verify whether the token exists in the transaction log. If it does, return response code 403 (Forbidden). Explain why in the body. If not, process the request to return 201 (Created) or 303 (See Other) depending on the outcome. Also store the token in the transaction log.

Discussion

Consider a bank transfer application, where the server needs to transfer a given sum of money from one account to another. The server can employ a controller resource to implement ...

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