import requests
import time
import logging
from typing import Dict, Any
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
class APIAnomalyDetector:
def __init__(self, api_endpoint: str, expected_status_code: int, retry_count: int = 3, retry_delay: int = 5):
"""
Initializes the API Anomaly Detector.
Args:
api_endpoint: The URL of the API endpoint to monitor.
expected_status_code: The expected HTTP status code for a healthy endpoint.
retry_count: The number of times to retry the request if it fails.
retry_delay: The delay (in seconds) between retries.
"""
self.api_endpoint = api_endpoint
self.expected_status_code = expected_status_code
self.retry_count = retry_count
self.retry_delay = retry_delay
def check_endpoint(self) -> bool:
"""
Checks the API endpoint and flags anomalies based on status code.
Returns:
True if the endpoint is healthy (status code matches), False otherwise (anomaly detected).
"""
for attempt in range(self.retry_count):
try:
response = requests.get(self.api_endpoint)
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
if response.status_code == self.expected_status_code:
logging.info(f"Endpoint {self.api_endpoint} is healthy (Status Code: {response.status_code})")
return True
else:
logging.warning(f"Endpoint {self.api_endpoint} returned unexpected status code: {response.status_code}")
return False #Anomaly Detected
except requests.exceptions.RequestException as e:
logging.error(f"Error accessing endpoint {self.api_endpoint}: {e}")
if attempt < self.retry_count - 1:
logging.info(f"Retrying in {self.retry_delay} seconds...")
time.sleep(self.retry_delay)
else:
logging.critical(f"Endpoint {self.api_endpoint} is down after {self.retry_count} attempts.")
return False #Anomaly Detected
return False #Should not reach here, but added for safety
if __name__ == '__main__':
# Example Usage
api_detector = APIAnomalyDetector(api_endpoint="https://api.example.com/data", expected_status_code=200)
is_healthy = api_detector.check_endpoint()
if not is_healthy:
print("API Endpoint Anomaly Detected. Maintenance Required.")
else:
print("API Endpoint is Operational.")
Add your comment