PUT vs POST vs PATCH in REST

This is a common question that might arise during a backend API Developer interview. Let’s clarify what each operation does and what are the differences and similarities between them.

What does PUT method do in REST

What RFC 2616, § 9.6 says,

The PUT method requests that the enclosed entity be stored under the supplied Request-URI.

If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be

considered as a modified version of the one residing on the origin server.

That means PUT method can be used to create or update a resource at a particular client defined URL 

When multiple PUT requests to the same URL issued, the results will be the same. 

Let’s clear this with an example

Let’s say you have an inventory management system and you want to create an item in store. The request URL will be something like this.

PUT /resources/<new_item>

Now if you need to update the same item request URL will be like below

PUT /resources/<existing_item>

What is POST method in REST

 What RFC 2616, § 9.5 says,

The POST method is used to request that the origin server accept the entity enclosed in the

request as a new subordinate of the resource identified by the Request-URI in the Request-Line.

This means the POST method can be used to create a resource at a particular server defined URL. In other words it will create a child resource at the defined URL. 

From the inventory store example above, 

If you want to create a new item, the request URL is something like below.

POST /questions

If you want to update an existing item, the request URL is something like below

POST /questions/<existing_item>

If multiple POST requests to the same URL, will create a different child resource each time, resulting in multiple child resources. 

What is PATCH method in REST

According to RFC 5789:

The PATCH method requests that a set of changes described in the request entity be applied to the resource identified by the Request-URI.

Which means the PATCH method can be used to update part of the resource.

So if POST and PUT can both be used to create or update a resource, What is the difference between them?

PUT

POST

Idempotent operation which means

multiple PUT operation to the same URL

will have same result

Non idempotent operation which means multiple

POST oprations to the same URL will have different

results

Can be used to create or update

resource when client already know

the URL beforehand

Can be used to create or update resource

when client doesn't know the URL beforehand


If PUT and PATCH can both be used to update or resource, what is the difference between them?

PUT

PATCH

Idempotent operation

Can either be idempotent or not idempotent

Send whole the entity in

PUT request body

Send only fields which needs to be updated in

PATCH request body



Post a Comment

1 Comments