Whether you are an API developer or tester, you must understand the difference between PUT and PATCH http methods. It is also a frequently asked interview question. Let’s understand PUT and PATCH in details.
An HTTP PUT method is used to primarily update the resource information but it also can be used to create a new resource (Depends on API development) if requested resource is not available. If PUT request is made to update resource, it should return 200 (OK) and 204 (No Content) status code. If PUT request is made to create a new resource, it must return a status code 201( Created).
When a PUT request is sent to server, request body is used to replace existing resource at server if available or created new resource if not available. Since PUT is either replacing or creating a resource on server, you may need to pass a full body of request which requires more bandwidth. Also a GET request is hit first to check existence of resource.
An HTTP PATCH method is used to update information partially or completely (May be) of already existing resource at server and produces a new version of resource with updated information. It is different from PUT as PUT updates/replace complete information of resource while PATCH updates some information of resource. It returns 200 (OK) and 204 (No Content) status code.
A PATCH method is not safe method as it operations on modification of data. It is also non-idempotent but can be made idempotent.
As per RFC-5789:
The difference between the PUT and PATCH requests is reflected in the way the server processes the enclosed entity to modify the resource identified by the Request-URI. In a PUT request, the enclosed entity is considered to be a modified version of the resource stored on the origin server, and the client is requesting that the stored version be replaced. With PATCH, however, the enclosed entity contains a set of instructions describing how a resource currently residing on the origin server should be modified to produce a new version.
An example is as below:
Suppose, server stores a student details (Information representation in JSON as an example) as:
You hit a PUT request to a student id say 123 with full body. First resource with given ID will be searched. If found, old resource information at server will be replaced by new one else, will be created a new resource on server. But if you want to update some data like firstName only, you should use patch and send only required information to be updated. Ideally it should throw a proper error message if request respurce is not found at server.
More about API Testing in upcoming posts. Stay tuned.
If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.