import json
def export_api_results(api_url, output_file="api_results.json"):
"""
Fetches data from an API, handles potential errors, and exports the results to a JSON file.
Includes fallback logic for API unavailability.
"""
try:
import requests # Import requests inside the try block
response = requests.get(api_url)
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
data = response.json() # Parse JSON response
except requests.exceptions.RequestException as e:
print(f"API request failed: {e}")
print("Falling back to dummy data.")
data = {"status": "fallback", "message": "API unavailable"}
except json.JSONDecodeError as e:
print(f"Failed to decode JSON: {e}")
print("Falling back to dummy data.")
data = {"status": "fallback", "message": "Invalid JSON response"}
except Exception as e:
print(f"An unexpected error occurred: {e}")
print("Falling back to dummy data.")
data = {"status": "fallback", "message": "Unexpected error"}
try:
with open(output_file, "w") as f:
json.dump(data, f, indent=4) # Write to JSON file with indentation
print(f"Results exported to {output_file}")
except IOError as e:
print(f"Failed to write to file: {e}")
if __name__ == '__main__':
# Example usage:
api_url = "https://jsonplaceholder.typicode.com/todos/1" # Replace with your API endpoint
export_api_results(api_url)
Add your comment