HTTP - PUT vs PATCH
Published 2020-02-23
Photo by eberhard grossgasteiger on Unsplash
The HTTP method PUT
is used quite often to perform let the server know that you're performing an update operation. PATCH
is also used for updates, but not in the same way as PUT
. Let's dig a little deeper...
TL;DR
PUT
replaces the entire object at the resource location.
PATCH
just updates the provided fields on the object and leaves any other fields untouched.
PUT
Let's assume there's a user jdahmer
object stored at location /users/id123
. This was created with the following POST:
POST /users
{
"username": "jdahmer",
"favorite_treat": "ice-cream",
"favorite_thing": "torso"
}
Now if we GET /users/id123
we should get back...
{
"id": "id123",
"username": "jdahmer",
"favorite_treat": "ice-cream",
"favorite_thing": "torso"
}
So what if we wanted to update jdahmer's favorite treat to gummy bears using a PUT command?
PUT /users/id123
{
"favorite_treat": "gummy bears",
}
Now if we GET the user again...
GET /users/id123
{
"favorite_treat": "gummy bears"
}
Where are the other fields? PUT replaces the entire object at the resource location, so if we just pass "favorite_treat", we lose the other fields from the object.
Let's rewind and pretend we undid the last PUT to get the original user object.
GET /users/id123
{
"id": "id123",
"username": "jdahmer",
"favorite_treat": "ice-cream",
"favorite_thing": "torso"
}
Now do PUT the correct way, passing the complete and entire user object with updated fields.
PUT /users/id123
{
"id": "id123",
"username": "jdahmer",
"favorite_treat": "gummy bears",
"favorite_thing": "torso"
}
Getting the user should return what we expected.
GET /users/id123
{
"id": "id123",
"username": "jdahmer",
"favorite_treat": "gummy bears",
"favorite_thing": "torso"
}
But what if we wanted to update only the fields that we pass in the body and leave the rest of the object intact?
PATCH
PATCH is the answer in this case.
Let's see the original user again.
GET /users/id123
{
"id": "id123",
"username": "jdahmer",
"favorite_treat": "ice-cream",
"favorite_thing": "torso"
}
Now jdahmer actually likes gummy bears over ice-cream.
PATCH /users/id123
{
"favorite_treat": "gummy bears",
}
And the user object is now...
GET /users/id123
{
"id": "id123",
"username": "jdahmer",
"favorite_treat": "gummy bears",
"favorite_thing": "torso"
}
Once more
PUT
is for doing full updates.
PATCH
is for doing incremental updates.
Happy coding 👩💻
#http