I was browsing around wikipedia on REST, reading specifically the section on REST APIs
Reading the different ways to treat elements from collections I read that POST is not generally used.
How does that work in practice? When successful REST APIs are developed, when it comes to elements, does POST just not exist or return an error?
Is there a reasoning behind that I haven’t grasped?
3
According to the RFC for HTTP, which most REST APIs build upon, the meaning of the methods is:
- GET: Retrieve a resource
- POST: Add a sub-entity to a resource
- PUT: Create or replace a resource
- DELETE: Remove a resource
In common usage, POST is also often used to modify a resource by indicating the changes that must be applied.
The main distinction between POST and PUT is that you should use PUT if you already know the exact URI of the resource you are creating, and POST if you only know the collection that will hold the resource.
As for the usage in REST APIs, I would recommend to use POST for adding resources to a collection and for modifying resources piecewise. If neither makes sense, then you should return a 405 (Method Not Allowed) error.
I’ve seen a lot of confusion from people over what POST actually means. It does not mean create, and it does not mean update. POST means “send a message to a resource without the expectation of idempotency”. The other basic HTTP methods are all idempotent: if you do the same thing twice, you get (morally) the same result.
Let’s clarify. When you use POST twice in a row, sending the same message to the same resource, you are nevertheless anticipating different results from the two operations. This can map quite nicely to creation where the server is creating new resource URIs in response to the messages: different URIs, non-idempotent. On the other hand, if the client is making the URI (a common case where you’re modelling a filesystem) then POST is the wrong thing for creation: PUT to the resource you want to create is more typically correct there (and PUTting the same content to the same URI twice results in the same thing: the content exists afterwards at that URI whether or not it existed beforehand).
It is important to realise that REST is not just about simply having collections and values in those collections. It can do much more than that (though in that case you have to do more work to make it all discoverable).
Philosophically, it is a hard question… There are schools of thoughts about REST, and nobody is right or wrong.
The way I develop my rest APIs is simple:
- GET – Read an element
- PUT – Update an element
- POST – create an element
- DELETE – Delete an element
The Wikipedia entry say that PUT can be used for create or replace. Sure it can be done that way, but I find it clearer (and it is subjective) so separate the 2 actions.
It all comes down to a matter of taste.
1