【问题标题】:How to Access Github API using personal access tokens instead of a password using shell script如何使用个人访问令牌而不是使用 shell 脚本的密码来访问 Github API
【发布时间】:2020-12-15 11:25:17
【问题描述】:

进展如何?

所以我使用 bash 脚本创建了一个远程存储库,使用密码访问这样的端点:

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

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

【问题讨论】:

标签: bash github github-api


【解决方案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

【讨论】:

  • 所以我是一个初学者程序员,我以前从未使用过 API,所以我不太了解这段代码。话虽如此,我收到错误“curl:(22)请求的URL返回错误:400 Bad Request”。我该怎么办?我插入了所有数据,包括我的令牌和我想要调用我的 github 存储库的数据。
  • @SrikarKarra 我只能在这里帮助您解决您的身份验证问题。你没有提到你打算通过调用 GitHub 的 API 方法来完成什么。了解如何调用方法以及它给出的参数和 JSON 回复。我引导你到docs.github.com/en/rest
  • 这个脚本的主要目的是使用 bash 脚本创建一个远程仓库。我最初使用的密码验证效果很好,但是,GitHub 很快就会删除此功能。所以我正在尝试使用个人访问令牌。这是存储库github.com/Srikar-Karra/CTDIR。通过使用上面答案中提供的代码,我收到了 400 bad request 错误。那么你能想到一些可能的问题吗?
  • @SrikarKarra 我刚刚修复了创建调用所需的 GitHub API url。还通过在我的 GitHub 帐户上使用上面的脚本创建一个 testrepository 来测试它实际上是否有效。因此,它将成为您扩展它的完美工作基础。您需要具有 repo 范围的 GitHub API 令牌才能使用此令牌创建存储库。
猜你喜欢
  • 2014-07-02
  • 2021-10-19
  • 2021-01-13
  • 2019-12-18
  • 1970-01-01
  • 2021-12-27
  • 1970-01-01
  • 2021-09-30
  • 2021-09-04
相关资源
最近更新 更多