1. import json
  2. def export_api_results(api_url, output_file="api_results.json"):
  3. """
  4. Fetches data from an API, handles potential errors, and exports the results to a JSON file.
  5. Includes fallback logic for API unavailability.
  6. """
  7. try:
  8. import requests # Import requests inside the try block
  9. response = requests.get(api_url)
  10. response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
  11. data = response.json() # Parse JSON response
  12. except requests.exceptions.RequestException as e:
  13. print(f"API request failed: {e}")
  14. print("Falling back to dummy data.")
  15. data = {"status": "fallback", "message": "API unavailable"}
  16. except json.JSONDecodeError as e:
  17. print(f"Failed to decode JSON: {e}")
  18. print("Falling back to dummy data.")
  19. data = {"status": "fallback", "message": "Invalid JSON response"}
  20. except Exception as e:
  21. print(f"An unexpected error occurred: {e}")
  22. print("Falling back to dummy data.")
  23. data = {"status": "fallback", "message": "Unexpected error"}
  24. try:
  25. with open(output_file, "w") as f:
  26. json.dump(data, f, indent=4) # Write to JSON file with indentation
  27. print(f"Results exported to {output_file}")
  28. except IOError as e:
  29. print(f"Failed to write to file: {e}")
  30. if __name__ == '__main__':
  31. # Example usage:
  32. api_url = "https://jsonplaceholder.typicode.com/todos/1" # Replace with your API endpoint
  33. export_api_results(api_url)

Add your comment