Learn GitHub
$ gh ghprofessional.ghapi

Scripting the GitHub API

4 learning objectives · 6 key terms · 4 commands · 1 diagrams · 5 quiz questions

$objectives

Scripting the GitHub API

Professional Practice

Module 5 of 5 · lesson 23 in this module

What 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
$concept

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

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.
$steps

How it works, step by step

  1. 1
    Start with gh api

    gh api repos/:owner/:repo --jq .stargazers_count proves auth, shape, and filtering in one line before writing any script.

    probebash
    gh api repos/:owner/:repo --jq '{stars: .stargazers_count, open_issues}'
  2. 2
    Paginate completely

    gh api --paginate collects all pages; raw scripts follow Link headers or cursors — partial pages silently undercount.

    paginatebash
    gh api --paginate repos/:owner/:repo/issues --jq 'length'
  3. 3
    Authenticate 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
  4. 4
    Go GraphQL when nested

    One query fetching repository plus recent pull requests plus reviews beats a dozen REST round trips — and spends rate budget once.

    graphqlbash
    gh api graphql -f query='{ repository(owner:"ada",name:"app") { stargazerCount } }' --jq .data
  5. 5
    Respect limits

    Check x-ratelimit-remaining, cache with ETags, back off exponentially — throttled automation fails loudly at 3am.

    limitsbash
    gh api rate_limit --jq .resources.core
$commands

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.

probe auth and shapebash
gh api repos/:owner/:repo --jq '{stars: .stargazers_count}'
Output
{"stars": 128}

:owner/:repo fill from the current clone; --jq keeps output script-sized.

count all issuesbash
gh api --paginate repos/:owner/:repo/issues --jq 'length'
Output
47

--paginate walks every page; without it you count one page and underreport.

check rate budgetbash
gh api rate_limit --jq .resources.core
Output
{"limit": 5000, "remaining": 4987, "reset": 1727188800}

Read before bulk jobs; schedule heavy syncs against reset windows.

nested query oncebash
gh api graphql -f query={repository(owner:"ada",name:"app"){stargazerCount}}
Output
{"data": {"repository": {"stargazerCount": 128}}}

One round trip for nested data that REST would fetch across endpoints.

$diagrams

Workflow diagrams

Diagram 1Choosing the automation layer

Start at the terminal, descend to scripts and precise queries as needs grow.

Reading the diagram
  1. Prototype every automation as gh api one-liners first.
  2. Promote stable ones to REST scripts with pagination discipline.
  3. Reach GraphQL when nesting or budgets demand precision.
$example

Worked example

A nightly stale-issue report assembled from paginated API data.

stale-issue reporterbash
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
Output
Two independent counts agree: 12 open issues, no silent pagination loss.
1--paginate walks every issues page; the filter keeps opens; length counts — complete by construction.
2The metadata count cross-checks: agreement proves no page was missed.
3Scheduled nightly, this becomes a dashboard number with a two-line script.
$use cases

Where you'll use it

▸Dashboards (counts, ages, owners) from jq-filtered endpoints.
▸Bulk operations (labeling, closing, assigning) scripted safely.
▸Nightly reports scheduled from paginated, cross-checked queries.
▸Production integrations as permissioned GitHub Apps.
$mistakes

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

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.
$exercise

Hands-on exercise

Automate one report

Ship a scheduled, cross-checked API report.

  1. Probe endpoints with gh api --jq until the needed fields appear.
  2. Write a paginated query counting something real (open issues, aging PRs).
  3. Cross-check against a metadata count and reconcile differences.
  4. Schedule it (Actions cron) with a fine-grained token.
  5. 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.

$quiz

Checkpoint quiz

0 of 5 answered · 0 correct

  1. Multiple choiceQ1

    When is GraphQL preferable to REST?

  2. Multiple choiceQ2

    What does --paginate guard against?

  3. True or falseQ3

    True or false: fine-grained tokens with expiry are preferable to broad classic tokens for scripts.

  4. TroubleshootingQ4

    Overnight automation started failing with rate errors. First move?

  5. Multiple choiceQ5

    Why prefer GitHub Apps over personal tokens for production integrations?

$summary

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.

Next up: The platform is scriptable; the course closes with the final assessment and capstone.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

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.