I got asked about the difference with PUT
and PATCH
in my interview earlier which made me write this article about the difference between the two.
In the context of APIs, both PATCH and PUT are HTTP methods used to update resources, but they are used in slightly different ways.
Example in Python using requests:
import requests
import json
url = 'https://api.example.com/resource/123'
data = {'key': 'new_value'}
response = requests.put(url, data=json.dumps(data), headers={'Content-Type': 'application/json'})
print(response.status_code)
Example in Python using requests:
import requests
import json
url = 'https://api.example.com/resource/123'
data = {'key': 'new_value'}
response = requests.patch(url, data=json.dumps(data), headers={'Content-Type': 'application/json'})
print(response.status_code)
In summary, use PUT when you want to update a resource by providing the full representation, and use PATCH when you want to apply partial modifications to a resource. The choice between them depends on the use case and the level of granularity you need in your updates.
Photo by Douglas Lopes on Unsplash
Also published here.