首页 > 解决方案 > 如何使用 REST Api 从本地 TFS 服务器 2018 获取多个提交?

问题描述

考虑GetCommits API。它有一个可选参数searchCriteria.ids,即提交 ID 列表。

但是如何通过这个列表呢?例如,我有 2 个提交 A 和 B。我试过:

  1. 甲,乙
  2. AB
  3. [A,B]

我得到的回应是:

An object ID must be 40 characters long and only have hex digits. Passed in object ID: 0533232917cc37fb743d282c467eb41bafac15ee,063a6805640221285db15f75c3b3ca6f3fe619c

对于所有三个变体,我得到相同的响应 - 只有报告的对象 ID 不同。

那么,如何在 GET 请求中将数组传递给 Azure Devops REST Api?

我使用powershell。声明很简单Invoke-RestMethod -UseDefaultCredentials -Uri $Url

变体 1 - 使用逗号

http://tfsserver:8080/tfs/defaultcollection/code/_apis/git/repositories/xyz/commits?api-version=4.1&searchCriteria.ids=0533232917cc37fb743d282c467eb41bafac15ee,063a6805640221285db15f75c3b3ca6f3fe619c0

结果是

{"$id":"1","innerException":null,"message":"An object ID must be 40 characters long and only have hex digits. Passed in object ID: 0533232917cc37fb743d282c467eb41bafac15ee,063a6805640221285db15f75c3b3ca6f3fe619c0.","typeName":"System.ArgumentException, mscorlib","typeKey":"ArgumentException","errorCode":0,"eventId":0}

变体 2 - 使用空间

http://tfsserver:8080/tfs/defaultcollection/code/_apis/git/repositories/xyz/commits?api-version=4.1&searchCriteria.ids=0533232917cc37fb743d282c467eb41bafac15ee%20063a6805640221285db15f75c3b3ca6f3fe619c0

导致同样的错误。

变体 3 - 使用 JavaScript 数组 [,]

http://tfsserver:8080/tfs/defaultcollection/code/_apis/git/repositories/xyz/commits?api-version=4.1&searchCriteria.ids=[0533232917cc37fb743d282c467eb41bafac15ee,063a6805640221285db15f75c3b3ca6f3fe619c0]

同样的错误。

当我只通过一个没有任何额外符号的提交时,它确实有效。

在此处输入图像描述

使用in代替=

有一个建议使用 'in' 而不是 '='。这确实接受逗号,但似乎无法正常工作。请注意:

在此处输入图像描述

因此,使用 '=' 会产生一个提交 - 正如预期的那样。但是使用'in'会产生100?我尝试传递两个用逗号分隔的提交,它没有失败,但也返回 100 个提交。这是错误的。

标签: gitrestpowershellazure-devops

解决方案


根据我的测试,逗号方式适用于其余 API。下面是使用Powershell代码的demo和测试结果,大家可以参考。我使用 Azure Devops API 对其进行测试。

如果 id 之间有空格,我也可以重现您提到的问题。

$pat = "PATToken"
$organization = "organization name"
$project = "project Id"
$repositoryId = "repository Id"
$ids = "266295d9adbxxx,f345970123bxxxx" # Ids of commits
$apiUrl= "https://dev.azure.com/$organization/$project/_apis/git/repositories/$repositoryId/commits?searchCriteria.ids=$ids&api-version=5.0-preview.1"

$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f "", $pat)))

$Result = Invoke-RestMethod -Uri $apiUrl -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}  -Method GET 

foreach($item in $Result.value)
{
  Write-Host "$item"
  Write-Host "---------------"
}

注意:我也尝试使用 API 4.1 版本对其进行测试,它也在我这边工作。

测试结果:

在此处输入图像描述

更新

如果我使用 TFS API,我还可以使用我提到的代码重现您提到的问题。

我可以通过以下方式得到结果。请尝试使用in to 代替"="

以下是我的测试代码:

$ids = '0cc4e954c082372379xxxx','9b5983436c2f81b5fae6a72xxx'

$apiUrl= "http://$tfsserver:8080/tfs/$organization/$project/_apis/git/repositories/$repositoryId/commits?searchCriteria.ids in $ids&api-version=4.1"

测试结果:

在此处输入图像描述


推荐阅读