如何用Python循环替换URL中的用户ID并获取接口返回数据?
Hey Todd! Glad you're working on automating this API call. Let's break down how to replace that hardcoded user ID in your URL with a loop that goes through all the IDs you need.
Step 1: Define your list of user IDs
First, create a list of all the user IDs you want to fetch data for. This could be a static list, or you might load it from a file/database—whatever fits your use case.
Step 2: Use a URL template with dynamic formatting
Instead of hardcoding the user ID in the URL, turn it into a template where you can plug in each ID dynamically. Python's string formatting options (like f-strings or str.format()) make this clean and straightforward.
Step 3: Loop through each ID and handle API requests
Wrap your request logic in a loop that iterates over each user ID. We'll also add basic error handling to catch cases where the request fails (like a 404 or network issue) so your script doesn't crash halfway through.
Here's the revised code with all these changes:
import requests import json # Step 1: List of user IDs you want to process user_ids = [12345, 67890, 11223, 44556] # Add all your target user IDs here # Step 2: URL template with a placeholder for user_id url_template = "https://api.abc.com/users/{user_id}?api_key=5632lkjgdlg&_format=_show" # Step 3: Loop through each user ID to make API calls for user_id in user_ids: try: # Replace the placeholder with the current user ID current_url = url_template.format(user_id=user_id) # Send GET request and parse JSON response response = requests.get(current_url) response.raise_for_status() # Trigger error for HTTP status codes like 404/500 data = response.json() # Print the full user JSON (formatted for readability) print(f"=== User ID {user_id} Data ===") print(json.dumps(data['user'], indent=2)) print("\n") except requests.exceptions.RequestException as e: print(f"Failed to fetch data for user ID {user_id}: {str(e)}") except KeyError: print(f"User ID {user_id} response doesn't contain a 'user' key")
Key Details to Note:
- Dynamic URL Construction: Using
str.format()makes it explicit which part of the URL is being replaced. Alternatively, you could use an f-string directly:f"https://api.abc.com/users/{user_id}?api_key=..."—both work equally well. - Error Handling: The
try/exceptblocks handle common issues like network failures, invalid HTTP responses, or missing keys in the JSON response. This keeps your script robust even if some user IDs return errors. - Readable Output: Adding
indent=2tojson.dumps()formats the printed JSON into a human-readable structure instead of a single messy line.
If you need to load user IDs from an external source (like a CSV or text file), feel free to ask—I can add an example for that too!
内容的提问来源于stack exchange,提问作者Todd

