0Pricing
AI Agents · Lesson

GitHub REST API Overview

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

GitHub REST API Overview is a free AI Agents lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AI Agents learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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

GitHub App Authentication

For production agents, GitHub Apps are preferred over PATs. They have fine-grained permissions, can be installed on specific repos, and use short-lived installation tokens that auto-rotate. Use github.GithubIntegration to generate installation tokens.

import os
import github

APP_ID = os.environ['GITHUB_APP_ID']
PRIVATE_KEY = os.environ['GITHUB_APP_PRIVATE_KEY']  # PEM content
INSTALLATION_ID = os.environ['GITHUB_INSTALLATION_ID']

# Create GitHub App client
auth = github.Auth.AppAuth(APP_ID, PRIVATE_KEY)
gi = github.GithubIntegration(auth=auth)

# Get installation access token (expires in 1 hour)
installation = gi.get_installation(int(INSTALLATION_ID))
access_token = gi.get_access_token(int(INSTALLATION_ID))

# Use the token with a standard Github client
g = github.Github(token=access_token.token)
print(f'App authenticated, token expires: {access_token.expires_at}')

Rate Limits: 5000 Requests Per Hour

The GitHub REST API allows 5,000 requests per hour for authenticated users. Each API call (even paginated ones) counts. Check your remaining quota before running batch operations — if you run out, all requests return 403 Forbidden until the rate limit resets.

from github import Github
import os

g = Github(token=os.environ['GITHUB_TOKEN'])

# Check current rate limit status
rate_limit = g.get_rate_limit()
core = rate_limit.core

print(f'Remaining: {core.remaining}/{core.limit} requests')
print(f'Resets at: {core.reset}')

# Calculate time until reset
import datetime
now = datetime.datetime.utcnow()
reset_in = (core.reset.replace(tzinfo=None) - now).seconds
print(f'Reset in: {reset_in // 60}m {reset_in % 60}s')

# Check before heavy operations
if core.remaining < 100:
    print('WARNING: Rate limit nearly exhausted!')

Getting a Repository Object

The repo object is the starting point for almost all GitHub operations. Get it with g.get_repo('owner/name'). It contains metadata (stars, forks, description, visibility) and methods to access issues, PRs, commits, releases, and more.

from github import Github
import os

g = Github(token=os.environ['GITHUB_TOKEN'])
repo = g.get_repo('myorg/myrepo')

# Repository metadata
print(f'Full name: {repo.full_name}')
print(f'Description: {repo.description}')
print(f'Default branch: {repo.default_branch}')
print(f'Stars: {repo.stargazers_count}')
print(f'Forks: {repo.forks_count}')
print(f'Open issues: {repo.open_issues_count}')
print(f'Private: {repo.private}')
print(f'Language: {repo.language}')
print(f'Created: {repo.created_at}')
print(f'Last push: {repo.pushed_at}')

API Pagination — PaginatedList

GitHub API calls that return many items (issues, commits, PRs) return a PaginatedList. You can iterate over it like a regular list — PyGitHub fetches pages automatically as you iterate. However, calling len() on a PaginatedList fetches all pages, which can be expensive.

from github import Github
import os

g = Github(token=os.environ['GITHUB_TOKEN'])
repo = g.get_repo('myorg/myrepo')

# PaginatedList: fetch pages lazily as you iterate
issues = repo.get_issues(state='open')  # returns PaginatedList

# Iterate — fetches pages 30 at a time automatically
for issue in issues:
    print(f'#{issue.number}: {issue.title}')

# Get first N items without fetching everything
first_10 = list(issues[:10])  # only fetches first page

# Count (WARNING: fetches ALL pages)
total_open = issues.totalCount  # uses the count from API metadata, not iteration

Handling Rate Limit Exceptions

When you exceed the rate limit, PyGitHub raises github.GithubException.RateLimitExceededException. Handle it by checking the reset time and sleeping until the limit resets. Build this into a retry wrapper to make any GitHub call resilient.

from github import Github
from github.GithubException import RateLimitExceededException
import os
import time
import datetime

g = Github(token=os.environ['GITHUB_TOKEN'])

def github_call_with_rate_limit(func, *args, **kwargs):
    while True:
        try:
            return func(*args, **kwargs)
        except RateLimitExceededException:
            rate_limit = g.get_rate_limit()
            reset_time = rate_limit.core.reset.replace(tzinfo=None)
            now = datetime.datetime.utcnow()
            wait_seconds = (reset_time - now).total_seconds() + 10

            print(f'Rate limit exceeded. Sleeping {wait_seconds:.0f}s until reset...')
            time.sleep(max(wait_seconds, 1))

# Usage
repo = github_call_with_rate_limit(
    g.get_repo, 'myorg/myrepo'
)

Searching Across GitHub

Use g.search_issues(), g.search_repositories(), and g.search_code() to run GitHub's search across all public (and your private) repos. These use the Search API with a separate rate limit of 30 requests per minute.

from github import Github
import os

g = Github(token=os.environ['GITHUB_TOKEN'])

# Search issues across all your repos
results = g.search_issues(
    query='is:open is:issue label:bug user:myorg',
    sort='created',
    order='desc'
)

print(f'Found {results.totalCount} open bugs')
for issue in results[:10]:
    print(f'{issue.repository.full_name}#{issue.number}: {issue.title}')

# Search for repos using a specific package
repos = g.search_repositories(
    query='topic:machine-learning language:python stars:>100'
)
for repo in repos[:5]:
    print(f'{repo.full_name}: {repo.stargazers_count} stars')

Working with Multiple Repos

Agents often need to operate across multiple repos in an organization. Use g.get_organization() to list all repos in an org, then process them in a loop. Filter by language, archived status, or activity date to avoid processing inactive repos.

from github import Github
import os
import datetime

g = Github(token=os.environ['GITHUB_TOKEN'])
org = g.get_organization('myorg')

# Get all active Python repos
cutoff = datetime.datetime.now() - datetime.timedelta(days=180)

active_repos = [
    repo
    for repo in org.get_repos(type='all')
    if (
        not repo.archived
        and repo.language == 'Python'
        and repo.pushed_at
        and repo.pushed_at.replace(tzinfo=None) > cutoff
    )
]

print(f'Active Python repos: {len(active_repos)}')
for repo in active_repos[:5]:
    print(f'  {repo.name}: last push {repo.pushed_at.date()}')

Reading File Contents from a Repo

Use repo.get_contents(path) to read any file from a repo. The content is base64-encoded, but PyGitHub decodes it automatically via the .decoded_content property. Specify a branch or commit SHA with the ref parameter.

from github import Github
import os

g = Github(token=os.environ['GITHUB_TOKEN'])
repo = g.get_repo('myorg/myrepo')

# Read a file from the default branch
contents = repo.get_contents('README.md')
readme_text = contents.decoded_content.decode('utf-8')
print(f'README ({len(readme_text)} chars):')
print(readme_text[:200])

# Read from a specific branch
requirements = repo.get_contents(
    'requirements.txt',
    ref='feature/new-deps'
)
deps = requirements.decoded_content.decode('utf-8')
print('Dependencies:', deps[:300])

Error Handling for Common GitHub Exceptions

PyGitHub raises GithubException for all API errors. Common subclasses: UnknownObjectException (404 — repo or issue not found), BadCredentialsException (401 — bad token), RateLimitExceededException (403 — rate limit). Always catch these specifically.

from github import Github
from github.GithubException import (
    GithubException, UnknownObjectException,
    BadCredentialsException, RateLimitExceededException
)
import os

g = Github(token=os.environ['GITHUB_TOKEN'])

def get_repo_safely(repo_full_name):
    try:
        return g.get_repo(repo_full_name)
    except BadCredentialsException:
        print('ERROR: GitHub token is invalid or expired')
        return None
    except UnknownObjectException:
        print(f'ERROR: Repo not found: {repo_full_name}')
        print('Check: typo in name? Private repo you can\'t access?')
        return None
    except RateLimitExceededException:
        print('ERROR: GitHub rate limit exceeded, retry later')
        return None
    except GithubException as e:
        print(f'GitHub API error {e.status}: {e.data}')
        return None

Quick Check: Rate Limit

Test your understanding of GitHub API rate limits.

GitHub REST API Recap

You can now connect to GitHub with PyGitHub:

  • Github(token=) or Github(auth=Auth.Token(...)) for PAT authentication
  • GitHub Apps with GithubIntegration for production agents with fine-grained permissions
  • Rate limit: 5,000 req/hr; check with g.get_rate_limit(); handle RateLimitExceededException
  • PaginatedList: iterate lazily; use .totalCount for counts without fetching all pages
  • g.get_repo('owner/name') — the entry point for repo-level operations
  • Catch UnknownObjectException (404), BadCredentialsException (401) explicitly

Frequently asked questions

Is the “GitHub REST API Overview” lesson free?

Yes — the full text of “GitHub REST API Overview” is free to read here on the web, and the AI Agents course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AI Agents course, upgrade to CoddyKit PRO.

What will I learn in “GitHub REST API Overview”?

PyGitHub library, personal access tokens, and API rate limits. You practise AI Agents with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start AI Agents?

No prior experience is required. AI Agents on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “GitHub REST API Overview” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this AI Agents lesson?

Yes. Every AI Agents lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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