import json
import requests
from typing import Optional
def pretty_print_response(response: requests.Response, indent: int = 4) -> None:
"""
Pretty-prints the content of an HTTP response. Supports older Python versions.
"""
try:
# Use json.dumps with indent for pretty printing if content is JSON
if response.headers.get('Content-Type', '').startswith('application/json'):
print(json.dumps(response.json(), indent=indent))
else:
# For other content types, print the text with some formatting
print(response.text)
except json.JSONDecodeError:
# Handle cases where the response is not valid JSON
print("Response content is not valid JSON:")
print(response.text)
def monitor_http(url: str) -> None:
"""
Monitors an HTTP URL and pretty-prints the response.
"""
try:
response = requests.get(url)
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
pretty_print_response(response)
except requests.exceptions.RequestException as e:
print(f"Error during request to {url}: {e}")
if __name__ == '__main__':
# Example usage:
monitor_http("https://api.example.com/data") # Replace with your URL
monitor_http("https://httpstat.us/404") #Example with error
monitor_http("https://httpstat.us/200") #Example with success
Add your comment