1. import requests
  2. import json
  3. def index_api_endpoints(api_base_url, default_values):
  4. """
  5. Indexes API endpoints for diagnostics, checking their status and returning
  6. a list of dictionaries with endpoint details and status.
  7. """
  8. endpoints = []
  9. # Define a list of potential diagnostic endpoints. Expand as needed.
  10. endpoints_list = [
  11. "/health",
  12. "/version",
  13. "/metrics",
  14. "/status"
  15. ]
  16. for endpoint in endpoints_list:
  17. url = f"{api_base_url}{endpoint}"
  18. try:
  19. response = requests.get(url, timeout=5) # Add timeout for robustness
  20. response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
  21. # Attempt to parse the response as JSON
  22. try:
  23. data = response.json()
  24. except json.JSONDecodeError:
  25. data = response.text # If JSON parsing fails, use text
  26. endpoint_data = {
  27. "url": url,
  28. "status_code": response.status_code,
  29. "response_time": response.elapsed.total_seconds(),
  30. "response_data": data # Store the raw response data
  31. }
  32. endpoints.append(endpoint_data)
  33. except requests.exceptions.RequestException as e:
  34. # Handle connection errors, timeouts, etc.
  35. endpoint_data = {
  36. "url": url,
  37. "status_code": None,
  38. "response_time": None,
  39. "error": str(e) # Store the error message
  40. }
  41. endpoints.append(endpoint_data)
  42. return endpoints
  43. if __name__ == '__main__':
  44. # Example usage:
  45. api_base = "http://localhost:8000" # Replace with your API base URL
  46. default_values = {"timeout": 5} # Example default values (not used in this version)
  47. diagnostics = index_api_endpoints(api_base, default_values)
  48. for endpoint in diagnostics:
  49. print(json.dumps(endpoint, indent=4))

Add your comment