The last lesson showed you how to update a complete resource using the PUT method. This lesson covers a similar method named PATCH.
PATCH vs. PUT
The PATCH and PUT HTTP methods do similar things: They are both used to update resources. However, there is a distinct difference between how they function: A PUT method updates the whole resource even if some fields don't change, whereas the PATCH method will partially update a resource based on the fields you pass in.
If you only need to update a single field, you can use a PATCH instead of a PUT, and the server will only update the field that was changed, helping to reduce typing, transfer, and processing time. Let's elaborate on this with an example. Say you have a task with ID 85 and the resource currently looks like this:
{
"id": 85,
"userId": 3,
"name": "anything you want",
"description": "anything you want",
"createdAt": 1612023016000,
"updatedAt": 1612023016000,
"completed": false
}
You want to update this task to mark it as completed. If you were to use PUT, the request would need to include all the required fields - even the ones that are not changing:
{
"userId": 3,
"name": "anything you want",
"description": "anything you want",
"completed": true
}
If you opt to use PATCH, the request becomes a lot more succinct, like so:
{
"completed": true
}
This is much more efficient. It is worth setting up PATCH functionality for your APIs.
Making the PATCH Request
Now, let's get you started by making an actual PATCH request:
Step 1: As usual, go ahead and open up a new tab.
Step 2: Set the method to PATCH and pick a task to update.
Step 3: Change the ID in the URL to match the task you picked:
http://demo.codingnomads.co:8080/tasks_api/tasks/85
Step 4: Toggle the completed field to either true or false in the above JSON and paste it into the HTTP body section of Postman.
Step 5: Send the request and confirm it was updated.
Learn by Doing
Location: http://demo.codingnomads.co:8080/tasks_api/tasks
- Use PATCH to update at least two existing tasks.
- Only update one or two fields each time.
Summary: Postman PATCH Request
PATCH and PUT do similar things. They are both used to update resources on a server. However, there is a fundamental difference between how the server handles these requests. For PUT, the server requires that you send all the required fields for the resource, and it updates the entire resource. For PATCH, the server only asks you to send the fields you want to change, updating them accordingly.