From time to time I have a discussion with my workmate Carlos Filho and our Architecture team at Infoglobo about the use of POST and PUT when developing RESTful webservices. Such discussion happens because we always get confused on when to use POST and when to use PUT.
The convention I’m going to explain here was not stated by us. It’s a definition made by Leonard Richardson and Sam Ruby in RESTful Web Services (Web services for the real world) published in 2007.
When to use POST
Scenario 1) If the client wants the service to create a resource but the client is not sure how (or don’t know) the resource’s URI is going to look like in advance
... Location: /product/1234 ...
Scenario 2) If the client wants the service to append a resource to a collection but the client is not sure (or don’t know) how the resource’s URI is going to look like in advance
... Location: /surf-boards-catalog/product/1234 ...
Tha’s pretty the same as the first scenario.
When to use PUT
Scenario 1) If the client wants the service to update a resource identified by an URI that the client knows in advance
This is the case where the client is going to use the URI provided by the service. This URI in the one in Location header provided by the service in the response to the POST request that created the resource.
Scenario 2) If the client wants the service to create a resource identified by an URI that the client knows in advance
When it’s the client who will decide how will be the resource’s URI, and not the service, the client should use PUT. In this scenario, of course the service knows the URI’s pattern but it’s the client who will tell the service what will be each one of the variable URI parts.
We had an example at Infoglobo of such scenario. We created a RESTful web service that will be consumed by iPhone, iPad and Android applications developed by Infoglobo. The first time the application is opened it will issue a request to this RESTful service to tell it there is a new device where the application was installed.
Each device is identified by an token and each application has a specific identification depending on the device’s operational system. This way we defined that each applilcation would issue a PUT request such as…
In this scenario the service doesn’t know in advance all device tokens and we decided not to register or create all applications and platforms in advance. All of it is done in this single request. Although the service knows the URL pattern it’s up to the client to define how the final URI looks like.
Hope that helps you when designing your next RESTful web service.