我正在尝试使用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中工作。我遍历了Google,没有发现任何东西指向我做错了的事情,但是如果有人能够向我指出正确的方向,为什么它可以作为GET而不是POST来工作,将不胜感激。
答案 0 :(得分:0)
请尝试在请求正文之外添加 [{}] 。
[
{
"op": "add",
"path": "/fields/System.Title",
"from": "null",
"value": "sample task"
}
]
Microsoft.VisualStudio.Services.Common.VssPropertyValidationException
此错误消息表示系统无法成功处理body属性。通常,用户必须发送具有正确属性的请求正文,以便我们的系统能够成功读取。然后解析其内容,例如'op'
,'path'
等。
答案 1 :(得分:-1)
下面的代码是一个解决方案。
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()));
}
);