Thursday, June 15, 2017

Different HTTP methods : Ideal Use Cases

You can find assertions on the web that say
  • POST should be used to create a resource, and PUT should be used to modify one
  • PUT should be used to create a resource, and POST should be used to modify one
Neither is quite right.

Better is to choose between PUT and POST based on idempotence of the action.

PUT implies putting a resource - completely replacing whatever is available at the given URL with a different thing. By definition, a PUT is idempotent. Do it as many times as you like, and the result is the same. x=5 is idempotent. You can PUT a resource whether it previously exists, or not (eg, to Create, or to Update)!

POST updates a resource, adds a subsidiary resource, or causes a change. A POST is not idempotent, in the way that x++ is not idempotent.

Some APIs like twitter follow rule : Idempotence is not about always returning the same result each time (ex: Twitter).  it just means that issuing the same request multiple times won't produce additional side effects.

By this argument, PUT is for creating when you know the URL of the thing you will create. POST can be used to create when you know the URL of the "factory" or manager for the category of things you want to create.
so: POST /students
or: PUT  /students/10929

When you use POST you are always refering to a collection, so whenever you say:
               POST /students HTTP/1.1
you are posting a new user to the users collection.

If you go on and try something like this:
              POST /students/john HTTP/1.1
It will work, but semantically you are saying that you want to add a resource to the john collection under the students collection.


The PATCH method is the correct choice when you're updating an existing resource - with few properties. PUT should only be used if you're replacing a resource in it's entirety

 In summary
  • POST to a URL creates a child resource at a server defined URL.
  • PUT to a URL creates/replaces the resource in its entirety at the client defined URL.Generally used when id is known.
  • PATCH to a URL updates part of the resource at that client defined URL.
For UPSERT operation
one should use PUT

DELETE : It can return the following

●  200 OK, if the resource is deleted successfully and there is something to tell the client.
●  202 Accepted, if the request is accepted but not deleted yet. This response should include some indications. Kind of batch delay , or if deletion takes time or resource marked for deletion and actual deletion happens later...
●  204 No Content,  if the resource is deleted successfully and there is nothing to tell the client.
●  in subsequent following ‘delete’ request return  404 , if resource doesn’t exists and it’s already deleted.

No comments: