提问者:小点点

如何使用外壳脚本中的个人访问令牌访问GitHubAPI?


进展如何?

因此,我使用bash脚本使用密码创建远程存储库以访问如下endpoint:

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

但是,GitHub将不再允许开发人员使用密码访问endpoint。所以我的问题是如何使用个人访问令牌创建远程存储库?


共1个答案

匿名用户

使用--header传输授权:

#!/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

请参阅我的答案,了解一个特色实现示例:https://stackoverflow.com/a/57634322/7939871