1. import json
  2. import requests
  3. from typing import Optional
  4. def pretty_print_response(response: requests.Response, indent: int = 4) -> None:
  5. """
  6. Pretty-prints the content of an HTTP response. Supports older Python versions.
  7. """
  8. try:
  9. # Use json.dumps with indent for pretty printing if content is JSON
  10. if response.headers.get('Content-Type', '').startswith('application/json'):
  11. print(json.dumps(response.json(), indent=indent))
  12. else:
  13. # For other content types, print the text with some formatting
  14. print(response.text)
  15. except json.JSONDecodeError:
  16. # Handle cases where the response is not valid JSON
  17. print("Response content is not valid JSON:")
  18. print(response.text)
  19. def monitor_http(url: str) -> None:
  20. """
  21. Monitors an HTTP URL and pretty-prints the response.
  22. """
  23. try:
  24. response = requests.get(url)
  25. response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
  26. pretty_print_response(response)
  27. except requests.exceptions.RequestException as e:
  28. print(f"Error during request to {url}: {e}")
  29. if __name__ == '__main__':
  30. # Example usage:
  31. monitor_http("https://api.example.com/data") # Replace with your URL
  32. monitor_http("https://httpstat.us/404") #Example with error
  33. monitor_http("https://httpstat.us/200") #Example with success

Add your comment