python-snippets/api-client/client.py
2024-07-20 00:54:31 +01:00

40 lines
1.3 KiB
Python

import sys
from requests import RequestException
from requests_oauthlib import OAuth2Session
def api_client(call_dict):
url = call_dict["url"]
headers = call_dict["headers"]
body = call_dict["body"]
client = OAuth2Session(token=call_dict["token"])
method = call_dict["method"]
try:
if method == 'GET':
response = client.get(url, headers=headers, params=body, verify=False)
elif method == 'POST':
response = client.post(url, headers=headers, json=body, verify=False)
elif method == 'PUT':
response = client.put(url, headers=headers, json=body, verify=False)
elif method == 'OPTIONS':
response = client.options(url, headers=headers, json=body, verify=False)
elif method == 'DELETE':
response = client.delete(url, verify=False)
else:
raise ValueError(f"Invalid method: {method}")
except RequestException as e:
print(f"Request failed. Method: {method}, URL: {url}", file=sys.stderr)
print(f"Error details: {str(e)}", file=sys.stderr)
exit(e.response.status_code)
if response.status_code == 200:
return response.json()
else:
return response.status_code, response.reason