Rest PUT vs POST

In this post we are going to discuss the differences between Rest PUT vs POST. Everyone has there own opinions on what PUT and POST requests should be able to do however, I have based my view on idempotent.

What is idempotency:

The definition of idempotent is as follows:

An idempotent HTTP method is a HTTP method that can be called many times without different outcomes. It would not matter if the method is called only once, or ten times over. The result should be the same.

PUT is considered idempotent where as POST is not.

Rest PUT vs POST:

So with the above in mind I tend to lean towards the following approach.

  • PUT requests used to create /¬†overwrite a resource
  • POST requests used to create / update an existing resource.

For example:

We would like to initialise the settings of a camera, in this case we would use POST. The reason for using POST is because we will only want to do this the first time a camera is being initialised and subsequent attempts should fail (return 409).

POST: /v1/settings/{cameraId}/initialise

If we would like to update a cameras settings, in this case we would use PUT as we completely overwrite the existing camera settings. Calling the update camera settings n times will have the same result.

PUT: /v1/settings/{cameraId}/ with JSON body

I hope the above explanation has helped you understand the differences between PUT and POST in rest.

Similar Posts:

  1. PUT request example
  2. POST request example
  3. GET request example
  4. Convert Java object to JSON string

References:

  1. What is idempotency
  2. Stackoverflow discussion on PUT vs POST

Leave a Reply