Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 36 ยท Administration and API

The GitHub API, CLI and Webhooks

Automate GitHub: call the REST and GraphQL APIs, authenticate with tokens and Apps, use the gh CLI, handle pagination and rate limits, and receive and verify webhooks.

Everything you can do in the GitHub web interface, and more, is available through APIs. That is how bots label issues, dashboards count pull requests, deploy tools update statuses and your own scripts create repositories in bulk. This lesson shows the three ways in (REST, GraphQL, the gh command line) and the push-style alternative, webhooks.

The commands below talk to the real GitHub and cannot run in this page, so they are read-only. The JavaScript stand-ins model pagination, rate limits and a webhook router with made-up data.

The REST API

The REST API lives at https://api.github.com. Resources are URLs, and the HTTP method says what to do: GET reads, POST creates, PATCH updates, PUT replaces or toggles, DELETE removes.

Terminal
# Public data needs no token (but is rate limited harder)
curl -s https://api.github.com/repos/octocat/Hello-World

# With a token: higher limits and private data
curl -s \
  -H "Authorization: Bearer $GITHUB_TOKEN" \
  -H "Accept: application/vnd.github+json" \
  -H "X-GitHub-Api-Version: 2022-11-28" \
  https://api.github.com/repos/OWNER/REPO/issues?state=open

# Create an issue
curl -s -X POST \
  -H "Authorization: Bearer $GITHUB_TOKEN" \
  -H "Accept: application/vnd.github+json" \
  https://api.github.com/repos/OWNER/REPO/issues \
  -d '{"title":"Found a bug","body":"Steps to reproduce...","labels":["bug"]}'

Responses are JSON. Status codes follow HTTP: 200 OK, 201 created, 204 no content, 401 bad or missing credentials, 403 forbidden or rate limited, 404 not found (also returned for private resources you cannot see), 422 validation failed. Send the X-GitHub-Api-Version header to pin behavior, so a future change does not surprise your script.

Authentication choices

Method Use it for
Personal access token (fine-grained) Your own scripts, limited to chosen repositories and permissions
Personal access token (classic) Older tools; broad scopes, so avoid when you can
GITHUB_TOKEN in Actions Automation inside a workflow, expires with the job
GitHub App installation token Production bots and integrations; short-lived, narrow, not tied to a person
OAuth app Letting other people sign in with GitHub in your product

Never paste a token into code or a repository; read it from an environment variable or a secret store, and see secrets for Actions.

Pagination

List endpoints return 30 items by default (up to 100 with per_page=100). The response has a Link header that points to the next page, and you follow it until there is no rel="next". The stand-in parses such a header the way a client library does.

JS Stand-in: Link header pagination (invented data)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Rate limits

Authenticated REST requests have a limit per hour (5,000 for a normal user token, more for Apps and Enterprise; much less for unauthenticated calls). Every response carries headers:

  • x-ratelimit-limit: your hourly allowance;
  • x-ratelimit-remaining: calls left;
  • x-ratelimit-reset: when the window resets, as a Unix time.

If you hit a 403 or 429 with a rate-limit message, wait until the reset time (or the retry-after header) instead of hammering the API; also avoid firing many write requests in parallel, because secondary limits protect GitHub from bursts. Use conditional requests with If-None-Match and the ETag header: a 304 Not Modified answer does not count against your limit.

GraphQL

The GraphQL API has a single endpoint (POST https://api.github.com/graphql). You ask for exactly the fields you need in one request, even across related objects, which avoids the many round trips REST sometimes needs.

GRAPHQL
query {
  repository(owner: "octocat", name: "Hello-World") {
    name
    stargazerCount
    issues(states: OPEN, first: 3) {
      totalCount
      nodes { number title author { login } }
    }
  }
}
Terminal
gh api graphql -f query='
  query { viewer { login repositories(first: 5) { nodes { name } } } }'

GraphQL has its own cost model: a "points" budget based on how many nodes your query could return. Paging uses cursors (first, after, pageInfo { hasNextPage endCursor }). Mutations change data, for example addComment. Use the Explorer in the documentation to build queries interactively.

The gh command line

gh is the official CLI. It handles authentication (gh auth login), opens pull requests from the terminal, and exposes the API.

Terminal
gh repo clone OWNER/REPO
gh issue list --label bug --state open
gh issue create --title "Crash on start" --body "See logs"
gh pr create --fill
gh pr checks
gh pr merge 42 --squash --auto
gh run list --workflow ci.yml
gh run watch
gh release create v1.0.0 --generate-notes
gh api repos/OWNER/REPO/pulls --paginate --jq '.[].title'

--json with --jq turns any listing into scriptable data, and gh api adds your credentials, handles pagination (--paginate) and lets you call any REST or GraphQL endpoint. Inside a workflow, set GH_TOKEN: ${{ github.token }} and gh just works. Extensions (gh extension install ...) add more commands.

Webhooks

Polling the API for changes wastes calls. A webhook reverses the direction: GitHub sends an HTTP POST with a JSON payload to your URL whenever a chosen event happens (push, pull request opened, issue comment, release published, check run completed, and many more). Add one in Settings -> Webhooks, choose the payload URL, content type application/json, a secret, and the events.

Each delivery includes headers:

  • X-GitHub-Event: the event name (push, pull_request...);
  • X-GitHub-Delivery: a unique id (use it to ignore duplicates);
  • X-Hub-Signature-256: sha256= plus an HMAC-SHA256 of the raw body keyed with your secret.

Always verify the signature before trusting a payload, and compare in constant time. Verification looks like this in Node.js (read-only here):

JavaScript
import { createHmac, timingSafeEqual } from "node:crypto";

function isValid(rawBody, signatureHeader, secret) {
  const expected = "sha256=" + createHmac("sha256", secret).update(rawBody).digest("hex");
  const a = Buffer.from(expected);
  const b = Buffer.from(signatureHeader ?? "");
  return a.length === b.length && timingSafeEqual(a, b);
}

Respond quickly (within about 10 seconds) with a 2xx status and do slow work in the background. The Recent Deliveries tab shows every attempt, and you can redeliver one while debugging. For local development, a tunnel tool exposes your machine; production receivers should be HTTPS only. For serious integrations, build a GitHub App, which receives webhooks for the installations it is added to, with narrowly scoped permissions.

The stand-in router below shows the shape of a receiver: dispatch on the event name and keep handlers small. The payloads are invented.

JS Stand-in: webhook event router (invented payloads)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you read the next page of a REST list response?

    The Link header contains next and last page URLs for the client to follow.
  2. 2. Which token type suits a production bot best?

    Apps have narrow permissions, short-lived tokens and are not tied to a person's account.
  3. 3. What should a webhook receiver do first with an incoming delivery?

    Verifying the signature proves the request came from GitHub and was not altered.
  4. 4. What is a main benefit of GraphQL for GitHub data?

    One query can fetch nested data and avoid many round trips; it has its own cost limits.

Summary

  • The REST API (api.github.com) and the single-endpoint GraphQL API expose nearly everything in the UI; pin a version header.
  • Authenticate with fine-grained tokens, GITHUB_TOKEN in workflows or GitHub App tokens, never with secrets in code.
  • Follow Link headers for pagination, watch rate-limit headers and use ETags.
  • gh is the scriptable terminal client; webhooks push events to your server and must be signature-verified.

Next: Project: A Complete CI Pipeline