import requests
import json
import argparse
import sys
def api_request(url, method='GET', data=None, headers=None):
"""
Makes an API request to the specified URL.
Args:
url (str): The URL to request.
method (str): The HTTP method (GET, POST, PUT, DELETE, etc.). Defaults to GET.
data (dict): The data to send in the request body (for POST, PUT, etc.). Defaults to None.
headers (dict): The HTTP headers to include in the request. Defaults to None.
Returns:
dict: The JSON response from the API, or None if an error occurred.
"""
try:
if method.upper() == 'GET':
response = requests.get(url, headers=headers)
elif method.upper() == 'POST':
response = requests.post(url, headers=headers, json=data)
elif method.upper() == 'PUT':
response = requests.put(url, headers=headers, json=data)
elif method.upper() == 'DELETE':
response = requests.delete(url, headers=headers)
else:
print(f"Unsupported HTTP method: {method}")
return None
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
return response.json()
except requests.exceptions.RequestException as e:
print(f"API request failed: {e}", file=sys.stderr)
return None
except json.JSONDecodeError as e:
print(f"Failed to decode JSON response: {e}", file=sys.stderr)
return None
def main():
"""
Main function to handle command-line arguments and API requests.
"""
parser = argparse.ArgumentParser(description="Local utility with API integration.")
parser.add_argument("api_url", help="The base URL of the API.")
parser.add_argument("endpoint", help="The API endpoint to call.")
parser.add_argument("--method", default="GET", help="HTTP method (GET, POST, PUT, DELETE).")
parser.add_argument("--data", help="JSON data to send in the request body.")
parser.add_argument("--headers", help="JSON data to send in the request headers.")
args = parser.parse_args()
url = args.api_url + args.endpoint
method = args.method.upper()
headers = {}
if args.headers:
headers = json.loads(args.headers)
data = None
if args.data:
data = json.loads(args.data)
response = api_request(url, method, data, headers)
if response:
print(json.dumps(response, indent=4)) #pretty print the json
else:
sys.exit(1) #exit with error code if API request fails
if __name__ == "__main__":
main()
Add your comment