pytest-api/apiclient/client.py

45 lines
1.4 KiB
Python
Raw Normal View History

2024-07-20 10:47:11 +00:00
import sys
2024-07-20 16:35:15 +00:00
import requests
2024-07-20 10:47:11 +00:00
from requests import RequestException
from requests_oauthlib import OAuth2Session
2024-07-20 16:35:15 +00:00
def api_client(call_dict, verify_cert=False, oauth=False):
2024-07-20 10:47:11 +00:00
method = call_dict["method"]
2024-07-20 10:47:11 +00:00
url = call_dict["url"]
headers = call_dict["headers"]
body = call_dict["body"]
2024-07-20 16:35:15 +00:00
if oauth:
client = OAuth2Session(token=call_dict["token"])
else:
client = requests.Session()
client.cookies.clear()
2024-07-20 10:47:11 +00:00
try:
if method == 'GET':
response = client.get(url, headers=headers, params=body, verify=verify_cert)
elif method == 'POST':
response = client.post(url, headers=headers, json=body, verify=verify_cert)
elif method == 'PUT':
response = client.put(url, headers=headers, json=body, verify=verify_cert)
elif method == 'OPTIONS':
response = client.options(url, headers=headers, json=body, verify=verify_cert)
elif method == 'DELETE':
response = client.delete(url, verify=verify_cert)
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