What's the difference between POST, PUT and PATCH for RESTful APIs?
Developers often get a bit confused about the type of verb to use and when to use it while dealing with web development and HTTP specification. With most applications on the internet being CRUD(Create, Read, Update, Delete) developers must learn how to match HTTP verbs to these actions.
It is not surprising that most people think that PUT and PATCH are allies that do the same thing. However, the reality is far more complex, especially when it comes to overlapping functionality and other complications. Actually, PUT and PATCH might be doing the same thing of updating a resource at a location, but they do it differently. Therefore, to understand more about these verbs, let’s dive deep into HTTP specification and identify the subtle differences between these three.
- POST - This method always creates a new resource on the server. Its a non-idempotent request, As an example, POST /api/v1/users creates a new user record in the given API and if a user hits same requests 2 times it would create another new instance if there is no constraint. It is used to indicate the server to create and store the resource you are sending. Think about it like an INSERT query in SQL which always creates a new record in database.
- PUT - first identifies the given resource from the URL and if it exists, it then replaces the existing resource, otherwise a new resource is created. PUT request is idempotent i.e. hitting the same requests twice would update the existing record (No new record created). In PUT method the resource id is decided by the client and provided in the request url. When the target resource exists it overwrites that resource with a complete new body. That implies that HTTP.PUT method is used to CREATE or UPDATE a resource. Http put method is like a MERGE query in SQL which inserts or updates a record depending upon whether the given record exists.
- PATCH - partially updates a resource into the server mapped by the provided data. Http patch method is like an UPDATE query in SQL which sets or updates selected columns only and not the whole row.
Summary
Now that you have a better understanding of these HTTP methods (POST,PUT and PATCH), you will probably make the best choice when designing a RESTful API or a new web application. Understanding these subtle differences will help improve your experience when integrating and creating cooperative apps.
Note: keep in mind this is a very simplified description of this operations in a RESTful API
Kudos 🙌👌👌
Welldon Chioma