Azure DevOps API-修补程序文档无效



我正在尝试使用PHP、Guzzle和Laravel连接到Azure Dev Ops API。我能够成功连接并获得以下代码的工作项:

Route::get('/getworkitem', function() {
$response = Http::withBasicAuth('Username', 'PAT')
->get('https://dev.azure.com/{Organisation}/{Project}/_apis/wit/workitems/32?fields=System.WorkItemType,System.AssignedTo&$expand=Links&api-version=5.1');
return $response;
});

我正在尝试使用Laravel HTTP客户端进行POST请求,以创建一个新的工作项,代码如下:

Route::get('/add', function() {
$requiredata = array (
'op' => 'add',
'path' => '/fields/System.Title',
'from' => null,
'value' => 'Sample Task'
);
$response = Http::withBasicAuth('Username', 'PAT')->withHeaders([
'Content-Type' => 'application/json-patch+json',
])->post('https://dev.azure.com/Oraganisation/{Project}/_apis/wit/workitems/$issue?api-version=5.1', [
'body' => json_encode($requiredata,JSON_UNESCAPED_SLASHES)
]);
dd(json_decode($response->getBody()));
});

然而,当我运行此程序时,我会得到以下响应:

+"$id": "1"
+"innerException": null
+"message": "You must pass a valid patch document in the body of the request."
+"typeName": "Microsoft.VisualStudio.Services.Common.VssPropertyValidationException, Microsoft.VisualStudio.Services.Common"
+"typeKey": "VssPropertyValidationException"
+"errorCode": 0
+"eventId": 3000

对我来说,这意味着响应正文中的"op"是不正确的,但当我检查时,它发送的信息是正确的。

然后我尝试通过Guzzle用以下内容完成请求:

Route::get('/add2', function() {
$headers = [
'Content-Type' => 'application/json-patch+json',
];
$body = [
'op' => 'add',
'path' => '/fields/System.Title',
'from' => null,
'value' => 'Sample Task'
];
$body = json_encode($body,JSON_UNESCAPED_SLASHES);
$client = new Client();
$res = $client->request('POST', 'https://dev.azure.com/{Organisation}/{Project}/_apis/wit/workitems/$Issue?api-version=5.1', [
'auth' => 'Username', 'Password'
], $headers, $body);
dd(json_decode($res->getBody()));
});

这将返回null。

我已经能够让POST请求在Postman中工作,但不能在PHP中工作。我浏览了谷歌,没有发现任何可以表明我做错了什么的东西,但如果有人能给我指明正确的方向,告诉我为什么它是GET而不是POST,那将不胜感激。

请尝试在请求正文之外添加[{}]

[
{
"op": "add",
"path": "/fields/System.Title",
"from": "null",
"value": "sample task"
}
]

Microsoft.VisualStudio.Services.Common.VssPropertyValidationException

此错误消息表示系统无法成功处理正文属性。正常情况下,用户必须发送具有正确属性的请求体,这样我们的系统才能成功读取。然后解析其内容,如'op''path'等。

尝试设置内容类型的编码。

ContentType "application/json-patch+json; charset=utf-8"

我对外国字符也有同样的问题

下面的代码是一个解决方案。

Route::get('/add_work_item',
function() {
$response = Http::withBasicAuth('{key}', '{PAT}')
->withHeaders(
[
'Content-Type' => 'application/json-patch+json'
]
)
->post('https://dev.azure.com/{Organisation}/{Project}/_apis/wit/workitems/$Task?api-version=5.1', 
[

[
'op' => 'add',
'path' => '/fields/System.Title',
'from' => null,
'value' => 'New Task'
],
[
'op'=> 'add',
'path'=> '/fields/System.AreaPath',
'from'=> null,
'value'=> '{Project}'
]
]
);
dd(json_decode($response->getBody()));
}
);

最新更新