如何通过GitHub API获取文件

Tyl*_*ton 9 api github

我需要获取GitHub仓库中托管的文件的内容.我更愿意获得带有元数据的JSON响应.我用cURL尝试了很多网址,只得到了响应{"message":"Not Found"}.我只需要URL结构.如果重要,那就是来自GitHub上的一个组织.这是我认为应该工作但不是:

http://api.github.com/repos/<organization>/<repository>/git/branches/<branch>/<file>
Run Code Online (Sandbox Code Playgroud)

Jos*_*ush 34

此 GitHub API 页面提供了完整的参考。用于读取文件的 API 端点:

https://api.github.com/repos/{username}/{repository_name}/contents/{file_path}
Run Code Online (Sandbox Code Playgroud)
https://api.github.com/repos/{username}/{repository_name}/contents/{file_path}
Run Code Online (Sandbox Code Playgroud)
  • 考虑使用个人访问令牌
    • 速率限制(匿名每小时最多 60 个,经过身份验证的每小时最多 5,000 个)了解更多
    • 允许访问私有存储库中的文件
  • 响应中的文件内容是base64编码的字符串

使用curl、jq

通过curl和jq使用GitHub的API读取https://github.com/airbnb/javascript/blob/master/package.json :

curl https://api.github.com/repos/airbnb/javascript/contents/package.json | jq -r ".content" | base64 --decode
Run Code Online (Sandbox Code Playgroud)

使用Python

使用Python中的GitHub API读取https://github.com/airbnb/javascript/blob/master/package.json

{
  "encoding": "base64",
  "size": 5362,
  "name": "README.md",
  "content": "encoded content ...",
  "sha": "3d21ec53a331a6f037a91c368710b99387d012c1",
  ...
}
Run Code Online (Sandbox Code Playgroud)
  • GITHUB_TOKEN运行前定义环境变量

  • 注意:要直接获取内容而不是 Base64 版本,请传递 `'Accept: application/vnd.github.v3.raw'` 请求标头: `curl -H 'Accept: application/vnd.github.v3.raw' ' https://api.github.com/repos/airbnb/javascript/contents/package.json'` (无需通过管道传输到 `| jq -r ".content" | base64 --decode`)。 (6认同)

小智 15

正如描述(位于http://developer.github.com/v3/repos/contents/)所说:

/回购/:所有者/:回购/​​内容/:路径

ajax代码将是:

$.ajax({
    url: readme_uri,
    dataType: 'jsonp',
    success: function(results)
    {
        var content = results.data.content;
    });
Run Code Online (Sandbox Code Playgroud)

用适当的/ repos /:owner /:repo/contents /:path替换readme_uri.

  • @taseenb使用`https://raw.githubusercontent.com/:owner /:repo/master /:path`来获取原始(二进制,而不是Base64) (12认同)
  • 您可以通过将“Accept”标头设置为“application/vnd.github.v3.raw”来请求原始内容 (5认同)
  • 看起来GitHub正在发送用Base64编码的文件内容...... (2认同)