Each HTTP request has its own header which tell the server what the request is all about. You can see this by opening developer tools in your browser, heading to the network tab, loading a page and then inspecting each request.
HTTP methods are classified into two types:
- Safe methods: They don’t change anything on the server side.
- Idempotent methods: They produce the same results no matter how many times they are called.
Idempotence catchphrase → Send and send and send my friend, it makes no difference in the end.
Now let’s look at each of these methods:
GET → Fetch a resource from the server.
Example: GET /users/207
Safe: ✅
Idempotent: ✅
POST → Modify/update a resource on the server.
Example: POST /users
Safe: ❌
Idempotent: ❌
PUT → Create a new resource or overwrite if one is present.
Example: PUT /users/207
Safe: ❌
Idempotent: ✅
DELETE → Remove a resource from the server.
Example: DELETE /users/207
Safe: ❌
Idempotent: ✅
PATCH → Apply partial modifications to a resource.
Safe: ❌
Idempotent: ❌
POST vs PUT vs PATCH
There is an excellent StackOverflow post that covers this in detail. Here’s an excerpt from that post →
- POST to a URL creates a child resource at a server defined URL.
- PUT to a URL creates/replaces the resource in its entirety at the client defined URL.
- PATCH to a URL updates part of the resource at that client defined URL.
If the endpoint on the server is idempotent (i.e safe to do the request over and over again) and the URI is address to the resource being updated then we can safely use PUT, else use POST.
PUT will essentially take an object and replace the entire resource at the URI. For example, if we had to update the email of a user, we would send the entire resource:
PUT /users/207
{
name: "Omkar Bhagat",
email: "omkar@bhagat.com", // only updating email in this request
city: "Mumbai"
}
If we only send email (a partial resource) as follows →
PUT /users/207
{
email: "omkar@google.com" // only updating email in this request
}
Then the rest of the properties will have NULL values. That’s where PATCH comes to our rescue.
Reference: https://medium.com/@kumaraksi/using-http-methods-for-restful-services-e6671cf70d4d