
The requests module can be used to issue a REST API request.
- DELETE request
- GET request
- PATCH request (this article - typically used to update an existing resource)
- POST request (typically used to create a new resource)
- PUT request (typically used to update an existing resource)
Here is how you can make a PATCH request.
#!/usr/bin/python3
import requests
requests.patch(
"http://www.example.com/api",
headers={ "Content-Type": "application/json" },
data={"foo": "hello world"}
)
Or, more commonly, like this.
#!/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