rest - 从 BitBucket Rest API v2.0 获取文件
问题描述
我有一个脚本,它使用 bitbucket REST API (1.0) 从 GIT 获取文件,但它最近停止工作。我推测这可能是由于 v1 REST API 被贬值,但我不确定。
无论如何,我正在尝试使用新的 2.0 REST API 检索文件,但由于请求不断失败,我似乎无法正确获取语法。
我从 curl 开始,因为它最容易测试。这就是我正在尝试的:
curl -u myusername@mydomain.com "https://api.bitbucket.org/2.0/repositories/MyCompany/myrepo/downloads/Scripts/Environment Setup/test.txt"
Enter host password for user 'myusername@mydomain.com': redacted
{"type": "error", "error": {"message": "Resource not found", "detail": "There is no API hosted at this URL.\n\nFor information about our API's, please refer to the documentation at: https://developer.atlassian.com/bitbucket/api/2/reference/"}}
也许我使用了错误的功能?我不确定。
解决方案
为了后代,您不想使用以下内容从 bitbucket 下载单个文件:
https://api.bitbucket.org/2.0/repositories/MyCompany/myrepo/downloads/path/to/your/file.txt
(“下载”是下载整个 repo 文件,如 .zip 文件)
相反,你想做:
curl --user myuser@mydomain.com:password "https://api.bitbucket.org/2.0/repositories/MyCompany/myrepo/src/master/path/to/file.txt"
如果您尝试使用 Invoke-RestRequest(在 powershell 中),请注意有一些额外的步骤。使用旧的 1.0 API,您可以:
$cred = Get-Credential
$uri = "https://api.bitbucket.org/1.0/repositories/MyCompany/$($filepath)"
# Get the files from bitbucket (GIT)
Invoke-RestMethod -Credential $cred -Uri $uri -Proxy $proxyUri -OutFile $destination
使用不再有效的新 2.0 API。Powershell 的 Invoke-RestMethod 在发送凭据之前等待 401 响应,而新的 2.0 bitbucket api 从不提供,因此永远不会发送凭据,从而导致 403 被禁止。
要解决这个问题,您必须使用以下丑陋的 hack 来强制 Invoke-RestMethod 在 Authorization 标头中立即发送凭据:
$cred = Get-Credential
$uri = "https://api.bitbucket.org/2.0/repositories/MyCompany/$($filepath)"
$username = ($cred.GetNetworkCredential()).username
$password = ($cred.GetNetworkCredential()).password
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username,$password)))
# Get the files from bitbucket (GIT)
Invoke-RestMethod -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} -Uri $uri -Proxy $proxyUri -OutFile $destination
希望这可以帮助其他人在未来!
感谢@Jim Redmond 的帮助。
推荐阅读
- css - 如何使模块 css 在 gatsby 应用程序中与 typescript 一起使用?
- android - Android从内部存储中打开图像意图
- python - 需要帮助将 html 解析为 python 数据框
- html - 如何使用带有线条边框的 CSS 在底部边框中添加小圆圈
- javascript - Firebase 云功能 - 连接错误
- azure-devops - Azure DevOps Repo 是否有任何 OData 查询?
- c++ - 为什么此代码在 visual-studio 2017 中不起作用?
- python-3.x - Bootstrap4 无法识别我有 python >= 3.5
- c# - 非静态类中的静态方法是否使其成为静态类c#
- bash - 将日志文件数据提取到 csv 文件中