Repository navigation
Expand file tree
/
Copy pathgithub_api.py
More file actions
89 lines (70 loc) · 2.69 KB
/
Copy pathgithub_api.py
File metadata and controls
89 lines (70 loc) · 2.69 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
"""Task 1: fetch GitHub users and display their public repository counts.
Uses only the Python standard library. For each username, the GitHub API
status code is checked and must be 200 before the JSON response is processed.
Run:
python github_api.py
Optional:
Set GITHUB_TOKEN to use an authenticated request (higher rate limit).
"""
from __future__ import annotations
import json
import os
import sys
import urllib.error
import urllib.request
from typing import Any
API_ENDPOINT = "https://api.github.com/users/{username}"
USERNAMES = ("octocat", "torvalds", "guido")
REQUEST_TIMEOUT_SECONDS = 30
def fetch_user(username: str) -> dict[str, Any]:
"""Return a GitHub user's JSON data, but only if the status is 200."""
headers = {
"Accept": "application/vnd.github+json",
"User-Agent": "python-github-api-assignment",
"X-GitHub-Api-Version": "2022-11-28",
}
token = os.environ.get("GITHUB_TOKEN")
if token:
headers["Authorization"] = f"Bearer {token}"
request = urllib.request.Request(
API_ENDPOINT.format(username=username),
headers=headers,
)
with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT_SECONDS) as response:
# Required check: do not process the payload unless the HTTP status is 200.
if response.status != 200:
raise RuntimeError(
f"GitHub returned HTTP {response.status} for {username}; "
"response was not processed."
)
payload = json.load(response)
if not isinstance(payload, dict):
raise RuntimeError(f"Unexpected JSON payload for {username}.")
if "login" not in payload or "public_repos" not in payload:
raise RuntimeError(f"Required fields are missing for {username}.")
return payload
def main() -> int:
print("GitHub API user details")
print("=" * 62)
print(f"{'Login':<20}{'Public repositories':>24}")
print("-" * 62)
failures = 0
for username in USERNAMES:
try:
user = fetch_user(username)
except urllib.error.HTTPError as exc:
failures += 1
print(f"{username:<20}{'FAILED':>24} (HTTP {exc.code})")
except (urllib.error.URLError, TimeoutError, RuntimeError, json.JSONDecodeError) as exc:
failures += 1
print(f"{username:<20}{'FAILED':>24} ({exc})")
else:
print(f"{user['login']:<20}{user['public_repos']:>24}")
print("-" * 62)
if failures:
print(f"{failures} request(s) failed. See the messages above.")
return 1
print("All requests returned HTTP 200 (verified before processing).")
return 0
if __name__ == "__main__":
raise SystemExit(main())