1. import requests
  2. import time
  3. import logging
  4. import json
  5. # Configure logging
  6. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
  7. def monitor_api(api_url, interval=60, expected_response_code=200):
  8. """
  9. Monitors the state of an API endpoint.
  10. Args:
  11. api_url (str): The URL of the API endpoint to monitor.
  12. interval (int): The interval (in seconds) between checks.
  13. expected_response_code (int): The expected HTTP response code.
  14. Returns:
  15. None. Logs status and errors.
  16. """
  17. while True:
  18. try:
  19. response = requests.get(api_url)
  20. response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
  21. if response.status_code == expected_response_code:
  22. logging.info(f"API endpoint {api_url} is healthy. Status code: {response.status_code}")
  23. else:
  24. logging.warning(f"API endpoint {api_url} returned unexpected status code: {response.status_code}")
  25. except requests.exceptions.RequestException as e:
  26. logging.error(f"Error connecting to API endpoint {api_url}: {e}")
  27. except Exception as e:
  28. logging.error(f"An unexpected error occurred: {e}")
  29. time.sleep(interval)
  30. if __name__ == "__main__":
  31. # Example usage: Replace with your API endpoint
  32. api_url = "https://your-api-endpoint.com/health" # Replace with your API URL
  33. monitor_api(api_url)

Add your comment