python-snippets/api-client/client.py
2024-07-19 23:45:11 +01:00

36 lines
1.1 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)
elif method == 'POST':
response = client.post(url, headers=headers, json=body)
elif method == 'PUT':
response = client.put(url, headers=headers, json=body)
elif method == 'OPTIONS':
response = client.options(url, headers=headers, json=body)
elif method == 'DELETE':
response = client.delete(url)
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)
return response.content, response.status_code