Designing the GitHub Client
I'm focusing on the implementation using the requests library. I've pinpointed key needs like how to manage authentication, error handling, and making asynchronous requests. I'm prioritizing building core functionalities first.
Constructing Core Functionality
I've outlined the structure for a GitHubClient class. It will manage the API token and base URL, employing helper methods for request construction. I'm prioritizing the use of environment variables for the token, aligning with best practices. I'm focusing on GET, POST, PUT, and DELETE, with built-in error handling.
Developing Request Abstraction
I'm now abstracting network calls to a central _make_request method. This centralizes error handling and ensures consistent headers. I'm dynamically constructing URLs and employing try-except blocks. I'm pondering JSON responses, as some operations might return 204. I'll need to refine handling non-JSON responses.
Expanding the API Interface
I'm translating common GitHub operations into concrete public methods. I've designed get_user_repos, create_issue, get_user_profile, and star_repo. The request abstraction needs improvements. I'm choosing plain requests for simplicity, but I'll ensure any custom headers are merged correctly. I'll check the status code or content before calling .json() for robust error handling.
Refining Request Wrappers
I'm now implementing the get and post methods within the client class, leveraging the session for efficiency. I'm focusing on error handling using raise_for_status() to ensure a robust client. I'm aiming for a straightforward, RESTful wrapper, initially omitting full pagination logic for simplicity.
Refining Documentation and Examples
I'm now adding docstrings to all methods, clearly explaining parameters and return values. I've re-evaluated the user request: Python and the requests library are confirmed. I'm focusing on crafting a generic request method alongside specific wrappers for get and post, plus a couple of illustrative examples. I'm taking the opportunity to pre-emptively handle potential issues with endpoint paths, preventing double slashes. JSON handling, specifically for responses with 204 status, is also on my mind. I'm almost ready to finalize the code, including comments on getting an authentication token, along with a more manageable scope for specific methods.
Completing the API Client
I've finalized the structure of the GitHubClient class. It includes the __init__, a private _request helper, and wrappers for get, post, put, and delete. I've added a few example domain methods, such as get_current_user and create_issue to demonstrate usage.
Here is a robust, class-based implementation of a GitHub API client using Python and the requests library.
This implementation uses a requests.Session for better performance (connection pooling) and handles authentication, error checking, and JSON serialization automatically.
The Python Code
import requests
import os
from typing import Optional, Dict, Any
class GitHubClient:
"""
A Python client for the GitHub REST API.
"""
BASE_URL = "https://api.github.com"
def __init__(self, token: str):
"""
Initialize the client with a GitHub Personal Access Token.
:param token: Your GitHub PAT (Settings -> Developer settings -> Tokens)
"""
self.session = requests.Session()
self.session.headers.update({
"Authorization": f"Bearer {token}",
"Accept": "application/vnd.github.v3+json",
"User-Agent": "python-github-client"
})
def _request(self, method: str, endpoint: str, **kwargs) -> Any:
"""
Internal helper to handle requests, errors, and JSON parsing.
"""
url = f"{self.BASE_URL}/{endpoint.lstrip('/')}"
try:
response = self.session.request(method, url, **kwargs)
# Raise an HTTPError if the status code is 4xx or 5xx
response.raise_for_status()
# Return None for 204 No Content (common in DELETE operations)
if response.status_code == 204:
return None
# Attempt to return JSON, fallback to raw content if empty
try:
return response.json()
except ValueError:
return response.content
except requests.exceptions.HTTPError as e:
print(f"HTTP Error: {e}")
if e.response is not None:
print(f"Response Body: {e.response.text}")
raise
except requests.exceptions.RequestException as e:
print(f"Network Error: {e}")
raise
# --- Generic HTTP wrappers ---
def get(self, endpoint: str, params: Optional[Dict] = None) -> Any:
return self._request('GET', endpoint, params=params)
def post(self, endpoint: str, data: Optional[Dict] = None) -> Any:
return self._request('POST', endpoint, json=data)
def patch(self, endpoint: str, data: Optional[Dict] = None) -> Any:
return self._request('PATCH', endpoint, json=data)
def delete(self, endpoint: str) -> Any:
return self._request('DELETE', endpoint)
# --- Specific API Capabilities (Examples) ---
def get_current_user(self):
"""Get the authenticated user's profile."""
return self.get("/user")
def get_user_repos(self, username: str):
"""Get a list of public repositories for a specific user."""
return self.get(f"/users/{username}/repos")
def create_issue(self, owner: str, repo: str, title: str, body: str):
"""Create an issue in a specific repository."""
endpoint = f"/repos/{owner}/{repo}/issues"
payload = {
"title": title,
"body": body
}
return self.post(endpoint, data=payload)
def star_repo(self, owner: str, repo: str):
"""Star a repository (returns None on success)."""
# PUT /user/starred/{owner}/{repo}
return self._request('PUT', f"/user/starred/{owner}/{repo}", headers={"Content-Length": "0"})
# --- Usage Example ---
if __name__ == "__main__":
# 1. Get your token from environment validation or hardcode it (not recommended)
# export GITHUB_TOKEN="your_pat_here"
TOKEN = os.getenv("GITHUB_TOKEN")
if not TOKEN:
print("Please set the GITHUB_TOKEN environment variable.")
exit(1)
client = GitHubClient(TOKEN)
try:
# Example 1: Get current user info
user = client.get_current_user()
print(f"Logged in as: {user['login']}")
# Example 2: Get repositories of a specific library (e.g., requests)
repos = client.get_user_repos("psf")
print(f"Found {len(repos)} repos for 'psf'. First one: {repos[0]['name']}")
# Example 3: Create an Issue (Uncomment to test - requires write permissions)
# issue = client.create_issue("your_username", "your_repo", "Bug Report", "Something is broken.")
# print(f"Created issue #{issue['number']}")
except Exception as e:
print(f"An error occurred: {e}")
Key Features of this Implementation
- Session Management (
requests.Session):
- This is more efficient than calling
requests.get directly. It keeps the underlying TCP connection open (Connection Pooling), making subsequent requests to the same host much faster.
- Authorization Header:
- It automatically attaches the
Authorization token and the recommended GitHub Accept header to every request so you don't have to repeat yourself.
- Error Handling (
raise_for_status):
- It automatically checks for 4xx (Client Error) and 5xx (Server Error) codes. If GitHub returns a 401 (Unauthorized) or 404 (Not Found), the script will raise an exception eagerly rather than failing silently.
- Clean Interface:
- It provides generic methods (
.get(), .post()) for flexibility.
- It provides logic-specific methods (
.create_issue()) to show how to wrap specific GitHub endpoints.
How to use it
- Get a Token: Go to GitHub -> Settings -> Developer Settings -> Personal Access Tokens -> Tokens (classic). Generate a token with
repo scope.
- Install Requests:
pip install requests
- Run the script:
export GITHUB_TOKEN="ghp_your_token_here"
python your_script_name.py