import requests import json def get_api_data(url): try: # Send a GET request response = requests.get(url) # Raise an exception for bad status codes (like 404 or 500) response.raise_for_status() # Parse the response as JSON data = response.json() return data except requests.exceptions.HTTPError as errh: print(f"Http Error: {errh}") except requests.exceptions.ConnectionError as errc: print(f"Error Connecting: {errc}") except requests.exceptions.Timeout as errt: print(f"Timeout Error: {errt}") except requests.exceptions.RequestException as err: print(f"OOps: Something Else: {err}") # Example usage api_url = "https://api.example.com/data" user_data = get_api_data(api_url) if user_data: print("Data fetched successfully:") # Pretty-print the JSON print(json.dumps(user_data, indent=4))