如何使用REST API在GitHub中获取文件的内容? 我正在尝试使用github api检索和下载文件中的文件内容,以模仿我如何使用Azure DevOps Rest API。 我的ADO URL是: https://dev.azure.com/

问题描述 投票:0回答:1
above的工作正常,如果我将其输入浏览器,它会立即下载

DEV1.yml

文件。 我正在尝试使用Github的

RestAPI

模仿此实现。我的URL看起来像:
https://api.github.com/repos/<Org>/<Repository>/contents/<Path to file>/DEV1.yml&download=true

这个github url在浏览器中不起作用,我认为这是因为存储库是私人的,我需要一个令牌。但是,当我使用卷发时:

curl -H "Authorization: Bearer <PAT>" https://api.github.com/repos/<Org>/<Repository>/contents/<Path to file>/DEV1.yml&download=true

这返回一个大型基本64编码的JSON对象。我试图将URL代替现有的ADO ONE,但失败了。 在上面的两个URL上不一样?

	
是的,这是不同的。

GITHUBREST API下载文件有两个步骤。

1,第一步是获取下载URL。

这样的URL格式:

https://api.github.com/repos/<Project Name>/<Repository Name>/contents/<File Name>

rest github curl azure-devops
1个回答
2
投票

2,第二步是使用下载URL获取文件内容。 这样的URL格式:

https://raw.githubusercontent.com/<Project Name>/<Repository Name>/main/<File Name>?token=<Random Token that related to Revision Version>

请注意,第一步无法跳过,否则您将无法获得修订令牌。 我可以使用Python来达到您的要求:
import requests

#Define required information
project_name = "xxx"
repository_name = "xxx"
# repository_name = "xxx"
branch_name = "xxx"
File_name = "xxx"
PAT = "xxx"
url = "https://api.github.com/repos/"+project_name+"/"+repository_name+"/contents/"+File_name

#downoad file from github
payload = {}
headers = {
    'Authorization': 'token '+PAT
}

#download file
file_content = requests.request("GET", ((requests.request("GET", url, headers=headers, data=payload)).json())['download_url'], headers=headers, data=payload)
print(file_content.text)

成功获取最新内容(我也基于私人存储库):

enter image description here

如果您想要一个原始文件,则只需要使用Accept

设置请求标题。只是一个步骤就足够了。

GITHUBAPI:

application/vnd.github.v3.raw

转到:

从脚本访问 /下载github文件的官方方法?


https://docs.github.com/en/rest/repos/contents

enter image description here

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.