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 '' 

Check if branch exists

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

$ curl -X GET -u $GITHUB_TOKEN:x-oauth-basic${owner}/${repo}/branches/${branch}

Get commit SHA for a branch

$ curl -s -X GET -u $GITHUB_TOKEN:x-oauth-basic${owner}/${repo}/branches/${branch} | jq -r .commit.sha
get_commit_sha() {
  local owner=$1
  local repo=$2
  local branch=$3
  local apiurl="${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

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!"

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

Leave a Comment

Your email address will not be published. Required fields are marked *