Scripting the GitHub API
4 learning objectives · 6 key terms · 4 commands · 1 diagrams · 5 quiz questions
Scripting the GitHub API
Professional PracticeWhat you'll be able to do
- Choose between gh CLI, REST, and GraphQL for automation tasks
- Paginate and filter API responses correctly
- Authenticate scripts with fine-grained tokens and Apps
- Respect rate limits and handle them gracefully
The idea, in plain language
Everything clickable in GitHub exists in the API, in three flavors: gh api for one-liners (authenticated, jq-filterable), REST for explicit resource scripting (repos, issues, runs — paginated, predictable), and GraphQL for precise nested queries (exactly the fields you name, one round trip). Choosing well matters: gh api for terminal work, REST for straightforward automation, GraphQL when nesting or rate budgets bite.
Authentication scales with blast radius: fine-grained personal tokens (scoped per repository, expiring) for scripts, GitHub Apps for production integrations (installable, permissioned, short-lived tokens). Rate limits (5,000/hour authenticated REST, tighter for search; GraphQL counts points) demand pagination discipline, conditional requests (ETag caching), and exponential backoff — automation that hammers gets throttled loudly.
Key terms
- gh api
- One-liner authenticated API access with --jq filtering and :owner/:repo magic.
- REST
- Resource endpoints (repos, issues, actions) with pagination and standard verbs.
- GraphQL
- Single-endpoint queries naming exact fields; nested data in one round trip.
- fine-grained PAT
- Personal token scoped per repository with expiry — least privilege for scripts.
- rate limit
- Hourly request budgets; secondary limits punish bursts and concurrency.
- pagination
- Paged results navigated via page/per_page or cursor links — never assume one page.
How it works, step by step
- 1Start with gh api
gh api repos/:owner/:repo --jq .stargazers_count proves auth, shape, and filtering in one line before writing any script.
probebashgh api repos/:owner/:repo --jq '{stars: .stargazers_count, open_issues}'
- 2Paginate completely
gh api --paginate collects all pages; raw scripts follow Link headers or cursors — partial pages silently undercount.
paginatebashgh api --paginate repos/:owner/:repo/issues --jq 'length'
- 3Authenticate minimally
Fine-grained tokens scoped to needed repositories with expiry; Apps for production with install-scoped permissions.
authbash# GH_TOKEN with repo scope, expiring in 30 days gh api user --jq .login
- 4Go GraphQL when nested
One query fetching repository plus recent pull requests plus reviews beats a dozen REST round trips — and spends rate budget once.
graphqlbashgh api graphql -f query='{ repository(owner:"ada",name:"app") { stargazerCount } }' --jq .data
- 5Respect limits
Check x-ratelimit-remaining, cache with ETags, back off exponentially — throttled automation fails loudly at 3am.
limitsbashgh api rate_limit --jq .resources.core
Commands worth memorising
Every block below is copy-ready — use the Copy button, then paste it into your terminal. Expected output is shown underneath so you know what “working” looks like.
gh api repos/:owner/:repo --jq '{stars: .stargazers_count}'
{"stars": 128}:owner/:repo fill from the current clone; --jq keeps output script-sized.
gh api --paginate repos/:owner/:repo/issues --jq 'length'
47
--paginate walks every page; without it you count one page and underreport.
gh api rate_limit --jq .resources.core{"limit": 5000, "remaining": 4987, "reset": 1727188800}Read before bulk jobs; schedule heavy syncs against reset windows.
gh api graphql -f query={repository(owner:"ada",name:"app"){stargazerCount}}
{"data": {"repository": {"stargazerCount": 128}}}One round trip for nested data that REST would fetch across endpoints.
Workflow diagrams
| Need | Use | Why |
|---|---|---|
| One-liners, checks | gh api + --jq | Authenticated, zero boilerplate |
| Straightforward automation | REST scripts | Predictable resources, easy pagination |
| Nested data, tight budgets | GraphQL | Exact fields, one round trip |
| Production integrations | GitHub Apps | Install-scoped, short-lived tokens |
Start at the terminal, descend to scripts and precise queries as needs grow.
- Prototype every automation as gh api one-liners first.
- Promote stable ones to REST scripts with pagination discipline.
- Reach GraphQL when nesting or budgets demand precision.
Worked example
A nightly stale-issue report assembled from paginated API data.
gh api --paginate repos/:owner/:repo/issues --jq '[.[] | select(.state=="open")] | length' # open issues: 12 gh api repos/:owner/:repo --jq .open_issues_count # cross-checks the same number from metadata
Two independent counts agree: 12 open issues, no silent pagination loss.
Where you'll use it
Common mistakes
- Counting one page of results as the total.
- Broad personal tokens where fine-grained expiring ones fit.
- Ignoring rate headers until automation gets throttled overnight.
- Hand-rolling nested REST calls GraphQL would do once.
Best practices
- Prototype as gh api one-liners before writing scripts.
- Paginate completely; cross-check counts against metadata.
- Scope tokens minimally with expirations; prefer Apps in production.
- Cache with ETags and back off exponentially under limits.
- Choose GraphQL for nested data, REST for the straightforward.
Hands-on exercise
Automate one report
Ship a scheduled, cross-checked API report.
- Probe endpoints with gh api --jq until the needed fields appear.
- Write a paginated query counting something real (open issues, aging PRs).
- Cross-check against a metadata count and reconcile differences.
- Schedule it (Actions cron) with a fine-grained token.
- Add rate-header logging so throttling is visible before it bites.
💡 Hint: --paginate plus a metadata cross-check is the whole correctness story.
Done when: A scheduled report whose numbers you trust, with minimal scopes and visible budgets.
Checkpoint quiz
0 of 5 answered · 0 correct
- Multiple choiceQ1
When is GraphQL preferable to REST?
- Multiple choiceQ2
What does --paginate guard against?
- True or falseQ3
True or false: fine-grained tokens with expiry are preferable to broad classic tokens for scripts.
- TroubleshootingQ4
Overnight automation started failing with rate errors. First move?
- Multiple choiceQ5
Why prefer GitHub Apps over personal tokens for production integrations?
Module summary
- Prototype with gh api one-liners; promote stable needs to scripts.
- Paginate completely and cross-check counts against metadata.
- Scope tokens minimally with expirations; prefer Apps in production.
- Choose GraphQL for nested data and tight budgets.
- Observe rate headers; cache and back off before throttling hits.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Put the GitHub course to work: open one of the company-wise repositories and follow the workflow you just learned, branch to release.