Sub topic 12
Managing rulesets as JSON with the REST API and gh
This chapter assumes you can read JSON, have used the gh CLI, and know what a ruleset's targets, rules, bypass actors and enforcement status are from earlier chapters. You will create, inspect, update and delete an organisation ruleset from the command line.
Why manage rulesets as JSON
The settings page is fine for one ruleset. Once you have several, JSON files in a repository give you review, history and repeatability. Each ruleset is one JSON document, and the REST API accepts that document as the request body.
The endpoints for an organisation are under /orgs/{org}/rulesets. Repository rulesets use /repos/{owner}/{repo}/rulesets and take the same body shape, minus the repository_name condition.
| Action | Method and path |
|---|---|
| List rulesets | `GET /orgs/{org}/rulesets` |
| Read one ruleset | `GET /orgs/{org}/rulesets/{ruleset_id}` |
| Create | `POST /orgs/{org}/rulesets` |
| Update | `PUT /orgs/{org}/rulesets/{ruleset_id}` |
| Delete | `DELETE /orgs/{org}/rulesets/{ruleset_id}` |
Creating, updating and deleting organisation rulesets requires admin rights on the organisation. If you use a token, it needs the matching organisation administration permission.
The shape of a ruleset body
A body combines the pieces you have already met:
name,target(branch,tagorpush) andenforcement(active,evaluateordisabled).bypass_actors, a list of actors and theirbypass_mode.conditions, which holdref_nameand, for organisation rulesets,repository_name.rules, a list of objects with atypeand, for most types,parameters.
This example targets the default branch of every repository except those named sandbox-*. It blocks deletion and force pushes, and requires one approving review. Repository admins can bypass it only through a pull request.
{
"name": "protect-default-branch",
"target": "branch",
"enforcement": "active",
"bypass_actors": [
{
"actor_id": 5,
"actor_type": "RepositoryRole",
"bypass_mode": "pull_request"
}
],
"conditions": {
"ref_name": {
"include": ["~DEFAULT_BRANCH"],
"exclude": []
},
"repository_name": {
"include": ["~ALL"],
"exclude": ["sandbox-*"]
}
},
"rules": [
{ "type": "deletion" },
{ "type": "non_fast_forward" },
{
"type": "pull_request",
"parameters": {
"required_approving_review_count": 1,
"dismiss_stale_reviews_on_push": true,
"require_code_owner_review": true,
"require_last_push_approval": false,
"required_review_thread_resolution": true
}
}
]
}Here actor_id 5 is the built-in repository admin role. ~DEFAULT_BRANCH and ~ALL are special values that the API accepts in place of name patterns.
Creating a ruleset with gh
Save the JSON as protect-default-branch.json, then send it with gh api. The --input flag uses the file as the request body.
gh api \
--method POST \
-H "Accept: application/vnd.github+json" \
/orgs/YOUR_ORG/rulesets \
--input protect-default-branch.jsonThe response contains the new ruleset's id. Keep it, because updates and deletes need it.
gh api /orgs/YOUR_ORG/rulesets --jq '.[] | {id, name, enforcement}'The list call returns a summary of each ruleset. Request a single ruleset by ID to see its full rules and conditions.
Adding a required workflow rule
A required workflow is one more entry in the rules array. It points at a workflow file in a repository, which must be identified by its numeric ID.
{
"type": "workflows",
"parameters": {
"do_not_enforce_on_create": false,
"workflows": [
{
"repository_id": 123456,
"path": ".github/workflows/org-ci.yml",
"ref": "refs/heads/main"
}
]
}
}Replace 123456 with your repository's ID. You can read it with gh api /repos/YOUR_ORG/YOUR_REPO --jq .id. The workflow itself must run on the pull_request or merge_group event, or the rule can never be satisfied.
Updating safely
PUT replaces the ruleset with the body you send. It is not a patch. The safest routine is to fetch the current document, edit it, and send it back.
- Run
gh api /orgs/YOUR_ORG/rulesets/ID > current.json. - Edit the file and remove read-only fields such as
id,source,source_type,created_at,updated_at,_linksandcurrent_user_can_bypass. - Send it with
gh api --method PUT /orgs/YOUR_ORG/rulesets/ID --input current.json.
Common errors
- 404 Not Found. The organisation name or ruleset ID is wrong, or your token lacks access. GitHub returns 404 for some permission failures.
- 422 Unprocessable Entity. The body is invalid. Typical causes are an unknown rule
type, a missingparametersobject, or atargetthat does not match the rule types. For example, push rules belong in a ruleset with targetpush. - Ruleset created but nothing is blocked. Check that
enforcementisactiveand that yourincludepatterns match the repository and branch.
Exercise
You fetched a ruleset with gh api, changed required_approving_review_count from 1 to 2, and sent it back with PUT. Why should you strip fields such as id and updated_at first, and what happens to parts of the ruleset you leave out of the body?
Show answer
Fields like id and updated_at are read-only values that the server generates, so they should not be in the request body. PUT replaces the whole ruleset, so any part left out of the body, such as bypass_actors or rules, can be removed. Send the complete edited document.