Sub topic 15
Automating with the REST API and gh CLI
This chapter assumes you know how classic branch protection and rulesets work, and that you have admin access to a repository you can experiment in. You also need the gh CLI installed and authenticated with gh auth login.
Why automate
Clicking through settings does not scale. A JSON file in version control can be reviewed, reused across repositories, and re-applied when settings drift. The same endpoints that power the settings pages are available through the REST API, and gh api sends authenticated requests to them.
Classic branch protection
Classic protection is configured per branch with one PUT request that replaces the whole configuration. Save this body as protection.json:
{
"required_status_checks": {
"strict": true,
"checks": [{ "context": "build" }]
},
"enforce_admins": true,
"required_pull_request_reviews": {
"required_approving_review_count": 1,
"dismiss_stale_reviews": true,
"require_code_owner_reviews": true
},
"restrictions": null,
"allow_force_pushes": false,
"allow_deletions": false
}Then send it:
gh api --method PUT repos/OWNER/REPO/branches/main/protection --input protection.jsonReplace OWNER and REPO with your own values. The body must include required_status_checks, enforce_admins, required_pull_request_reviews, and restrictions. Use null for any of them you do not want. A null for restrictions means no push restrictions, which is the normal setting for repositories owned by a user.
Rulesets
Rulesets are created with POST to a collection endpoint, so each one is a separate object with its own ID. Save this as ruleset.json:
{
"name": "protect-default-branch",
"target": "branch",
"enforcement": "evaluate",
"bypass_actors": [],
"conditions": {
"ref_name": {
"include": ["~DEFAULT_BRANCH"],
"exclude": []
}
},
"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": false,
"require_last_push_approval": false,
"required_review_thread_resolution": true
}
},
{
"type": "required_status_checks",
"parameters": {
"strict_required_status_checks_policy": true,
"required_status_checks": [{ "context": "build" }]
}
}
]
}The ~DEFAULT_BRANCH value targets whatever the default branch is, so the file works even if the branch is named master or trunk. Because enforcement is evaluate, the ruleset only records what it would block. Run it for a while, review the results, and then switch to active.
Create the ruleset, then inspect what applies to main:
gh api --method POST repos/OWNER/REPO/rulesets --input ruleset.json
gh api repos/OWNER/REPO/rules/branches/mainThe second command lists the rules from all active rulesets that apply to main. Use it to check how rule sources combine. It does not include classic branch protection rules, so compare it with the protection endpoint when both exist.
Common errors
- 404 Not Found: the repository or branch does not exist, or your token lacks admin permission. GitHub returns 404 instead of 403 in some cases to avoid revealing private repositories.
- 422 Unprocessable Entity: the body is invalid. A common cause is a missing required key in the classic protection body.
- Check names that never report: a
contextthat no workflow produces leaves pull requests waiting forever. Use the exact job or check name.
Exercise
You send a classic protection PUT that contains only required_pull_request_reviews, and you get a 422 error. What is the likely cause, and what is the fix?
Show answer
The classic endpoint requires required_status_checks, enforce_admins, required_pull_request_reviews, and restrictions to be present. Add the missing keys, setting any you do not want to null, and send the request again.