1. import json
  2. def initialize_api_response_components(api_response_data):
  3. """
  4. Initializes components of API responses for exploratory work.
  5. Args:
  6. api_response_data (dict): The raw API response data (usually a dictionary).
  7. Returns:
  8. dict: A dictionary containing initialized components. Returns an empty dict if input is invalid.
  9. """
  10. if not isinstance(api_response_data, dict):
  11. print("Error: Invalid input. Expected a dictionary.")
  12. return {}
  13. initialized_components = {}
  14. # Basic metadata
  15. initialized_components['status_code'] = api_response_data.get('status_code', 'N/A') # Get status code, default to 'N/A'
  16. initialized_components['request_url'] = api_response_data.get('request_url', 'N/A') # Get request URL, default to 'N/A'
  17. initialized_components['timestamp'] = api_response_data.get('timestamp', 'N/A') # Get timestamp, default to 'N/A'
  18. # Response headers
  19. initialized_components['response_headers'] = api_response_data.get('headers', {}) # Get headers, default to empty dict
  20. # Response body - Handling different content types
  21. response_body = api_response_data.get('body', '')
  22. content_type = api_response_data.get('content_type', 'application/json') # Default content type
  23. if content_type == 'application/json':
  24. try:
  25. initialized_components['response_data'] = json.loads(response_body) # Parse JSON
  26. except json.JSONDecodeError:
  27. initialized_components['response_data'] = response_body # Store as string if JSON parsing fails
  28. elif content_type == 'text/plain':
  29. initialized_components['response_data'] = response_body # Store as plain text
  30. else:
  31. initialized_components['response_data'] = response_body #Store as raw string if other type
  32. #Error/message handling
  33. initialized_components['error_message'] = api_response_data.get('error', None) #Get error message
  34. return initialized_components

Add your comment