How to install GitHub App using API
This guide will show you how to install a GitHub App using the GitHub API. This is useful for the situations where you need to install a GitHub App to a list of repositories.
This guide assumes that you have already created a GitHub App and have a Personal Access Token (PAT) with the necessary permissions.
In most cases it is much easier to install a GitHub App using the GH CLI, but there are situations where using the API is necessary. In my case it is due to some company policies that do not allow installing GitHub Apps using the GH CLI.
Prerequisites
Installed GH Cli and authenticated with your GitHub account. You can follow the instructions GH CLI to install GH CLI.
Created GitHub App and installed to at least one repository manually in the GitHub portal. How to create and install a GitHub App can be found in the GitHub documentation.
Steps to install GitHub App using API
Prepare a list of repositories
The easiest way of installing a GitHub App to multiple repositories is to prepare a list of repositories in a text file. Each line in the file should contain the full name of the repository. For example:
$ cat ./repos.txt
my-repo-1
my-repo-2
Save your GitHub Personal Access Token (PAT) in a temporary file
vim /tmp/token.txt
Don't forget to remove the temporary file after you are done with the installation.
Get the GitHub App ID
The fasted way to get the GitHub App ID is to go to the GitHub App settings page of the repository where you already installed the app and look at the URL.
https://<GHE_HOST>/<ORG_NAME>/<REPO_NAME>/settings/installations
In the list of installed GitHub Apps, click on the Configure button of the app you want to install to other repositories. The URL will change to something like this:
https://<GHE_HOST>/<ORG_NAME>/settings/installations/<INSTALLATION_ID>
Copy the <INSTALLATION_ID> from the URL. This is the GitHub App ID that you will use in the API request.
Install the GitHub App to the repositories
API="https://<GHE_HOST>/api/v3"
INSTALLATION_ID=<INSTALLATION_ID> # Don't forget to replace with your installation id
ORG="<ORG_NAME>" # Don't forget to replace with your organization name
REPOS=($(cat ./repos.txt)) # repos.txt should contain the list of repositories to which you want to install the app, one per line
TOKEN=$(cat /tmp/token.txt) # token.txt should contain a valid GitHub PAT with the necessary permissions to install the app
for repo in "${REPOS[@]}"; do
REPO_ID=$(curl -s \
-H "Authorization: Bearer $TOKEN" \
-H "Accept: application/vnd.github+json" \
"$API/repos/$ORG/$repo" | jq .id)
curl -s -o /dev/null -w "%{http_code} $repo" \
-X PUT \
-H "Authorization: Bearer $TOKEN" \
-H "Accept: application/vnd.github+json" \
"$API/user/installations/$INSTALLATION_ID/repositories/$REPO_ID"
done
If everything is correct, you should see a list of HTTP status codes and repository names. A status code of 204 means that the app was successfully installed to the repository.