1. import requests
  2. import json
  3. import time
  4. def monitor_api(api_url, interval=60):
  5. """
  6. Monitors an API endpoint and logs errors.
  7. """
  8. try:
  9. while True:
  10. try:
  11. response = requests.get(api_url)
  12. response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
  13. # Process the JSON response
  14. data = response.json()
  15. print(f"API response received successfully at {time.strftime('%Y-%m-%d %H:%M:%S')}: {data}")
  16. except requests.exceptions.RequestException as e:
  17. print(f"Error during API request: {e}")
  18. except json.JSONDecodeError as e:
  19. print(f"Error decoding JSON response: {e}")
  20. except Exception as e:
  21. print(f"An unexpected error occurred: {e}")
  22. time.sleep(interval) # Wait before next check
  23. except KeyboardInterrupt:
  24. print("Monitoring stopped.")
  25. if __name__ == '__main__':
  26. # Example usage: Replace with your API URL
  27. api_url = "https://rickandmortyapi.com/api/character"
  28. monitor_api(api_url)

Add your comment