-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_data_fetch.py
More file actions
51 lines (40 loc) · 1.57 KB
/
api_data_fetch.py
File metadata and controls
51 lines (40 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import requests
import json
API_URL = "https://randomuser.me/api/"
def fetch_user_data():
try:
response = requests.get(API_URL, timeout=10)
# 4. Check response status code
if response.status_code != 200:
print(f"Failed to fetch data. Status Code: {response.status_code}")
return
# 5. Parse JSON response
data = response.json()
# 6. Extract nested fields
user = data["results"][0]
extracted_data = {
"full_name": f"{user['name']['first']} {user['name']['last']}",
"gender": user["gender"],
"email": user["email"],
"country": user["location"]["country"],
"city": user["location"]["city"]
}
# 8. Display clean output
print("\nUser Data Fetched Successfully\n")
for key, value in extracted_data.items():
print(f"{key.capitalize().replace('_', ' ')}: {value}")
# 9. Store data locally
with open("data.json", "w") as file:
json.dump(extracted_data, file, indent=4)
print("\nData saved to data.json")
# 7. Handle API errors gracefully
except requests.exceptions.Timeout:
print("⏳Request timed out.")
except requests.exceptions.ConnectionError:
print("Network connection error.")
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
except KeyError:
print("Unexpected response structure.")
if __name__ == "__main__":
fetch_user_data()