Requests - HTTP PATCH Method - Python Examples


HTTP PATCH is used to send a request to apply specific modifications to the resource identified by given URL.

In Python Requests library, requests.patch() method is used to send a PATCH request to a server over HTTP. You can also send additional data in the PATCH request as keyword arguments.

Syntax

The following is the syntax to send a PATCH request.

requests.patch(url, data=None, **kwargs)

where

ParameterDescription
urlURL for the new Request object
dataDictionary, list of tuples, bytes, or file-like object to send in the body of the Request.
**kwargsOptional arguments that request takes.

requests.patch() returns a requests.Response object. It contains all the data and properties like response content, headers, encoding, cookies, etc.

Example

Let us send a PATCH request to the server, get the response, and print out response headers.

Python Program

import requests

response = requests.patch('/',
            data = {'apple':'25', 'banana':'33'})
print(response.headers)

Output

{'Content-Type': 'text/html; charset=UTF-8', 'Content-Length': '10600', 'Connection': 'keep-alive', 'Date': 'Thu, 11 May 2023 11:50:09 GMT', 'Server': 'Apache', 'Link': '</wp-json/>; rel="https://api.w.org/", </wp-json/wp/v2/pages/1>; rel="alternate"; type="application/json", </>; rel=shortlink', 'Vary': 'Accept-Encoding', 'Content-Encoding': 'gzip', 'X-Cache': 'Miss from cloudfront', 'Via': '1.1 093d516f7a216e2d93a34013516b0ba6.cloudfront.net (CloudFront)', 'X-Amz-Cf-Pop': 'HYD50-C3', 'X-Amz-Cf-Id': '37kF4m9AG_MMAEqBeCXSF8ujZ5XZI1cBBI1OUQqAaUd3o3MvCBTrAg=='}

Summary

In this Python Tutorial, we learned about HTTP PATCH in requests module.