import requests
import time
import logging
import json
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def monitor_api(api_url, interval=60, expected_response_code=200):
"""
Monitors the state of an API endpoint.
Args:
api_url (str): The URL of the API endpoint to monitor.
interval (int): The interval (in seconds) between checks.
expected_response_code (int): The expected HTTP response code.
Returns:
None. Logs status and errors.
"""
while True:
try:
response = requests.get(api_url)
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
if response.status_code == expected_response_code:
logging.info(f"API endpoint {api_url} is healthy. Status code: {response.status_code}")
else:
logging.warning(f"API endpoint {api_url} returned unexpected status code: {response.status_code}")
except requests.exceptions.RequestException as e:
logging.error(f"Error connecting to API endpoint {api_url}: {e}")
except Exception as e:
logging.error(f"An unexpected error occurred: {e}")
time.sleep(interval)
if __name__ == "__main__":
# Example usage: Replace with your API endpoint
api_url = "https://your-api-endpoint.com/health" # Replace with your API URL
monitor_api(api_url)
Add your comment