I’m planning to implement a Python API client for GitHub using the requests library. I think the user wants a minimal API client with methods like getting user info, repos, and issues, but they didn’t specify complexity. I'll keep it concise but not too bare, ensuring I include code with a short explanation. I'll consider adding authentication via a Personal Access Token (PAT), error handling, and pagination in a single file module called GitHubClient. The base URL will be https://api.github.com, with options for "Bearer" token authentication.Implementing GitHub client in Python
I’m going to implement a GitHub API client in Python using the requests library. The plan includes defining a custom exception class, GitHubAPIError, and a main class, GitHubClient, with methods for user and repository access. I’ll set up a private request method to handle API calls, along with pagination for listing repos. They'll use a requests.Session() to optimize connections. I also need to keep the docstring concise but informative, including usage examples and addressing rate limits. Overall, it needs to be a well-structured module.Setting up session and error handling
I'm initializing session headers for the GitHub client with an "Accept" header for GitHub's JSON format. If a token is provided, I'll include it in the Authorization header as "Bearer." I'll also add a custom User-Agent string.
For error handling, I’ll define a custom exception class, GitHubAPIError, to capture details like status codes and messages. In the _request method, I'll use session.request to check if the response is okay, and if not, raise the custom error. I also need basic methods for different HTTP verbs, ensuring flexibility for the client.Implementing GitHub client methods
I'm going to implement several methods for my GitHubClient class, including _request and _paginate. I think it’s important to provide convenience methods like get_user for fetching user data, get_repo for specific repositories, and list_user_repos with options for visibility and pagination. I’ll also add a list_issues method for gathering issues based on their state. Additionally, I’ll ensure to handle query parameters and include example usage at the bottom within an if name == "main" block, keeping it concise yet functional. I'll also consider edge cases like timeout parameters and add optional type hints.Planning the GitHub client implementation
I’m setting up the GitHub API client using requests. The main parts will be creating a custom error class, GitHubAPIError, and the GitHubClient class, which will include methods for user interactions and pagination. I’ll be using type hints, considering whether to use List[str] or keep it simple with Optional[list].
I’ll implement context manager support for the client, allowing for automatic session closure. I need to ensure proper error handling, especially for the starred methods where I'm handling 204 and 404 responses distinctly. Overall, I want a well-structured, functional module.Simplifying type hints and design
I want to clarify my type hints, so I'm thinking of using widely supported ones like Optional[str], Dict[str, Any], and List[Dict[str, Any]]. I'll avoid newer features from Python 3.9, opting instead for Iterable and List.
For handling query parameters, I’ll ensure the initial pagination uses params=params and switch to params=None afterward for robustness. In the _request method, I'll simplify error handling to accept any 2xx as success. This way, I can streamline the implementation while still allowing versatility. ```python
"""
Simple GitHub API client implemented using the requests library.
Features:
Personal Access Token (PAT) authentication
Basic error handling with a custom exception
Pagination helper
A few convenience methods (users, repos, issues, starring)
Requires: requests
pip install requests
"""
from typing import Any, Dict, Generator, Optional
import requests
class GitHubAPIError(Exception):
"""Raised when the GitHub API returns an error response."""
if name == "main":
# Example usage (read-only, unauthenticated)
client = GitHubClient()
code
user = client.get_user("octocat")
print("Octocat:", user["login"], "id:", user["id"])
print("\nSome octocat repos:")
for i, repo in enumerate(client.list_user_repos("octocat"), start=1):
print(f"{i:2d}. {repo['name']}")
if i >= 5:
break
client.close()
code
def __init__(
self,
token: Optional[str] = None,
base_url: str = BASE_URL,
timeout: float = 10.0,
) -> None:
"""
Initialize the GitHub client.
:param token: Personal Access Token for authenticated requests (optional).
:param base_url: Base URL for the API, default GitHub public API.
:param timeout: Timeout in seconds for requests.
"""
self.base_url = base_url.rstrip("/")
self.timeout = timeout
self.session = requests.Session()
self.session.headers.update(
{
"Accept": "application/vnd.github+json",
"User-Agent": "github-client-demo/1.0",
}
)
if token:
# GitHub accepts "token" and "Bearer". "Bearer" is recommended for PATs.
self.session.headers["Authorization"] = f"Bearer {token}"
# --- Context manager support -------------------------------------------------
def __enter__(self) -> "GitHubClient":
return self
def __exit__(self, exc_type, exc, tb) -> None: # type: ignore[override]
self.close()
def close(self) -> None:
"""Close the underlying HTTP session."""
self.session.close()
# --- Low-level HTTP helpers --------------------------------------------------
def _build_url(self, path: str) -> str:
if not path.startswith("/"):
path = "/" + path
return self.base_url + path
def _handle_error(self, response: requests.Response) -> None:
"""Raise GitHubAPIError if response is not successful."""
try:
data = response.json()
message = data.get("message", "") or response.text
except ValueError:
message = response.text or "Unknown error"
raise GitHubAPIError(response.status_code, message, response)
def _request(
self,
method: str,
path: str,
*,
params: Optional[Dict[str, Any]] = None,
json: Optional[Any] = None,
headers: Optional[Dict[str, str]] = None,
) -> Any:
"""
Perform a single HTTP request to the GitHub API.
Treat any 2xx status as success; raise GitHubAPIError otherwise.
"""
url = self._build_url(path)
response = self.session.request(
method=method,
url=url,
params=params,
json=json,
headers=headers,
timeout=self.timeout,
)
if not response.ok: # 4xx / 5xx
self._handle_error(response)
if response.status_code == 204:
return None
content_type = response.headers.get("Content-Type", "")
if "application/json" in content_type:
return response.json()
return response.text
def _paginate(
self,
method: str,
path: str,
*,
params: Optional[Dict[str, Any]] = None,
json: Optional[Any] = None,
) -> Generator[Any, None, None]:
"""
Generator that automatically follows GitHub's Link-based pagination.
Yields individual items from list responses.
"""
url = self._build_url(path)
while url:
response = self.session.request(
method=method,
url=url,
params=params,
json=json,
timeout=self.timeout,
)
if not response.ok:
self._handle_error(response)
data = response.json()
if isinstance(data, list):
for item in data:
yield item
else:
# Some endpoints (like search) return {"items": [...]}
items = data.get("items", [])
for item in items:
yield item
# Parse Link header for "next" URL
link_header = response.headers.get("Link", "")
next_url = None
if link_header:
for part in link_header.split(","):
section = part.strip().split(";")
if len(section) < 2:
continue
link_part = section[0].strip()
rel_part = section[1].strip()
if rel_part == 'rel="next"':
if link_part.startswith("<") and link_part.endswith(">"):
next_url = link_part[1:-1]
else:
next_url = link_part
break
url = next_url
# After first request, further pagination info is encoded into `next_url`
params = None
# --- Convenience methods -----------------------------------------------------
# Users
def get_user(self, username: str) -> Dict[str, Any]:
"""Get a public GitHub user profile."""
return self._request("GET", f"/users/{username}")
def get_authenticated_user(self) -> Dict[str, Any]:
"""Get the authenticated user's profile (requires token)."""
return self._request("GET", "/user")
# Repositories
def get_repo(self, owner: str, repo: str) -> Dict[str, Any]:
"""Get a single repository."""
return self._request("GET", f"/repos/{owner}/{repo}")
def list_user_repos(
self,
username: str,
*,
repo_type: str = "owner",
sort: str = "full_name",
direction: str = "asc",
per_page: int = 100,
) -> Generator[Dict[str, Any], None, None]:
"""
List repositories for a user, yielding repos across all pages.
"""
params = {
"type": repo_type,
"sort": sort,
"direction": direction,
"per_page": per_page,
}
return self._paginate("GET", f"/users/{username}/repos", params=params)
# Issues
def list_repo_issues(
self,
owner: str,
repo: str,
*,
state: str = "open",
per_page: int = 100,
) -> Generator[Dict[str, Any], None, None]:
"""List issues for a repository, including pagination."""
params = {"state": state, "per_page": per_page}
return self._paginate("GET", f"/repos/{owner}/{repo}/issues", params=params)
def create_issue(
self,
owner: str,
repo: str,
title: str,
body: Optional[str] = None,
assignees: Optional[list] = None,
labels: Optional[list] = None,
) -> Dict[str, Any]:
"""Create an issue in a repository (requires token with repo scope)."""
payload: Dict[str, Any] = {"title": title}
if body is not None:
payload["body"] = body
if assignees is not None:
payload["assignees"] = assignees
if labels is not None:
payload["labels"] = labels
return self._request("POST", f"/repos/{owner}/{repo}/issues", json=payload)
# Starring
def add_star(self, owner: str, repo: str) -> None:
"""Star a repository (authenticated user)."""
self._request("PUT", f"/user/starred/{owner}/{repo}")
def remove_star(self, owner: str, repo: str) -> None:
"""Unstar a repository (authenticated user)."""
self._request("DELETE", f"/user/starred/{owner}/{repo}")
def is_starred(self, owner: str, repo: str) -> bool:
"""
Check if the authenticated user has starred a repository.
GitHub returns:
- 204 if starred
- 404 if not starred
"""
url = f"/user/starred/{owner}/{repo}"
try:
self._request("GET", url)
return True
except GitHubAPIError as exc:
if exc.status_code == 404:
return False
raise