Sub topic 12
Managing rulesets as JSON with the REST API and gh
This chapter assumes you can read JSON, have the GitHub CLI (gh) installed and authenticated, and know the ruleset parts from earlier chapters: targets, rules, bypass actors and enforcement. Here you will manage those parts as files instead of through the web form.
Why manage rulesets as JSON
The ruleset form in the web interface is fine for a first experiment. It is a poor fit for a ruleset that covers hundreds of repositories. A JSON file can be reviewed in a pull request, kept in version control, diffed against the live state, and re-applied after someone edits the ruleset by hand.
The REST API accepts and returns the same structure the form edits. A ruleset body has these top-level fields:
| Field | Purpose |
|---|---|
| `name` | Display name. Must be unique within the organisation or repository. |
| `target` | `branch`, `tag` or `push`. |
| `enforcement` | `active`, `evaluate` or `disabled`. |
| `bypass_actors` | Who may skip the rules, and how. |
| `conditions` | Which refs and (for organisation rulesets) which repositories. |
| `rules` | The list of rule objects. |
Endpoints
The same operations exist at two scopes.
| Operation | Organisation scope | Repository scope |
|---|---|---|
| List | `GET /orgs/{org}/rulesets` | `GET /repos/{owner}/{repo}/rulesets` |
| Create | `POST /orgs/{org}/rulesets` | `POST /repos/{owner}/{repo}/rulesets` |
| Read one | `GET /orgs/{org}/rulesets/{id}` | `GET /repos/{owner}/{repo}/rulesets/{id}` |
| Replace | `PUT /orgs/{org}/rulesets/{id}` | `PUT /repos/{owner}/{repo}/rulesets/{id}` |
| Delete | `DELETE /orgs/{org}/rulesets/{id}` | `DELETE /repos/{owner}/{repo}/rulesets/{id}` |
Two read-only endpoints help when you debug:
GET /repos/{owner}/{repo}/rules/branches/{branch}returns the rules that currently apply to one branch, after all rulesets have been combined.GET /orgs/{org}/rulesets/rule-suiteslists recent evaluations. These are the data behind rule insights.
The repository-scoped body does not accept repository_name, repository_id or repository_property conditions. Those only make sense when a ruleset spans repositories.
Creating a ruleset from a file
Save the ruleset body from the earlier chapter as protect-default-branch.json. Then send it with --input, so gh posts the file as the request body unchanged:
gh api \
--method POST \
-H "Accept: application/vnd.github+json" \
-H "X-GitHub-Api-Version: 2022-11-28" \
/orgs/YOUR_ORG/rulesets \
--input protect-default-branch.jsonA successful call returns 201 Created and the full ruleset, including the numeric id that every later call needs. Pinning X-GitHub-Api-Version keeps the response shape stable if GitHub releases a newer API version.
Do not build a body with repeated -f or -F flags. Those flags build flat key-value pairs. Nested arrays such as rules and bypass_actors are easier and safer to send as a file.
Finding the ruleset ID
Names are unique, so you can look up an ID by name. The --jq option applies a jq filter to the response:
ORG=YOUR_ORG
NAME=protect-default-branch
ID=$(gh api "/orgs/$ORG/rulesets" \
--jq ".[] | select(.name == \"$NAME\") | .id")
echo "Ruleset ID: $ID"The list endpoint returns summaries only. It omits rules and conditions, so fetch the single ruleset when you need the full body. The list is paginated, 30 items per page by default. With many rulesets, add --paginate.
Updating a ruleset
Update with PUT. Treat the body as a full replacement, not a patch. Fields you leave out of the body can be reset, and an omitted rules list can remove rules. The safe pattern is to download the current body, change it with jq, and send the whole result back.
This script switches a ruleset to evaluate mode and bumps the required review count:
#!/usr/bin/env bash
set -euo pipefail
ORG=YOUR_ORG
NAME=protect-default-branch
ID=$(gh api "/orgs/$ORG/rulesets" \
--jq ".[] | select(.name == \"$NAME\") | .id")
# Download the current body and keep only the fields the API accepts back.
gh api "/orgs/$ORG/rulesets/$ID" \
--jq '{name, target, enforcement, bypass_actors, conditions, rules}' \
> current.json
# Edit: evaluate mode, two required approvals.
jq '.enforcement = "evaluate"
| (.rules[] | select(.type == "pull_request")
| .parameters.required_approving_review_count) = 2' \
current.json > updated.json
# Show the difference before sending it.
diff -u current.json updated.json || true
gh api --method PUT "/orgs/$ORG/rulesets/$ID" --input updated.jsonThe jq projection in the download step drops read-only fields such as id, source, created_at, _links and current_user_can_bypass. Sending those back can cause a validation error, so keep them out of the file.
A workflow rule through the API
The required-workflow rule from the earlier chapter goes into the rules array like any other rule. You can add it with jq instead of editing JSON by hand:
jq '.rules += [{
"type": "workflows",
"parameters": {
"do_not_enforce_on_create": false,
"workflows": [{
"repository_id": 123456,
"path": ".github/workflows/org-ci.yml",
"ref": "refs/heads/main"
}]
}
}]' current.json > updated.jsonReplace 123456 with the numeric ID of the repository that stores the workflow. You can read it with gh api /repos/YOUR_ORG/shared-workflows --jq .id. The workflow file must declare an on: pull_request or on: merge_group trigger, or the check will never run on the changes it is meant to gate.
Checking the effective result
Updating a ruleset only tells you the request was accepted. To see what a branch actually receives, ask for its effective rules:
gh api /repos/YOUR_ORG/YOUR_REPO/rules/branches/main \
--jq '.[] | {type, ruleset_source, ruleset_id}'Each item in the response names the rule type and the ruleset it came from. This is the quickest way to confirm that two overlapping rulesets combined the way you predicted. It also shows which ruleset to edit when a rule is unexpectedly present.
Common errors
| Status | Typical cause | Fix |
|---|---|---|
| 401 | Not authenticated. | Run `gh auth login` or set `GH_TOKEN`. |
| 403 | Token lacks organisation administration rights. | Use a token with the permission described above, or an organisation owner account. |
| 404 | Wrong organisation, wrong ID, or no permission to see it. | GitHub returns 404 for resources you cannot access. Check the name and your rights. |
| 422 | Body failed validation. | Read the `errors` array. Common causes are a duplicate `name`, an unknown rule `type`, or sending read-only fields. |
A 422 for a duplicate name usually means you used POST when you meant PUT. Look up the ID first.
Keeping files and live state in sync
A common practice is a small repository that holds one JSON file per ruleset and a workflow that applies them on merge. The apply step needs to create a ruleset if it does not exist and replace it if it does:
#!/usr/bin/env bash
set -euo pipefail
ORG=YOUR_ORG
FILE=protect-default-branch.json
NAME=$(jq -r .name "$FILE")
ID=$(gh api "/orgs/$ORG/rulesets" --paginate \
--jq ".[] | select(.name == \"$NAME\") | .id")
if [ -z "$ID" ]; then
gh api --method POST "/orgs/$ORG/rulesets" --input "$FILE"
else
gh api --method PUT "/orgs/$ORG/rulesets/$ID" --input "$FILE"
fiUse a GitHub App installation token or a dedicated machine account for this job, not a personal token. The credential can change enforcement across the whole organisation, so give it nothing beyond that permission and protect the repository that holds the files with its own ruleset.
Exercise
You have a PUT script that downloads a ruleset, edits .rules, and sends the result back. The API answers 422. The error says the body has unexpected fields. What is the most likely cause, and how do you fix it?
Show answer
The downloaded body still contains read-only fields such as id, source, created_at, updated_at, _links or current_user_can_bypass. Fix it by projecting only the writable fields before sending, for example with jq '{name, target, enforcement, bypass_actors, conditions, rules}'.
Exercise
After applying a new organisation ruleset, a developer says a push to main in one repository is blocked by a rule you did not expect. Which call shows which ruleset the rule comes from?
Show answer
GET /repos/{owner}/{repo}/rules/branches/main, for example gh api /repos/ORG/REPO/rules/branches/main --jq '.[] | {type, ruleset_source, ruleset_id}'. Each entry names the ruleset that contributes the rule, so you can open that ruleset and edit it.