【问题标题】:How to access the github API via requests in python?如何通过python中的请求访问github API?
【发布时间】:2021-02-02 09:32:11
【问题描述】:

我正在尝试通过 python 请求访问 github API(类似问题的答案 herehere 没有帮助)。

使用 curl,我可以获得项目最近提交的列表,例如

curl -H "Accept: application/vnd.github.inertia-preview+json Authorization: token a0d42faabef23ab5b5462394373fc133ca107890" https://api.github.com/repos/rsapkf/42/commit 

尝试在 python 中使用与我尝试使用的请求相同的设置

url = "https://api.github.com/repos/rsapkf/42/commits"
headers = {"Accept": "application/vnd.github.inertia-preview+json", "Authorization": "token a0d42faabef23ab5b5462394373fc133ca107890"}
r = requests.get(url, headers=headers)

还有

url = "https://api.github.com/repos/rsapkf/42/commits"
headers = {"Accept": "application/vnd.github.inertia-preview+json"}
my_username = "someuser"
my_token  = "a0d42faabef23ab5b5462394373fc133ca107890"
r = requests.get(url, headers=headers, auth=(my_username, my_token))

但在这两种情况下我都会得到响应

{'documentation_url': 'https://docs.github.com/rest',
 'message': 'Bad credentials'}

我在这里错过了什么?

【问题讨论】:

  • 无耻插件:我写了一个包,使使用 github API 更容易:cmustrudel.github.io/strudel.scraper
  • @Marat 谢谢你的建议,但它似乎不起作用。我收到一个错误requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url...
  • 你不能给一个令牌,那么它就起作用了!?!
  • 对于某些 API,例如要从您有权访问的私有存储库中读取,您必须使用 auth。此外,即使对于公共数据,未经身份验证的请求也仅限于每个 IP 每小时 60 个

标签: python github python-requests


【解决方案1】:

不需要身份验证。以下作品:

url = "https://api.github.com/repos/rsapkf/42/commits"
headers = {"Accept": "application/vnd.github.inertia-preview+json"}
r = requests.get(url, headers=headers)

【讨论】:

  • 它每小时只给你 60 个请求。原始代码中的问题是 my_username 应该是 token 而不是 someuser
猜你喜欢
  • 2022-10-17
  • 2019-04-09
  • 2017-08-22
  • 2019-11-11
  • 1970-01-01
  • 2021-04-13
  • 1970-01-01
  • 2019-02-20
  • 2012-09-29
相关资源
最近更新 更多