import requests
import json
import time
def flatten_http_response(url, timeout=10):
"""
Flattens the structure of an HTTP response for development purposes.
Includes a timeout to prevent indefinite waiting.
"""
try:
response = requests.get(url, timeout=timeout)
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 not JSON, use text
# Flatten the structure recursively
def flatten(obj, prefix=""):
flattened = {}
if isinstance(obj, dict):
for k, v in obj.items():
new_prefix = prefix + k + "_" if prefix else k + "_"
flattened.update(flatten(v, new_prefix))
elif isinstance(obj, list):
for i, v in enumerate(obj):
new_prefix = prefix + str(i) + "_"
flattened.update(flatten(v, new_prefix))
else:
flattened[prefix[:-1]] = obj # remove trailing underscore
return flattened
flattened_data = flatten(data)
return flattened_data
except requests.exceptions.RequestException as e:
print(f"Request error: {e}")
return None
except Exception as e:
print(f"An unexpected error occurred: {e}")
return None
if __name__ == '__main__':
# Example usage
url = "https://httpbin.org/json" # A test URL that returns JSON
flattened_response = flatten_http_response(url)
if flattened_response:
print(json.dumps(flattened_response, indent=4))
Add your comment