2023-11-08 18:07:21 +03:00
|
|
|
import requests
|
2023-11-09 18:58:51 +03:00
|
|
|
from logger import get_logger
|
|
|
|
|
|
|
|
logger = get_logger(__name__)
|
2023-11-08 18:07:21 +03:00
|
|
|
|
|
|
|
|
2023-11-09 18:58:51 +03:00
|
|
|
def get_api_call_response_as_text(
|
|
|
|
method, api_url, params, search_params, secrets
|
|
|
|
) -> str:
|
2023-11-08 18:07:21 +03:00
|
|
|
headers = {}
|
|
|
|
|
2023-11-09 18:58:51 +03:00
|
|
|
api_url_with_search_params = api_url
|
|
|
|
if search_params:
|
|
|
|
api_url_with_search_params += "?"
|
|
|
|
for search_param in search_params:
|
|
|
|
api_url_with_search_params += (
|
|
|
|
f"{search_param}={search_params[search_param]}&"
|
|
|
|
)
|
2023-11-08 18:07:21 +03:00
|
|
|
|
|
|
|
for secret in secrets:
|
|
|
|
headers[secret] = secrets[secret]
|
|
|
|
|
2023-11-09 18:58:51 +03:00
|
|
|
try:
|
2024-01-23 04:33:48 +03:00
|
|
|
if method in ["GET", "DELETE"]:
|
|
|
|
response = requests.request(
|
|
|
|
method,
|
|
|
|
url=api_url_with_search_params,
|
|
|
|
params=params or None,
|
|
|
|
headers=headers or None,
|
|
|
|
)
|
|
|
|
elif method in ["POST", "PUT", "PATCH"]:
|
|
|
|
response = requests.request(
|
|
|
|
method,
|
|
|
|
url=api_url_with_search_params,
|
|
|
|
json=params or None,
|
|
|
|
headers=headers or None,
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
raise ValueError(f"Invalid method: {method}")
|
|
|
|
|
2023-11-09 18:58:51 +03:00
|
|
|
return response.text
|
2024-01-23 04:33:48 +03:00
|
|
|
|
2023-11-09 18:58:51 +03:00
|
|
|
except Exception as e:
|
|
|
|
logger.error(f"Error calling API: {e}")
|
2024-01-23 04:33:48 +03:00
|
|
|
return None
|