import json
def initialize_api_response_components(api_response_data):
"""
Initializes components of API responses for exploratory work.
Args:
api_response_data (dict): The raw API response data (usually a dictionary).
Returns:
dict: A dictionary containing initialized components. Returns an empty dict if input is invalid.
"""
if not isinstance(api_response_data, dict):
print("Error: Invalid input. Expected a dictionary.")
return {}
initialized_components = {}
# Basic metadata
initialized_components['status_code'] = api_response_data.get('status_code', 'N/A') # Get status code, default to 'N/A'
initialized_components['request_url'] = api_response_data.get('request_url', 'N/A') # Get request URL, default to 'N/A'
initialized_components['timestamp'] = api_response_data.get('timestamp', 'N/A') # Get timestamp, default to 'N/A'
# Response headers
initialized_components['response_headers'] = api_response_data.get('headers', {}) # Get headers, default to empty dict
# Response body - Handling different content types
response_body = api_response_data.get('body', '')
content_type = api_response_data.get('content_type', 'application/json') # Default content type
if content_type == 'application/json':
try:
initialized_components['response_data'] = json.loads(response_body) # Parse JSON
except json.JSONDecodeError:
initialized_components['response_data'] = response_body # Store as string if JSON parsing fails
elif content_type == 'text/plain':
initialized_components['response_data'] = response_body # Store as plain text
else:
initialized_components['response_data'] = response_body #Store as raw string if other type
#Error/message handling
initialized_components['error_message'] = api_response_data.get('error', None) #Get error message
return initialized_components
Add your comment