1. import requests
  2. import time
  3. import logging
  4. from typing import Dict, Any
  5. # Configure logging
  6. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
  7. class APIAnomalyDetector:
  8. def __init__(self, api_endpoint: str, expected_status_code: int, retry_count: int = 3, retry_delay: int = 5):
  9. """
  10. Initializes the API Anomaly Detector.
  11. Args:
  12. api_endpoint: The URL of the API endpoint to monitor.
  13. expected_status_code: The expected HTTP status code for a healthy endpoint.
  14. retry_count: The number of times to retry the request if it fails.
  15. retry_delay: The delay (in seconds) between retries.
  16. """
  17. self.api_endpoint = api_endpoint
  18. self.expected_status_code = expected_status_code
  19. self.retry_count = retry_count
  20. self.retry_delay = retry_delay
  21. def check_endpoint(self) -> bool:
  22. """
  23. Checks the API endpoint and flags anomalies based on status code.
  24. Returns:
  25. True if the endpoint is healthy (status code matches), False otherwise (anomaly detected).
  26. """
  27. for attempt in range(self.retry_count):
  28. try:
  29. response = requests.get(self.api_endpoint)
  30. response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
  31. if response.status_code == self.expected_status_code:
  32. logging.info(f"Endpoint {self.api_endpoint} is healthy (Status Code: {response.status_code})")
  33. return True
  34. else:
  35. logging.warning(f"Endpoint {self.api_endpoint} returned unexpected status code: {response.status_code}")
  36. return False #Anomaly Detected
  37. except requests.exceptions.RequestException as e:
  38. logging.error(f"Error accessing endpoint {self.api_endpoint}: {e}")
  39. if attempt < self.retry_count - 1:
  40. logging.info(f"Retrying in {self.retry_delay} seconds...")
  41. time.sleep(self.retry_delay)
  42. else:
  43. logging.critical(f"Endpoint {self.api_endpoint} is down after {self.retry_count} attempts.")
  44. return False #Anomaly Detected
  45. return False #Should not reach here, but added for safety
  46. if __name__ == '__main__':
  47. # Example Usage
  48. api_detector = APIAnomalyDetector(api_endpoint="https://api.example.com/data", expected_status_code=200)
  49. is_healthy = api_detector.check_endpoint()
  50. if not is_healthy:
  51. print("API Endpoint Anomaly Detected. Maintenance Required.")
  52. else:
  53. print("API Endpoint is Operational.")

Add your comment