0PricingLogin
AI Agents · Lesson

GitHub REST API Overview

PyGitHub library, personal access tokens, and API rate limits.

PyGitHub — The Python GitHub Client

PyGitHub is the most popular Python library for the GitHub REST API. It wraps the raw HTTP API with Python objects representing repos, issues, PRs, commits, and users. Almost every GitHub automation task starts with Github(token=) and g.get_repo().

# Install: pip install PyGitHub
from github import Github
import os

# Authenticate with a personal access token
g = Github(token=os.environ['GITHUB_TOKEN'])

# Get the authenticated user
user = g.get_user()
print(f'Logged in as: {user.login}')
print(f'Name: {user.name}')
print(f'Public repos: {user.public_repos}')

# Get a specific repository
repo = g.get_repo('octocat/Hello-World')
print(f'Repo: {repo.full_name}')
print(f'Stars: {repo.stargazers_count}')

Authentication: Personal Access Token

The simplest authentication is a Personal Access Token (PAT) — a long-lived token tied to your GitHub account. Create one at github.com → Settings → Developer settings → Personal access tokens. Store it in an environment variable, never in code. Use fine-grained PATs for better security (scope to specific repos).

from github import Github, Auth
import os

# Method 1: Classic token (works with PyGitHub)
token = os.environ['GITHUB_TOKEN']
g = Github(token=token)

# Method 2: Auth object (recommended for PyGitHub >= 1.59)
auth = Auth.Token(os.environ['GITHUB_TOKEN'])
g = Github(auth=auth)

# Test authentication
try:
    user = g.get_user()
    print(f'Authenticated as {user.login}')
except Exception as e:
    print(f'Auth failed: {e}')
    print('Check: Is GITHUB_TOKEN set? Has it expired?')

g.close()  # close the connection when done

All lessons in this course

  1. GitHub REST API Overview
  2. Listing and Managing Issues
  3. Automated PR Review Comments
  4. Commit History and Diff Analysis
← Back to AI Agents