Srikar Karra
Srikar Karra

Reputation: 35

How to access GitHub API using personal access tokens in shell script?

how is it going?

So I used a bash script to create a remote repository using a password to access a endpoint like this:

NEWVAR="{\"name\":\"$githubrepo\",\"private\":\"true\"}"
curl -u $USERNAME https://api.github.com/user/repos -d "$NEWVAR"

However, GitHub is going to not allow developers to access endpoints using passwords anymore. So my question is how do I create a remote repository using a personal access token?

Upvotes: 2

Views: 5428

Answers (1)

Léa Gris
Léa Gris

Reputation: 19675

use --header to transmit authorization:

#!/usr/bin/env sh

github_user='The GitHub user name'
github_repo='The repository name'

github_oauth_token='The GitHub API auth token'

# Create the JSON data payload arguments needed to create
# a GitHub repository.
json_data="$(
  jq \
    --null-input \
    --compact-output \
    --arg name "$github_repo" \
    '{$name, "private":true}'
)"

if json_reply="$(
  curl \
    --fail \
    --request POST \
    --header 'Accept: application/vnd.github.v3+json' \
    --header "Authorization: token $github_oauth_token" \
    --header 'Content-Type: application/json' \
    --data "$json_data" \
    'https://api.github.com/user/repos'
)"; then
  # Save the JSON answer of the repository creation
  printf '%s' "$json_reply" >"$github_repo.json"
  printf 'Successfully created the repository: %s\n' "$github_repo"
else
  printf 'Could not create the repository: %s\n' "$github_repo" >&2
  printf 'The GitHub API replied with this JSON:\n%s\n' "$json_reply" >&2
fi

See my answer here for a featured implementation example: https://stackoverflow.com/a/57634322/7939871

Upvotes: 4

Related Questions