skip to content

gh api and Scripting

When no subcommand exists, gh api gives you authenticated REST and GraphQL with pagination and jq filtering built in. It is the standard way to script bulk org-wide changes and to automate GitHub from inside a workflow.

on this pageshow

questions

6

With the GitHub CLI, what does gh api handle for you that a hand-written curl call to the GitHub API does not?

level: juniorimportance: must knowfreq 45%

answer

  1. the login you already have
  2. host and URL prefix resolved
  3. braces filled from the current repository
  4. a jq that ships inside gh
  5. what the exit status means

basics

~20 s

gh api reuses gh's own credentials, resolves the host and API prefix, fills {owner} and {repo} from the current repository, builds JSON bodies, follows pages, filters with built-in jq and exits non-zero when the API returns an error.

solid answer

~50 s

`gh api <endpoint>` is the GitHub CLI's escape hatch for anything that has an API endpoint but no gh subcommand. It authenticates with whatever gh already uses (the stored login on a laptop, a token in `GH_TOKEN` in automation), so no token is typed into the command. It resolves the host (github.com unless `--hostname` or `GH_HOST` names another) and prepends the API prefix, and it replaces `{owner}`, `{repo}` and `{branch}` in the path from the repository you are standing in or from `GH_REPO`. On top it adds `-f`/`-F` to build the request body, `--paginate` to follow every page, `--jq` and `--template` to shape output without installing jq, and `--cache` for repeated reads. When the API answers with an error, gh prints the message on standard error and exits with status 1, so a script stops instead of parsing an error document as data.

go deeper

for a junior

Recall the concrete list: stored credentials, host resolution, repository placeholders, field flags, pagination, built-in jq and a failing exit status. Being able to show one real call matters more than reciting flags.

for a middle

Explain where each convenience comes from: placeholders from the local remote or GH_REPO, the method switching to POST when fields appear, per_page set to 100 under --paginate, and error text going to standard error.

for a senior

Show the production judgement: scripts that rely on exit status, GH_REPO in places with no clone, caching for repeated reads, and knowing that back-off on rate limits stays the script's responsibility.

for a principal

Weigh gh api scripts against a real client library or an app for long-lived automation, and argue where a shell script stops being the cheapest maintainable option.

## What `gh api` is `gh api` is the GitHub CLI command that "makes an authenticated HTTP request to the GitHub API and prints the response". Its single argument is either a **REST path** such as `repos/{owner}/{repo}/releases` or the literal word `graphql` for the GraphQL API. Everything gh's own subcommands do not cover (repository rulesets, custom properties, team membership, organisation settings) is still reachable through it, which is why it is the usual starting point for scripts that automate GitHub. The comparison with `curl` is the classic way interviewers open the topic, because it forces you to list what the wrapper actually adds rather than saying "it is easier". ## What it does that a raw HTTP call does not | Concern | Hand-written `curl` | `gh api` | |---|---|---| | **Credentials** | You add an `Authorization` header with a token, often visible in shell history | Uses gh's stored login, or `GH_TOKEN` / `GH_ENTERPRISE_TOKEN` in automation | | **Host and URL** | You type the full API URL, including an Enterprise Server's own prefix | github.com by default; `--hostname` or `GH_HOST` picks another host and gh adds the prefix | | **Repository context** | You type the owner and repository every time | `{owner}`, `{repo}` and `{branch}` are filled from the current repository or `GH_REPO` | | **Request body** | You hand-write JSON | `-f` and `-F` build JSON, including nested keys, arrays and `@file` values | | **Paging** | You parse the `Link` header yourself | `--paginate` follows every page | | **Output** | Raw bytes; jq must be installed | Pretty-printed on a terminal; `--jq` and `--template` built in | | **Errors** | Exit status 0 on an HTTP 404 unless you add `--fail` | Message on standard error, exit status 1 | ## The pieces, one by one - **Authentication.** gh sends the token it would use for any other command. The token-selection rules (which variable wins, how Enterprise hosts differ) belong to the material on gh authentication; for `gh api` the point is that the command line carries no secret. - **Placeholders.** The help text says `{owner}`, `{repo}` and `{branch}` "will get replaced with values from the repository of the current directory or the repository specified in the `GH_REPO` environment variable". Outside a clone and without `GH_REPO`, a path that uses them fails, so scripts either set `GH_REPO` or write the owner and name out. - **Parameters.** `-f key=value` adds a string; `-F key=value` adds a typed value and can read a file with `@path`. Adding any parameter switches the default method from `GET` to `POST`, so `--method GET` is needed to send them as a query string. - **Pagination.** `--paginate` keeps requesting until there is no next page; for REST it also asks for 100 items per page unless you set `per_page` yourself. - **Output shaping.** `--jq` evaluates a jq expression with gh's built-in implementation, so the `jq` binary does not have to be installed; `--template` applies a Go template. `--silent` drops the body, `-i/--include` prints the status line and headers, and `--verbose` prints the whole exchange. - **Caching.** `--cache 1h` stores the response and reuses it, which helps a script that reads the same slow-changing endpoint many times. ## Failure behaviour, which is what scripts depend on When the response status is 400 or above, gh still writes the response body to standard output, then prints a line such as `gh: Not Found (HTTP 404)` on standard error and exits with **status 1**, the CLI's general failure code (a command that needs authentication and has none exits with 4). A `--jq` filter is skipped for a JSON error response, so the filter never runs against an error document. For `graphql`, an `errors` array in the response counts as a failure even when the HTTP status is 200. That contract is what makes `set -e` style scripting safe: a missing repository or a forbidden call stops the script at the line that failed. Rate limiting is a failure the script has to plan for itself: gh does not pause and resend a refused call, so back-off is the script's job, and the rate-limit rules belong to the material on the GitHub API. ## When not to reach for it 1. If a gh subcommand already does the job (`gh pr list`, `gh release create`), use it: the subcommand knows the right endpoint, handles its paging and offers `--json` output. 2. If you are writing a long-lived service rather than a script, a proper API client library with its own retry and token handling is usually the better tool. 3. If the call is one-off and interactive, `gh api` still beats `curl` simply because it needs no token pasting.

  • Why does gh api repos/{owner}/{repo} fail in an empty directory?
    The braces are filled from the repository of the current directory, which gh finds through the local Git remotes. With no clone there is nothing to infer from, so gh reports that it cannot determine the repository. Set `GH_REPO=acme/payments` or write the owner and name into the path.
  • How do you call an Enterprise Server host instead of github.com with gh api?
    Pass `--hostname ghe.example.com` on the command, or set `GH_HOST` for the whole script. gh then builds that host's API URL and uses the credentials stored for it, or the Enterprise token variable in automation.

  • gh api is just curl with a shorter name and no extra behaviour
  • You must install the jq binary before gh api --jq works
  • gh api exits 0 on a 404, so scripts must parse the body
  • The {owner} placeholder always means the logged-in user
  • You have to paste a token into every gh api call
open as a page

With the GitHub CLI's gh api, how do -f/--raw-field and -F/--field differ, and when does adding them change the HTTP method?

level: middleimportance: must knowfreq 36%

basics

~20 s

-f always sends a string; -F converts true, false, null and integers to JSON types, fills {owner}/{repo}/{branch} and reads @file. Adding either switches gh api from GET to POST unless --method is given; --method GET sends them as a query string.

open as a page

With the GitHub CLI, how do gh api --paginate, --jq and --slurp interact when a script lists every repository in an organisation?

level: middleimportance: should knowfreq 26%

basics

~20 s

--paginate follows every next page (100 items each for REST); --jq then runs once per page, not over the whole set; --slurp wraps all pages into one array but cannot be combined with --jq, so whole-set filtering happens in an external jq.

open as a page

In a nightly GitHub Actions workflow that runs the GitHub CLI to open issues across an organisation, how does gh get its token and what bounds it?

level: seniorimportance: should knowfreq 22%

basics

~20 s

gh on a runner has no login, so the step sets GH_TOKEN, usually from github.token. The workflow's permissions block bounds that token, and it only reaches the workflow's own repository, so organisation-wide writes need a different token.

open as a page

With the GitHub CLI, what is a gh extension, how does gh install and run one, and how do you keep it reproducible in CI?

level: seniorimportance: nice to knowfreq 8%

basics

~20 s

A gh extension is a repository named gh-NAME holding an executable or release binaries; gh extension install fetches it and gh NAME runs it with your arguments. Pin it with --pin to a tag or commit so CI stays reproducible.

open as a page

With the GitHub CLI, what must a query contain for gh api graphql --paginate to fetch every page, and what can it not page through?

level: seniorimportance: nice to knowfreq 9%

basics

~20 s

The query must declare a nullable $endCursor: String variable, pass it as after: on the connection, and select pageInfo { hasNextPage endCursor }. gh pages only through the connection whose pageInfo it meets first; nested connections need their own queries.

open as a page