import requests
import json
def index_api_endpoints(api_base_url, default_values):
"""
Indexes API endpoints for diagnostics, checking their status and returning
a list of dictionaries with endpoint details and status.
"""
endpoints = []
# Define a list of potential diagnostic endpoints. Expand as needed.
endpoints_list = [
"/health",
"/version",
"/metrics",
"/status"
]
for endpoint in endpoints_list:
url = f"{api_base_url}{endpoint}"
try:
response = requests.get(url, timeout=5) # Add timeout for robustness
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
# Attempt to parse the response as JSON
try:
data = response.json()
except json.JSONDecodeError:
data = response.text # If JSON parsing fails, use text
endpoint_data = {
"url": url,
"status_code": response.status_code,
"response_time": response.elapsed.total_seconds(),
"response_data": data # Store the raw response data
}
endpoints.append(endpoint_data)
except requests.exceptions.RequestException as e:
# Handle connection errors, timeouts, etc.
endpoint_data = {
"url": url,
"status_code": None,
"response_time": None,
"error": str(e) # Store the error message
}
endpoints.append(endpoint_data)
return endpoints
if __name__ == '__main__':
# Example usage:
api_base = "http://localhost:8000" # Replace with your API base URL
default_values = {"timeout": 5} # Example default values (not used in this version)
diagnostics = index_api_endpoints(api_base, default_values)
for endpoint in diagnostics:
print(json.dumps(endpoint, indent=4))
Add your comment