pytest-api/apiclient/client.py

45 lines
1.4 KiB
Python

import sys
import requests
from requests import RequestException
from requests_oauthlib import OAuth2Session
def api_client(call_dict, verify_cert=False, oauth=False):
method = call_dict["method"]
url = call_dict["url"]
headers = call_dict["headers"]
body = call_dict["body"]
if oauth:
client = OAuth2Session(token=call_dict["token"])
else:
client = requests.Session()
client.cookies.clear()
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