Hey there, fellow dev! Ready to supercharge your workflow with GitHub's API? You're in the right place. We'll be using PyGithub to make our lives easier, so buckle up!
GitHub's API is a powerhouse for automating tasks, fetching data, and integrating GitHub into your projects. Whether you're building a CI/CD pipeline, a code analysis tool, or just want to automate some tedious tasks, this guide's got you covered.
First things first, let's get our environment ready:
pip install PyGithub
Now, head over to your GitHub settings and generate a Personal Access Token. Keep it safe; we'll need it soon!
Let's dive in and authenticate:
from github import Github # Replace with your token g = Github("your-access-token-here") try: user = g.get_user() print(f"Successfully authenticated as {user.login}") except Exception as e: print(f"Authentication failed: {e}")
repo = g.get_repo("octocat/Hello-World") print(f"Repo: {repo.full_name}") print(f"Stars: {repo.stargazers_count}")
# Create an issue repo.create_issue(title="Found a bug", body="Details here...") # List pull requests pulls = repo.get_pulls(state='open', sort='created', base='main') for pr in pulls: print(f"PR #{pr.number}: {pr.title}")
user = g.get_user("octocat") print(f"User: {user.name}") print(f"Followers: {user.followers}") org = g.get_organization("github") print(f"Organization: {org.name}") print(f"Public repos: {org.public_repos}")
PyGithub handles pagination for you, but here's how to work with it explicitly:
repos = user.get_repos() for repo in repos: print(repo.name) if repos.totalCount >= 100: break
rate_limit = g.get_rate_limit() print(f"Remaining requests: {rate_limit.core.remaining}")
repo.create_hook("web", {"url": "http://example.com/webhook", "content_type": "json"}, events=["push", "pull_request"])
Here's a quick example to get your creative juices flowing:
def get_repo_stats(repo_name): repo = g.get_repo(repo_name) return { "name": repo.full_name, "stars": repo.stargazers_count, "forks": repo.forks_count, "open_issues": repo.open_issues_count } repos = ["pytorch/pytorch", "tensorflow/tensorflow", "scikit-learn/scikit-learn"] stats = [get_repo_stats(repo) for repo in repos] for stat in stats: print(f"{stat['name']}: {stat['stars']} stars, {stat['forks']} forks, {stat['open_issues']} open issues")
You're now armed with the knowledge to build powerful GitHub integrations! Remember, the PyGithub docs and GitHub API docs are your best friends for diving deeper.
Now go forth and code something awesome! 🚀