import requests
from requests.exceptions import HTTPError
class GitHubClient:
"""
A simple Python client for the GitHub API.
"""
BASE_URL = "https://api.github.com"
def __init__(self, token=None):
"""
Initialize the client.
:param token: GitHub Personal Access Token (PAT).
While optional for public data, it is highly recommended
to avoid rate limiting.
"""
self.session = requests.Session()
self.token = token
# Set default headers
headers = {
"Accept": "application/vnd.github.v3+json",
"User-Agent": "Python-GitHub-Client/1.0"
}
if token:
headers["Authorization"] = f"token {token}"
self.session.headers.update(headers)
def _request(self, method, endpoint, params=None, data=None):
"""
Internal helper to make requests and handle errors.
"""
url = f"{self.BASE_URL}{endpoint}"
try:
response = self.session.request(
method,
url,
params=params,
json=data
)
# Check for specific HTTP errors
if response.status_code == 401:
raise ValueError("Authentication failed. Check your token.")
if response.status_code == 403:
# Usually rate limiting
raise ValueError("Rate limit likely exceeded or forbidden access.")
if response.status_code == 404:
raise ValueError(f"Resource not found: {url}")
# Raise an error for other 4xx/5xx codes
response.raise_for_status()
# Return JSON if content exists, else empty dict
return response.json() if response.content else {}
except HTTPError as http_err:
print(f"HTTP error occurred: {http_err}")
raise
except Exception as err:
print(f"An error occurred: {err}")
raise
# --- User Operations ---
def get_authenticated_user(self):
"""Get the currently authenticated user."""
return self._request("GET", "/user")
def get_user(self, username):
"""Get public info about a specific user."""
return self._request("GET", f"/users/{username}")
# --- Repository Operations ---
def list_user_repos(self, username, visibility="all"):
"""
List public repositories for a specific user.
"""
params = {"visibility": visibility}
return self._request("GET", f"/users/{username}/repos", params=params)
def list_my_repos(self, visibility="all"):
"""
List repositories for the authenticated user.
"""
params = {"visibility": visibility}
return self._request("GET", "/user/repos", params=params)
def get_repo(self, owner, repo):
"""Get details of a specific repository."""
return self._request("GET", f"/repos/{owner}/{repo}")
def create_repo(self, name, description="", private=False):
"""
Create a new repository for the authenticated user.
"""
data = {
"name": name,
"description": description,
"private": private
}
return self._request("POST", "/user/repos", data=data)
def create_file(self, owner, repo, path, message, content, branch="main"):
"""
Create or update a file in a repository.
"""
# Note: In a real app, you might need to base64 encode 'content'
# depending on how strict the API implementation is, but usually
# the json payload handles string escaping.
# For GitHub API, 'content' must be Base64 encoded.
import base64
encoded_content = base64.b64encode(content.encode('utf-8')).decode('utf-8')
data = {
"message": message,
"content": encoded_content,
"branch": branch
}
return self._request("PUT", f"/repos/{owner}/{repo}/contents/{path}", data=data)
# --- Usage Example ---
if __name__ == "__main__":
# 1. Initialize client (Without token for public data)
client = GitHubClient()
try:
print("--- Fetching User: octocat ---")
user = client.get_user("octocat")
print(f"Name: {user.get('name')}")
print(f"Bio: {user.get('bio')}")
print(f"Public Repos: {user.get('public_repos')}")
print("\n--- Fetching a Public Repo ---")
repo = client.get_repo("octocat", "Hello-World")
print(f"Repo Description: {repo.get('description')}")
print(f"Stars: {repo.get('stargazers_count')}")
except Exception as e:
print(f"Error in public fetch: {e}")
# 2. Example of Authenticated Actions (Requires Token)
# Set your token as an environment variable or paste it here
# import os
# MY_TOKEN = os.getenv("GITHUB_TOKEN")
# if MY_TOKEN:
# auth_client = GitHubClient(token=MY_TOKEN)
#
# # Get your own profile
# me = auth_client.get_authenticated_user()
# print(f"\nLogged in as: {me['login']}")
#
# # Create a test repo
# # new_repo = auth_client.create_repo("my-api-test-repo", description="Created via Python Client")
# # print(f"Created repo at: {new_repo['html_url']}")