Did you know that according to the Internet Assigned Numbers Authority, there are 39 different HTTP methods?? 🤯 As a newcomer to coding, I've only been working with a handful of the more common methods like GET, POST, PATCH, and DELETE.
Recently, I learned about the PUT method. Similar to PATCH, PUT updates data, but there are some important differences between the two.
PUT is used to update an entity's data completely. PUT overwrites the entire entity if it already exists, and creates a new resource if it doesn't. What this means is that when working with PUT, you will need to send details for the entire resource, or you will replace the resource only with what you've sent in your PUT request.
PATCH applies a partial update to the resource, meaning you only need to send the data that you want to update. After sending the PATCH request, that specific piece of information will update, without replacing the entire entity.
What does this look like IRL?
Let's say we have a business that offers customizable meal plans. Below is the data we use to update specific meal plans:
{
"protein": "Flank Steak",
"vegetable": "Asparagus",
"starch": "Brown Rice",
"dessert": "Chocolate Chip Cookie"
}
I need to update the starch on this meal from Brown Rice to Sweet Potatoes. If I use a PUT request and only send "starch": "Sweet Potatoes"
, without the other elements, this is what I'll get in return:
{
"starch": "Sweet Potatoes"
}
If I use a PATCH request only sending "starch": "Sweet Potatoes"
, the response would return:
{
"protein": "Flank Steak",
"vegetable": "Asparagus",
"starch": "Sweet Potatoes",
"dessert": "Chocolate Chip Cookie"
}
Using PATCH, we could also add another item to the meal, like a beverage, by sending only "beverage": "Orange Cranberry Spritzer"
. This will add a "beverage" element to the object instead of replacing the entire entity.
{
"protein": "Flank Steak",
"vegetable": "Asparagus",
"starch": "Sweet Potatoes",
"dessert": "Chocolate Chip Cookie",
"beverage": "Orange Cranberry Spritzer"
}
Happy Coding 💻
Cited Source: https://rapidapi.com/blog/put-vs-patch/
Top comments (0)