Bootstrap FreeKB - Python (Scripting) - PATCH request
Python (Scripting) - PATCH request

Updated:   |  Python (Scripting) articles

There are several built in modules that are part of the Python Standard Library included with your Python installation, such as os (Operating System) and re (Regular Expression) and sys (System).

The requests module can be used to issue a REST API request.

Here is how you can make a PATCH request.

#!/usr/bin/python
import requests

url      = "http://www.example.com/api"
data     = { "foo": "hello", "bar": "world" }
headers  = { "Content-Type": "application/json" }
response = requests.patch(url, data=payload, headers=headers)

 

Or sometimes you'll have to use "json=payload" instead of "data=payload".

response = requests.patch(url, json=payload, headers=headers)

 

verify=False can be used to ignore SSL issues, such as when using a self-signed certificate. This is like using the --insecure flag in curl.

response = requests.patch(url, json=payload, headers=headers, verify=False)

 

There are a number of different objects that can be used to return useful information.

print(f"response             = {response}")
print(f"response.status_code = {response.status_code}")
print(f"response.ok          = {response.ok}")
print(f"response.content     = {response.content}")
print(f"response.text        = {response.text}")
print(f"response.json        = {response.json()}")
print(f"response.headers     = {response.headers}")

 

Since each API has it's own unique response, the response you get back will different between APIs. However, I typically expect to get some sort of response that let's me know if the request was successful or if it failed.

response             = <Response [200]>
response.status_code = 200
response.ok          = True
response.content     = {"result":{"success":true}}
response.text        = {"result":{"success":true}}
response.json        = {u'result': {u'success': True}}

 

If some issue occurs, you may want to set logging to DEBUG to view the full request and response.

#!/usr/bin/python
import logging

try:
    import http.client as http_client
except ImportError:
    import httplib as http_client

http_client.HTTPConnection.debuglevel = 1
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter ecccd2 in the box below so that we can be sure you are a human.