1. import requests
  2. import json
  3. import argparse
  4. import sys
  5. def api_request(url, method='GET', data=None, headers=None):
  6. """
  7. Makes an API request to the specified URL.
  8. Args:
  9. url (str): The URL to request.
  10. method (str): The HTTP method (GET, POST, PUT, DELETE, etc.). Defaults to GET.
  11. data (dict): The data to send in the request body (for POST, PUT, etc.). Defaults to None.
  12. headers (dict): The HTTP headers to include in the request. Defaults to None.
  13. Returns:
  14. dict: The JSON response from the API, or None if an error occurred.
  15. """
  16. try:
  17. if method.upper() == 'GET':
  18. response = requests.get(url, headers=headers)
  19. elif method.upper() == 'POST':
  20. response = requests.post(url, headers=headers, json=data)
  21. elif method.upper() == 'PUT':
  22. response = requests.put(url, headers=headers, json=data)
  23. elif method.upper() == 'DELETE':
  24. response = requests.delete(url, headers=headers)
  25. else:
  26. print(f"Unsupported HTTP method: {method}")
  27. return None
  28. response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
  29. return response.json()
  30. except requests.exceptions.RequestException as e:
  31. print(f"API request failed: {e}", file=sys.stderr)
  32. return None
  33. except json.JSONDecodeError as e:
  34. print(f"Failed to decode JSON response: {e}", file=sys.stderr)
  35. return None
  36. def main():
  37. """
  38. Main function to handle command-line arguments and API requests.
  39. """
  40. parser = argparse.ArgumentParser(description="Local utility with API integration.")
  41. parser.add_argument("api_url", help="The base URL of the API.")
  42. parser.add_argument("endpoint", help="The API endpoint to call.")
  43. parser.add_argument("--method", default="GET", help="HTTP method (GET, POST, PUT, DELETE).")
  44. parser.add_argument("--data", help="JSON data to send in the request body.")
  45. parser.add_argument("--headers", help="JSON data to send in the request headers.")
  46. args = parser.parse_args()
  47. url = args.api_url + args.endpoint
  48. method = args.method.upper()
  49. headers = {}
  50. if args.headers:
  51. headers = json.loads(args.headers)
  52. data = None
  53. if args.data:
  54. data = json.loads(args.data)
  55. response = api_request(url, method, data, headers)
  56. if response:
  57. print(json.dumps(response, indent=4)) #pretty print the json
  58. else:
  59. sys.exit(1) #exit with error code if API request fails
  60. if __name__ == "__main__":
  61. main()

Add your comment