import requests
import json
import time
def monitor_api(api_url, interval=60):
"""
Monitors an API endpoint and logs errors.
"""
try:
while True:
try:
response = requests.get(api_url)
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
# Process the JSON response
data = response.json()
print(f"API response received successfully at {time.strftime('%Y-%m-%d %H:%M:%S')}: {data}")
except requests.exceptions.RequestException as e:
print(f"Error during API request: {e}")
except json.JSONDecodeError as e:
print(f"Error decoding JSON response: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
time.sleep(interval) # Wait before next check
except KeyboardInterrupt:
print("Monitoring stopped.")
if __name__ == '__main__':
# Example usage: Replace with your API URL
api_url = "https://rickandmortyapi.com/api/character"
monitor_api(api_url)
Add your comment