Requests library is one of the important aspects of Python for making HTTP requests to a specified URL. This article revolves around how one can make PATCH request to a specified URL using requests.patch() method. Before checking out the PATCH method, let’s figure out what a Http PATCH request is –
PATCH Http Method
PATCH is a request method supported by HTTP used by the World Wide Web. It is used for modify capabilities. The PATCH request only needs to contain the changes to the resource, not the complete resource. This resembles PUT, but the body contains a set of instructions describing how a resource currently residing on the server should be modified to produce a new version. This means that the PATCH body should not just be a modified part of the resource, but in some kind of patch language like JSON Patch or XML Patch. PATCH is neither safe nor idempotent.
How to make Patch request through Python Requests
Python’s requests module provides in-built method called patch() for making a PATCH request to a specified URI.
Syntax –
requests.patch(url, params={key: value}, args)
Example –
Let’s try making a request to httpbin’s APIs for example purposes.
Python3
import requests # Making a PATCH request # check status code for response received # success code - 200 print (r) # print content of request print (r.content) |
save this file as request.py and through terminal run,
python request.py
Output –
When to use PATCH method ?
The PATCH method is a request method supported by the HTTP protocol for making partial changes to an existing resource. The PATCH method provides an entity containing a list of changes to be applied to the resource requested using the HTTP URI. The list of changes are supplied in the form of a PATCH document. If the requested resource does not exist then the server may create the resource depending on the PATCH document media type and permissions. The changes described in the PATCH document must be semantically well defined but can have a different media type than the resource being patched. Frameworks such as XML, JSON can be used in describing the changes in the PATCH document.
PUT vs PATCH
The main difference between the PUT and PATCH method is that the PUT method uses the request URI to supply a modified version of the requested resource which replaces the original version of the resource whereas the PATCH method supplies a set of instructions to modify the resource. If the PATCH document is larger than the size of the new version of the resource sent by the PUT method then the PUT method is preferred.