Search This Blog

Friday 2 February 2024

What is the difference between POST, PUT AND PATCH in HTTP?

 PUT is used for creating or replacing resources, POST is used for creating or appending data to resources, and PATCH is used for partially updating existing resources


Features of the PUT method

The PUT method has the following characteristics:


The request URI is used as the resource identifier

The request body contains the entire updated resource

It has idempotency - repeating the same request yields the same result

If the existing resource does not exist, a new one will be created

If an existing resource exists, it will be completely replaced with the contents of the body


// PUT example  

PUT /Studeant/1

{

  "id": 1,

  "name": "Student",

  "age": 18

}



Features of the POST method

The URI indicates the location of the resource that will handle the request

The request body contains data for creating the new resource

It does not have idempotency - repeating the same request may produce different results

Often used to create new resources

An empty request body may still be valid


// POST example

POST /users  

{

  "name": "Student",

  "age": 21

}

Features of the PATCH method

The PATCH method applies partial modifications to entities of a resource. 

The PATCH method executes the requested changes atomically. 

It means that if the server can't satisfy all the requested changes, 

it doesn't modify the target entity

// PATCH example  

PATCH /Studeant/1

{

  "id": 1,

  "name": "Student",

  "age": 18

}


Action

PUT

PATCH

Request body

Yes

Yes

Response with body Content

No

Yes

Safe

No

No

IDEMPOTENT

Yes

No