Generate Python 3.12 which connect to a test REST API and process its JSON data. Do some…
- User
Generate Python 3.12 which connect to a test REST API and process its JSON data. Do some error handling in the code.
Assistant
Python 3.12 REST API Client with Error Handling
Here's a Python 3.12 script that connects to a test REST API (using JSONPlaceholder as an example), processes the JSON data, and includes comprehensive error handling:
import json import logging from typing import Any, Dict, List import urllib.error import urllib.request from http.client import HTTPResponse # Configure logging logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s' ) logger = logging.getLogger(__name__) # Constants BASE_URL = "https://jsonplaceholder.typicode.com" ENDPOINT = "/posts" TIMEOUT_SECONDS = 10 MAX_RETRIES = 3 def fetch_api_data(url: str) -> HTTPResponse: """Fetch data from the API with retry logic.""" for attempt in range(MAX_RETRIES): try: request = urllib.request.Request(url) request.add_header('User-Agent', 'PythonRESTClient/1.0') logger.info(f"Attempt {attempt + 1}: Fetching data from {url}") response = urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) if response.status == 200: return response else: logger.warning(f"Received HTTP {response.status}") except urllib.error.URLError as e: logger.warning(f"Network error (attempt {attempt + 1}): {e.reason}") if attempt == MAX_RETRIES - 1: raise except TimeoutError: logger.warning(f"Timeout occurred (attempt {attempt + 1})") if attempt == MAX_RETRIES - 1: raise raise ConnectionError(f"Failed to fetch data after {MAX_RETRIES} attempts") def process_json_data(data: List[Dict[str, Any]]) -> None: """Process and analyze the JSON data.""" if not data: logger.warning("No data received from API") return logger.info(f"Processing {len(data)} items") # Example processing: count posts per user user_post_count: Dict[int, int] = {} for item in data: try: user_id = item['userId'] user_post_count[user_id] = user_post_count.get(user_id, 0) + 1 except KeyError as e: logger.error(f"Missing expected field in data: {e}") # Display results print("\nPosts per user:") for user_id, count in sorted(user_post_count.items()): print(f"User {user_id}: {count} posts") # Additional analysis could be added here def main() -> None: """Main function to execute the API client.""" try: # Construct the full API URL api_url = f"{BASE_URL}{ENDPOINT}" logger.info(f"Connecting to API at: {api_url}") # Fetch data from API response = fetch_api_data(api_url) # Parse JSON data try: data = json.load(response) logger.info("Successfully parsed JSON data") except json.JSONDecodeError as e: logger.error(f"Failed to parse JSON: {e}") raise # Process the data process_json_data(data) except urllib.error.URLError as e: logger.error(f"URL Error: {e.reason}") except TimeoutError: logger.error("Request timed out") except ConnectionError as e: logger.error(f"Connection failed: {e}") except Exception as e: logger.error(f"Unexpected error: {e}", exc_info=True) else: logger.info("API data processing completed successfully") finally: logger.info("Script execution finished") if __name__ == "__main__": main()Key Features:
-
Error Handling:
- Network errors (URLError, TimeoutError)
- HTTP status codes
- JSON parsing errors
- Missing data fields
- Retry mechanism for transient failures
-
Modern Python 3.12 Features:
- Type hints throughout the code
- F-strings for string formatting
- Context managers for resource handling
-
Logging:
- Detailed logging at different levels
- Timestamps for debugging
- Error reporting with stack traces when needed
-
Processing:
- Example data analysis (count posts per user)
- Graceful handling of missing data
-
Configuration:
- Constants for easy modification
- Timeout settings
- Retry logic
To test with a different API, just change the
BASE_URLandENDPOINTconstants. The error handling will work with any REST API that returns JSON data.Would you like me to modify any specific part of this implementation?
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.