Using GitHub API with Personal Access Token

Create a personal access token first.

Add to .bashrc or .zshrc if necessary.

$ export GITHUB_TOKEN=xxxxxxxxxxxxxxxxxxx

Get User Info

$ curl -X GET -u $GITHUB_TOKEN:x-oauth-basic 'https://api.github.com/user' 

Check if branch exists

$ owner=myuser
$ repo=myrepo
$ branch=mybranch

$ curl -X GET -u $GITHUB_TOKEN:x-oauth-basic https://api.github.com/repos/${owner}/${repo}/branches/${branch}

Get commit SHA for a branch

$ curl -s -X GET -u $GITHUB_TOKEN:x-oauth-basic https://api.github.com/repos/${owner}/${repo}/branches/${branch} | jq -r .commit.sha
 cadedac326275c11e02c1d7c30cf1b87e2f5a114
get_commit_sha() {
  local owner=$1
  local repo=$2
  local branch=$3
  local apiurl="https://api.github.com/repos/${owner}/${repo}/branches/${branch}"
  local sha=$(curl -s -X GET -u $GITHUB_TOKEN:x-oauth-basic ${apiurl} | jq -r '.commit.sha')
  echo ${sha}
  if [[ ${sha} == "null" ]]; then
    return 1
  fi
}

get_commit_sha ninegene bootstrap main
get_commit_sha ninegene bootstrap refs/heads/main

if get_commit_sha ninegene bootstrap refs/heads/main >/dev/null; then
  echo "refs/heads/dev exists!"
fi

if ! get_commit_sha ninegene bootstrap refs/heads/dummy >/dev/null; then
  echo "refs/heads/dummy doesn't exists!"
fi

Leave a Comment

Your email address will not be published.

3 × 4 =