AI Agents · บทเรียน

ภาพรวม GitHub REST API

ไลบรารี PyGitHub โทเค็นเข้าถึงส่วนบุคคล และการจำกัดอัตรา API

บทเรียน 1 จาก 413 ขั้นตอน

ภาพรวม GitHub REST API เป็นบทเรียน AI Agents ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน AI Agents และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส AI Agents มีบทเรียนทั้งหมด 4 บทเรียน

PyGitHub — ไคลเอนต์ GitHub สำหรับ Python

PyGitHub เป็นไลบรารี Python ยอดนิยมสำหรับ REST API ของ GitHub โดยห่อหุ้ม API HTTP โดยตรงด้วยออบเจ็กต์ Python ที่แทนคลังโค้ด ปัญหา PR คอมมิต และผู้ใช้ แทบทุกงานอัตโนมัติบน GitHub เริ่มต้นด้วย Github(token=) และ 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}')

การยืนยันตัวตน: โทเค็นการเข้าถึงส่วนบุคคล

วิธีการยืนยันตัวตนที่ง่ายที่สุดคือ โทเค็นการเข้าถึงส่วนบุคคล (PAT) ซึ่งเป็นโทเค็นที่มีอายุการใช้งานยาวนานและผูกกับบัญชี GitHub ของคุณ สร้างโทเค็นได้ที่ github.com → การตั้งค่า → การตั้งค่านักพัฒนา → โทเค็นการเข้าถึงส่วนบุคคล จัดเก็บโทเค็นไว้ในตัวแปรสภาพแวดล้อม ห้ามเก็บไว้ในโค้ด ใช้ PAT แบบกำหนดสิทธิ์ละเอียดเพื่อความปลอดภัยที่ดีขึ้น โดยกำหนดขอบเขตให้เฉพาะคลังโค้ดที่ระบุ

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

สำหรับเอเจนต์ที่ใช้งานจริง ควรใช้ แอป GitHub แทน PAT แอปเหล่านี้มีสิทธิ์แบบกำหนดรายละเอียด ติดตั้งในคลังโค้ดที่ระบุได้ และใช้โทเค็นการติดตั้งอายุสั้นที่หมุนเวียนโดยอัตโนมัติ ใช้ github.GithubIntegration เพื่อสร้างโทเค็นการติดตั้ง

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}')

ข้อจำกัดอัตรา: 5,000 คำขอต่อชั่วโมง

REST API ของ GitHub อนุญาตให้ ผู้ใช้ที่ยืนยันตัวตนส่งคำขอได้ 5,000 ครั้งต่อชั่วโมง การเรียก API แต่ละครั้ง (แม้เป็นการเรียกแบบแบ่งหน้า) จะถูกนับรวม ตรวจสอบโควตาที่เหลือก่อนดำเนินการแบบกลุ่ม หากใช้โควตาหมด คำขอทั้งหมดจะส่งคืน 403 Forbidden จนกว่าข้อจำกัดอัตราจะรีเซ็ต

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!')

การรับออบเจ็กต์คลังโค้ด

ออบเจ็กต์ repo เป็นจุดเริ่มต้นของการดำเนินการบน GitHub เกือบทั้งหมด รับออบเจ็กต์นี้ด้วย g.get_repo('owner/name') ออบเจ็กต์นี้มีข้อมูลเมตา (ดาว จำนวนการฟอร์ก คำอธิบาย การเปิดเผย) และเมธอดสำหรับเข้าถึงปัญหา PR คอมมิต รุ่นเผยแพร่ และอื่น ๆ

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 — PaginatedList

การเรียก API ของ GitHub ที่ส่งคืนรายการจำนวนมาก (ปัญหา คอมมิต PR) จะส่งคืน PaginatedList คุณสามารถวนซ้ำได้เหมือนรายการทั่วไป โดย PyGitHub จะดึงหน้าเพิ่มเติมโดยอัตโนมัติระหว่างการวนซ้ำ อย่างไรก็ตาม การเรียก len() กับ PaginatedList จะดึงข้อมูลทุกหน้า ซึ่งอาจใช้ทรัพยากรมาก

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

การจัดการข้อยกเว้นจากข้อจำกัดอัตรา

เมื่อคุณส่งคำขอเกินข้อจำกัดอัตรา PyGitHub จะยก github.GithubException.RateLimitExceededException ขึ้นมา จัดการกรณีนี้โดยตรวจสอบเวลารีเซ็ต แล้วหยุดรอจนกว่าข้อจำกัดจะรีเซ็ต ควรสร้างสิ่งนี้ไว้ในตัวห่อการลองใหม่ เพื่อให้การเรียก GitHub ใด ๆ รับมือกับข้อผิดพลาดได้อย่างทนทาน

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'
)

การค้นหาทั่ว GitHub

ใช้ g.search_issues() g.search_repositories() และ g.search_code() เพื่อค้นหาบน GitHub ในคลังโค้ดสาธารณะทั้งหมด (รวมถึงคลังส่วนตัวของคุณ) การค้นหาเหล่านี้ใช้ Search API ซึ่งมีข้อจำกัดอัตราแยกต่างหากที่ 30 คำขอต่อนาที

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')

การทำงานกับหลายคลังโค้ด

เอเจนต์มักต้องทำงานกับคลังโค้ดหลายแห่งภายในองค์กร ใช้ g.get_organization() เพื่อแสดงรายการคลังโค้ดทั้งหมดในองค์กร แล้วประมวลผลในลูป กรองตามภาษา สถานะเก็บถาวร หรือวันที่มีกิจกรรม เพื่อหลีกเลี่ยงการประมวลผลคลังโค้ดที่ไม่มีการใช้งาน

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()}')

การอ่านเนื้อหาไฟล์จากคลังโค้ด

ใช้ repo.get_contents(path) เพื่ออ่านไฟล์ใด ๆ จากคลังโค้ด เนื้อหาจะถูกเข้ารหัสแบบ base64 แต่ PyGitHub จะถอดรหัสให้อัตโนมัติผ่านพร็อพเพอร์ตี .decoded_content ระบุสาขาหรือ SHA ของคอมมิตด้วยพารามิเตอร์ ref

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])

การจัดการข้อผิดพลาดสำหรับข้อยกเว้น GitHub ทั่วไป

PyGitHub จะยก GithubException ขึ้นมาสำหรับข้อผิดพลาดจาก API ทั้งหมด คลาสย่อยที่พบบ่อย ได้แก่ UnknownObjectException (404 — ไม่พบคลังโค้ดหรือปัญหา) BadCredentialsException (401 — โทเค็นไม่ถูกต้อง) และ RateLimitExceededException (403 — เกินข้อจำกัดอัตรา) ควรดักจับข้อยกเว้นเหล่านี้โดยเฉพาะเสมอ

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

ตรวจสอบความเข้าใจอย่างรวดเร็ว: ข้อจำกัดอัตรา

ทดสอบความเข้าใจเกี่ยวกับข้อจำกัดอัตราของ GitHub API

สรุป GitHub REST API

ขณะนี้คุณสามารถเชื่อมต่อกับ GitHub ด้วย PyGitHub ได้แล้ว:

  • Github(token=) หรือ Github(auth=Auth.Token(...)) สำหรับการยืนยันตัวตนด้วย PAT
  • แอป GitHub ที่ใช้ GithubIntegration สำหรับเอเจนต์ที่ใช้งานจริงและมีสิทธิ์แบบกำหนดรายละเอียด
  • ข้อจำกัดอัตรา: 5,000 คำขอต่อชั่วโมง ตรวจสอบด้วย g.get_rate_limit() และจัดการ RateLimitExceededException
  • PaginatedList: วนซ้ำแบบประเมินเมื่อจำเป็น ใช้ .totalCount เพื่อนับจำนวนโดยไม่ต้องดึงข้อมูลทุกหน้า
  • g.get_repo('owner/name') — จุดเริ่มต้นสำหรับการดำเนินการระดับคลังโค้ด
  • ดักจับ UnknownObjectException (404) และ BadCredentialsException (401) อย่างชัดเจน
เริ่มต้นได้ฟรี

เรียนรู้ AI Agents ด้วย AI tutor — ฟรี

เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป

คอร์ส
60
บทเรียน
239

คำถามที่พบบ่อย

บทเรียน “ภาพรวม GitHub REST API” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “ภาพรวม GitHub REST API” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส AI Agents ให้อัปเกรดเป็น CoddyKit PRO คอร์ส AI Agents มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “ภาพรวม GitHub REST API”

ไลบรารี PyGitHub โทเค็นเข้าถึงส่วนบุคคล และการจำกัดอัตรา API คุณปฏิบัติ AI Agents ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน AI Agents หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน AI Agents บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน

บทเรียน “ภาพรวม GitHub REST API” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน AI Agents นี้ได้ไหม

ได้ บทเรียน AI Agents ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. ภาพรวม GitHub REST API
  2. การแสดงรายการและจัดการประเด็น
  3. ความคิดเห็นตรวจสอบ PR อัตโนมัติ
  4. ประวัติการคอมมิตและการวิเคราะห์ส่วนต่าง
← กลับไปที่ AI Agents